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
5ddd0dcee13d445c1c8ced2b0a3fc1e14cdcddea
648
module Support module Messages module Outlook module Reply class FileAttachment def self.from_uploaded_file(http_uploaded_file) new(file: http_uploaded_file.tempfile, name: http_uploaded_file.original_filename) end attr_reader :file, :name def initialize(file:, name:) @file = file @name = name end def content_bytes file.rewind Base64.encode64(file.read) end def content_type Rack::Mime.mime_type(File.extname(file)) end end end end end end
21.6
94
0.560185
f800f415bd2d94a37e76218d925d67f182a8b313
1,736
# == Schema Information # # Table name: web_hooks # # id :integer not null, primary key # url :string(255) # project_id :integer # created_at :datetime # updated_at :datetime # type :string(255) default("ProjectHook") # service_id :integer # push_events :boolean default(TRUE), not null # issues_events :boolean default(FALSE), not null # merge_requests_events :boolean default(FALSE), not null # tag_push_events :boolean default(FALSE) # note_events :boolean default(FALSE), not null # require "spec_helper" describe ServiceHook, models: true do describe "Associations" do it { is_expected.to belong_to :service } end describe "execute" do before(:each) do @service_hook = create(:service_hook) @data = { project_id: 1, data: {} } WebMock.stub_request(:post, @service_hook.url) end it "POSTs to the webhook URL" do @service_hook.execute(@data) expect(WebMock).to have_requested(:post, @service_hook.url).with( headers: { 'Content-Type'=>'application/json', 'X-Gitlab-Event'=>'Service Hook' } ).once end it "POSTs the data as JSON" do @service_hook.execute(@data) expect(WebMock).to have_requested(:post, @service_hook.url).with( headers: { 'Content-Type'=>'application/json', 'X-Gitlab-Event'=>'Service Hook' } ).once end it "catches exceptions" do expect(WebHook).to receive(:post).and_raise("Some HTTP Post error") expect { @service_hook.execute(@data) }.to raise_error(RuntimeError) end end end
31.563636
89
0.604263
626d61f1ab94c035316a541dd843b90c2a0860ab
1,727
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "carrot" s.version = "1.2.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Amos Elliston"] s.date = "2011-10-20" s.description = "A synchronous version of the ruby amqp client" s.email = "[email protected]" s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ "LICENSE", "README.markdown", "Rakefile", "VERSION.yml", "carrot.gemspec", "lib/carrot.rb", "lib/carrot/amqp/buffer.rb", "lib/carrot/amqp/exchange.rb", "lib/carrot/amqp/frame.rb", "lib/carrot/amqp/header.rb", "lib/carrot/amqp/protocol.rb", "lib/carrot/amqp/queue.rb", "lib/carrot/amqp/server.rb", "lib/carrot/amqp/spec.rb", "lib/examples/simple_pop.rb", "protocol/amqp-0.8.json", "protocol/amqp-0.8.xml", "protocol/codegen.rb", "protocol/doc.txt", "test/buffer_test.rb", "test/carrot_test.rb", "test/frame_test.rb", "test/protocol_test.rb", "test/test_helper.rb" ] s.homepage = "http://github.com/famoseagle/carrot" s.require_paths = ["lib"] s.rubygems_version = "1.8.11" s.summary = "A synchronous version of the ruby amqp client" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<mocha>, [">= 0"]) else s.add_dependency(%q<mocha>, [">= 0"]) end else s.add_dependency(%q<mocha>, [">= 0"]) end end
27.412698
105
0.639259
188b265f0f30a41014783aaf95f1f366d5eebfe1
532
class Api::V4::SegmentSerializer < Api::V4::ApplicationSerializer attributes :id, :name, :segment_number, :realtime_start_ms, :realtime_end_ms, :realtime_duration_ms, :realtime_shortest_duration_ms, :realtime_gold, :realtime_reduced, :realtime_skipped, :gametime_start_ms, :gametime_end_ms, :gametime_duration_ms, :gametime_shortest_duration_ms, :gametime_gold, :gametime_reduced, :gametime_skipped has_many :histories, serializer: Api::V4::SegmentHistorySerializer end
53.2
106
0.740602
015871889a5b2fbe3f047e4d16581d6ca30f718b
1,088
# frozen_string_literal: true require File.join(File.dirname(__FILE__), 'lib', 'jsonpath', 'version') Gem::Specification.new do |s| s.name = 'jsonpath' s.version = JsonPath::VERSION s.required_ruby_version = '>= 2.5' s.authors = ['Joshua Hull', 'Gergely Brautigam'] s.summary = 'Ruby implementation of http://goessner.net/articles/JsonPath/' s.description = 'Ruby implementation of http://goessner.net/articles/JsonPath/.' s.email = ['[email protected]', '[email protected]'] s.extra_rdoc_files = ['README.md'] s.files = `git ls-files`.split("\n") s.homepage = 'https://github.com/joshbuddy/jsonpath' s.test_files = `git ls-files`.split("\n").select { |f| f =~ /^spec/ } s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) } s.licenses = ['MIT'] # dependencies s.add_runtime_dependency 'multi_json' s.add_development_dependency 'bundler' s.add_development_dependency 'code_stats' s.add_development_dependency 'minitest', '~> 2.2.0' s.add_development_dependency 'phocus' s.add_development_dependency 'rake' end
38.857143
82
0.701287
6a8a4ea61339757c2e4f42d0e9b3c9f9bb209ebe
1,679
Gem::Specification.new do |s| s.name = 'squcumber-postgres' s.version = '0.0.5' s.default_executable = 'squcumber-postgres' s.licenses = ['MIT'] s.required_ruby_version = '>= 2.0' s.required_rubygems_version = Gem::Requirement.new('>= 0') if s.respond_to? :required_rubygems_version= s.authors = ['Stefanie Grunwald'] s.date = %q{2018-09-05} s.email = %q{[email protected]} s.files = [ 'Rakefile', 'lib/squcumber-postgres.rb', 'lib/squcumber-postgres/mock/database.rb', 'lib/squcumber-postgres/step_definitions/common_steps.rb', 'lib/squcumber-postgres/support/database.rb', 'lib/squcumber-postgres/support/matchers.rb', 'lib/squcumber-postgres/support/output.rb', 'lib/squcumber-postgres/rake/task.rb' ] s.test_files = [ 'spec/spec_helper.rb', 'spec/squcumber-postgres/mock/database_spec.rb' ] s.homepage = %q{https://github.com/moertel/sQucumber-postgres} s.require_paths = ['lib'] s.rubygems_version = %q{1.6.2} s.summary = %q{Define and execute SQL integration tests for Postgres databases} s.add_runtime_dependency 'pg', ['>= 0.16', '< 1.0'] s.add_runtime_dependency 'cucumber', ['>= 2.0', '< 3.0'] s.add_runtime_dependency 'rake', ['>= 10.1', '< 12.0'] s.add_development_dependency 'rspec', ['>= 3.1', '< 4.0'] s.add_development_dependency 'rspec-collection_matchers', ['>= 1.1.2', '< 2.0'] s.add_development_dependency 'codeclimate-test-reporter', ['>= 0.4.3', '< 1.0'] if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.0.0') then else end else end end
34.979167
105
0.664086
bf8012b9ea79c1f51392e7e286c25afcfc6daedc
1,019
require('keen/arguments/ArgumentParser') require('keen/arguments/ArgumentType') module Keen module TaskInvoker def self.invoke(clazz, command, args) obj = clazz.new() if (!obj.respond_to?(command)) raise ArgumentError.new("Task class #{clazz} does not contain a command '#{command}'") end parsedArgs = Keen::ArgumentParser.parse(args) meta = clazz::get_args(command) meta.arguments.each() do |key, arg| matched = false if (arg.type == ArgumentType::POSITIONAL) if (parsedArgs.has_key?(arg.position)) matched = true arg.value = parsedArgs[arg.position].value end else # options and opt-args are not required matched = true arg.getAliases().each() do |argAlias| if (parsedArgs.has_key?(argAlias)) arg.value = parsedArgs[argAlias].value end end end if (!matched) raise ArgumentError.new("Unmatched required argument '#{arg.symbol}'") end end return obj.send(command, meta) end end end
20.795918
90
0.65947
18c41b4060bff5acc7e42ff8af5a79e1e662508b
1,270
require 'spec_helper' require 'napa/middleware/request_stats' describe Napa::Middleware::RequestStats do before do # Delete any prevous instantiations of the emitter and set valid statsd env vars Napa::Stats.emitter = nil ENV['STATSD_HOST'] = 'localhost' ENV['STATSD_PORT'] = '8125' end it 'should increment api_requests counter' do Napa::Stats.emitter.should_receive(:increment).with(Napa::Identity.name + ".http.get." + "test.path.requests") app = lambda { |env| [200, { 'Content-Type' => 'application/json' }, Array.new] } middleware = Napa::Middleware::RequestStats.new(app) env = Rack::MockRequest.env_for('/test/path') middleware.call(env) end it 'should send the api_response_time' do Napa::Stats.emitter.should_receive(:timing).with( Napa::Identity.name + ".http.get." + "test.path.response_time", an_instance_of(Float) ) app = lambda { |env| [200, { 'Content-Type' => 'application/json'}, Array.new] } middleware = Napa::Middleware::RequestStats.new(app) env = Rack::MockRequest.env_for('/test/path') middleware.call(env) end end
39.6875
117
0.608661
f8ae55610e122336a52e43cdf31311de6d7dcc6e
1,775
# encoding: utf-8 class AvatarUploader < CarrierWave::Uploader::Base # Include RMagick or MiniMagick support: # include CarrierWave::RMagick include CarrierWave::MiniMagick # Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility: # include Sprockets::Helpers::RailsHelper # include Sprockets::Helpers::IsolatedHelper # Choose what kind of storage to use for this uploader: # storage :file storage :fog # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end # Provide a default URL as a default if there hasn't been a file uploaded: # def default_url # # For Rails 3.1+ asset pipeline compatibility: # # asset_path("fallback/" + [version_name, "default.png"].compact.join('_')) # # "/images/fallback/" + [version_name, "default.png"].compact.join('_') # end # Process files as they are uploaded: # process :scale => [200, 300] # # def scale(width, height) # # do something # end version :avatar do process :resize_to_fill => [50, 50] end version :medium do process :resize_to_fill => [150, 150] end # Create different versions of your uploaded files: # version :thumb do # process :scale => [50, 50] # end # Add a white list of extensions which are allowed to be uploaded. # For images you might use something like this: def extension_white_list %w(jpg jpeg gif png) end # Override the filename of the uploaded files: # Avoid using model.id or version_name here, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename # end end
27.734375
81
0.696901
e224f9a0f016710ce8b4932422775d4b9d88a3eb
1,047
module Fog module Parsers module Redshift module AWS class DescribeEvents < Fog::Parsers::Base # :marker - (String) # :events - (Array) # :source_identifier - (String) # :source_type - (String) # :message - (String) # :date - (Time) def reset @response = { 'Events' => [] } end def start_element(name, attrs = []) super case name when 'Events' @event = {} end end def end_element(name) super case name when 'Marker' @response[name] = value when 'SourceIdentifier', 'SourceType', 'Message' @event[name] = value when 'Date' @event[name] = Time.parse(value) when 'Event' @response['Events'] << {name => @event} @event = {} end end end end end end end
23.795455
60
0.424069
1af564a0258adf14b4008dea6d4bc5deb5e7a4ae
1,121
cask 'tableau' do version '2020.2.1' sha256 '8437d0fd125cdc76849adef9fffec0dbe162445d549811246d2f333cacc13db9' url "https://downloads.tableau.com/tssoftware/TableauDesktop-#{version.dots_to_hyphens}.dmg" appcast 'https://macupdater.net/cgi-bin/check_urls/check_url_redirect.cgi?url=https://www.tableau.com/downloads/desktop/mac', configuration: version.dots_to_hyphens name 'Tableau Desktop' homepage 'https://www.tableau.com/products/desktop/download' depends_on macos: '>= :yosemite' pkg 'Tableau Desktop.pkg' uninstall pkgutil: [ 'com.amazon.redshiftodbc', 'simba.sparkodbc', 'com.simba.sparkodbc', 'com.simba.sqlserverodbc', 'com.tableausoftware.Desktop.app', 'com.tableausoftware.DesktopShortcut', 'com.tableausoftware.FLEXNet.11.*', 'com.tableausoftware.mysql', 'com.tableausoftware.oracle', 'com.tableausoftware.postgresql', ] end
40.035714
127
0.601249
61aa5bef75ccf5ddc4f74b435a18c8b58280603b
1,535
module SessionsHelper # Logs in the given user. def log_in(user) session[:user_id] = user.id end # Remembers a user in a persistent session. def remember(user) user.remember cookies.permanent.signed[:user_id] = user.id cookies.permanent[:remember_token] = user.remember_token end # Returns true if the given user is the current user. def current_user?(user) user == current_user end # Returns the user corresponding to the remember token cookie. def current_user if (user_id = session[:user_id]) @current_user ||= User.find_by(id: user_id) elsif (user_id = cookies.signed[:user_id]) user = User.find_by(id: user_id) if user && user.authenticated?(cookies[:remember_token]) log_in user @current_user = user end end end # Returns true if the user is logged in, false otherwise. def logged_in? !current_user.nil? end # Forgets a persistent session. def forget(user) user.forget cookies.delete(:user_id) cookies.delete(:remember_token) end # Logs out the current user. def log_out forget(current_user) session.delete(:user_id) @current_user = nil end # Redirects to stored location (or to the default). def redirect_back_or(default) redirect_to(session[:forwarding_url] || default) session.delete(:forwarding_url) end # Stores the URL trying to be accessed. def store_location session[:forwarding_url] = request.original_url if request.get? end end
23.984375
67
0.686645
1801afd20059f509c64ba7706842c86af06e53b5
1,285
require 'test_helper' class ProductPartsControllerTest < ActionDispatch::IntegrationTest setup do @product_part = product_parts(:one) end test "should get index" do get product_parts_url assert_response :success end test "should get new" do get new_product_part_url assert_response :success end test "should create product_part" do assert_difference('ProductPart.count') do post product_parts_url, params: { product_part: { part_id: @product_part.part_id, product_id: @product_part.product_id } } end assert_redirected_to product_part_url(ProductPart.last) end test "should show product_part" do get product_part_url(@product_part) assert_response :success end test "should get edit" do get edit_product_part_url(@product_part) assert_response :success end test "should update product_part" do patch product_part_url(@product_part), params: { product_part: { part_id: @product_part.part_id, product_id: @product_part.product_id } } assert_redirected_to product_part_url(@product_part) end test "should destroy product_part" do assert_difference('ProductPart.count', -1) do delete product_part_url(@product_part) end assert_redirected_to product_parts_url end end
26.22449
141
0.752529
1c946c7eb81abf37bbbe65731bae95522c072795
50
# 版本 module Fibman VERSION = "2.0.6".freeze end
10
26
0.66
26a32edbcd65fe6889162a1ae4c7fdcd4c6286f7
172
class CreateBoardcategories < ActiveRecord::Migration[5.0] def change create_table :boardcategories do |t| t.string :name t.timestamps end end end
17.2
58
0.69186
26daefc11344db5413ca9fa97a972c3ca91828e2
2,340
require 'spec_helper' describe HackerNewsRanking do it 'has a version number' do expect(HackerNewsRanking::VERSION).not_to be nil end context 'class method' do describe '#configure' do let(:configuration) { HackerNewsRanking::Configuration.configuration } it 'returns defaults' do expect(configuration).to( include( timestamp: :created_at, gravity: 1.8, points_offset: -1, timestamp_offset: 2, scope_method: :trending, current_rank_method: :rank ) ) end it 'saves the passed configuration' do HackerNewsRanking.configure do points :comments_count timestamp :commented_at gravity 2.3 points_offset 0 timestamp_offset 3 scope_method :controversial current_rank_method :points end expect(configuration).to( include( points: :comments_count, timestamp: :commented_at, gravity: 2.3, points_offset: 0, timestamp_offset: 3, scope_method: :controversial, current_rank_method: :points ) ) end end context 'ranking methods' do let(:array) { (1..4).to_a } describe '#rank' do let(:sorted_array) do HackerNewsRanking.rank( array: array, points: proc { 100 }, timestamp: -> (number) { 5 - number }, gravity: 5 ) end it 'sorts the array' do expect(sorted_array).to eq([4, 3, 2, 1]) end it 'returns a different array from the one passed to it' do expect(sorted_array).not_to be(array) end end describe '#rank!' do let(:sorted_array) do HackerNewsRanking.rank!( array: array, points: proc { 100 }, timestamp: -> (number) { 5 - number }, gravity: 5 ) end it 'sorts the array' do expect(sorted_array).to eq([4, 3, 2, 1]) end it 'returns the same array as the one passed to it' do expect(sorted_array).to be(array) end end end end context 'instance method' do end end
24.375
76
0.536325
910702349f3ac42e755879ae5720cd8bc036add5
2,738
class Znc < Formula desc "Advanced IRC bouncer" homepage "https://wiki.znc.in/ZNC" url "https://znc.in/releases/archive/znc-1.8.2.tar.gz" sha256 "ff238aae3f2ae0e44e683c4aee17dc8e4fdd261ca9379d83b48a7d422488de0d" license "Apache-2.0" revision 1 bottle do sha256 arm64_big_sur: "a4fb4117aeb8ffc30b301d9f030b4c7b52103fbd79c6b69e336bd5ce966f7e3a" sha256 big_sur: "3ee6a7b433414a20d4497d267711ae787f1f0c985e89f40352ae0e8db8fd7a6e" sha256 catalina: "0968a0d12ce30428023911e4074b276b1d5e80f689fabf5cdb4ff72a3f57e721" sha256 mojave: "476fe82c16953d5e0645f59128e8dd86cb1cba86bb798a483d2b3ef394b8e28e" sha256 high_sierra: "512c83a43b82c84dc773a603e3ccc21f1f315fd8bcef1e259cc4a50c46359e2e" sha256 x86_64_linux: "745a7581baa89cca0f4eb52982d22d189da5482ba65edf16e41e2d3501701b08" end head do url "https://github.com/znc/znc.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end depends_on "pkg-config" => :build depends_on "icu4c" depends_on "[email protected]" depends_on "[email protected]" uses_from_macos "zlib" def install ENV.cxx11 # These need to be set in CXXFLAGS, because ZNC will embed them in its # znc-buildmod script; ZNC's configure script won't add the appropriate # flags itself if they're set in superenv and not in the environment. ENV.append "CXXFLAGS", "-std=c++11" ENV.append "CXXFLAGS", "-stdlib=libc++" if ENV.compiler == :clang on_linux do ENV.append "CXXFLAGS", "-I#{Formula["zlib"].opt_include}" ENV.append "LIBS", "-L#{Formula["zlib"].opt_lib}" end system "./autogen.sh" if build.head? system "./configure", "--prefix=#{prefix}", "--enable-python" system "make", "install" end plist_options manual: "znc --foreground" def plist <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/znc</string> <string>--foreground</string> </array> <key>StandardErrorPath</key> <string>#{var}/log/znc.log</string> <key>StandardOutPath</key> <string>#{var}/log/znc.log</string> <key>RunAtLoad</key> <true/> <key>StartInterval</key> <integer>300</integer> </dict> </plist> EOS end test do mkdir ".znc" system bin/"znc", "--makepem" assert_predicate testpath/".znc/znc.pem", :exist? end end
32.211765
108
0.659606
39a1a6d55e3021b125b438b7deeacda238d7e6a2
392
# typed: strong # Be sure to restart your server when you modify this file. # Add new inflection rules using the following format # (all these examples are active by default): # ActiveSupport::Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end
32.666667
59
0.704082
f8ca3da4d3ea67f28f0c46df948f805b4f23f3b0
231
module ExceptionHandler extend ActiveSupport::Concern class HubspotError < StandardError; end included do rescue_from HubspotError do |error| @error = error render template: 'events/index' end end end
17.769231
41
0.714286
e2d78c0493966e47d82f6f3273e4b727e2978644
344
module Hyperstack def self.deprecation_warning(name, message) return if env.production? @deprecation_messages ||= [] message = "Warning: Deprecated feature used in #{name}. #{message}" return if @deprecation_messages.include? message @deprecation_messages << message `console.warn.apply(console, [message])` end end
31.272727
71
0.718023
f8208c97468867a30276bdc289eafba65d206e06
309
Deface::Override.new(:virtual_path => 'spree/orders/_line_item', :name => 'escape_variant_description_with_html_safe', :replace => "erb[loud]:contains('line_item_description(variant)')", :erb => '<%= line_item_description(variant).html_safe %>')
61.8
88
0.598706
e891e7ce0476e1e04e093028ce6f59914964ab55
240
module Dandelion module Adapter class NoOpAdapter < Adapter::Base def read(path) end def write(path, data) end def delete(path) end def symlink(path, data) end end end end
14.117647
37
0.558333
f8ca6f84f3fe3f9f4f089181453d4e3dac534000
2,827
module AdminData class ActiveRecordUtil attr_accessor :klass def initialize(klass) @klass = klass end # class User # has_and_belongs_to_many :clubs # end # # ActiveRecordUtil.new(User).declared_habtm_association_names # #=> ['clubs'] def declared_habtm_association_names delcared_association_names_for(:has_and_belongs_to_many).map(&:name).map(&:to_s) end # class User # belongs_to :club # end # # ActiveRecordUtil.new(User).declared_belongs_to_association_names # #=> ['club'] def declared_belongs_to_association_names delcared_association_names_for(:belongs_to).map(&:name).map(&:to_s) end # class User # has_one :car # end # # ActiveRecordUtil.new(User).declared_has_one_association_names # #=> ['car'] def declared_has_one_association_names delcared_association_names_for(:has_one).map(&:name).map(&:to_s) end # class User # has_many :cars # end # # ActiveRecordUtil.new(User).declared_has_many_association_names # #=> ['cars'] def declared_has_many_association_names delcared_association_names_for(:has_many).map(&:name).map(&:to_s) end # returns an array of classes # # class User # has_and_belongs_to_many :clubs # end # # ActiveRecordUtil.new(User).habtm_klasses_for # #=> [Club] def habtm_klasses_for declared_habtm_association_names.map do |assoc_name| klass_for_association_type_and_name(:has_and_belongs_to_many, assoc_name) end end # returns a class or nil # # class User # has_many :comments # end # # ActiveRecordUtil.new(User).klass_for_association_type_and_name(:has_many, 'comments') # #=> Comment # def klass_for_association_type_and_name(association_type, association_name) data = klass.name.camelize.constantize.reflections.values.detect do |value| value.macro == association_type && value.name.to_s == association_name end data.klass if data # output of detect from hash is an array with key and value end # returns false if the given Klass has no association info. Otherwise returns true. def has_association_info? declared_belongs_to_association_names.any? || declared_has_many_association_names.any? || declared_has_many_association_names.any? || declared_habtm_association_names.any? end private # returns declared association names like # # #=> ['comments'] # #=> ['positive_comments'] # #=> ['negative_comments'] def delcared_association_names_for(association_type) klass.name.camelize.constantize.reflections.values.select do |value| value.macro == association_type end end end end
27.446602
91
0.683056
0387ce8d39ad46eb23b24b64522e3e6a24860b1e
1,467
{ matrix_id: '2019', name: 'ch6-6-b3', group: 'JGD_Homology', description: 'Simplicial complexes from Homology from Volkmar Welker.', author: 'V. Welker', editor: 'J.-G. Dumas', date: '2008', kind: 'combinatorial problem', problem_2D_or_3D: '0', num_rows: '5400', num_cols: '2400', nonzeros: '21600', num_explicit_zeros: '0', num_strongly_connected_components: '1', num_dmperm_blocks: '1', structural_full_rank: 'true', structural_rank: '2400', pattern_symmetry: '0.000', numeric_symmetry: '0.000', rb_type: 'integer', structure: 'rectangular', cholesky_candidate: 'no', positive_definite: 'no', notes: 'Simplicial complexes from Homology from Volkmar Welker. From Jean-Guillaume Dumas\' Sparse Integer Matrix Collection, http://ljk.imag.fr/membres/Jean-Guillaume.Dumas/simc.html http://www.mathematik.uni-marburg.de/~welker/ Filename in JGD collection: Homology/ch6-6.b3.5400x2400.sms ', norm: '4.242641e+00', min_singular_value: '2.414724e-16', condition_number: '17569877663081696', svd_rank: '1985', sprank_minus_rank: '415', null_space_dimension: '415', full_numerical_rank: 'no', svd_gap: '210347336092480.718750', image_files: 'ch6-6-b3.png,ch6-6-b3_svd.png,ch6-6-b3_graph.gif,', }
34.116279
75
0.612815
7a78c15dc76c09fd25c574343d73b704165406bf
2,476
require 'test_helper' class UserTest < ActiveSupport::TestCase def setup @user = User.new(name: "Example User", email: "[email protected]", password: "foobar", password_confirmation: "foobar") end test "should be valid" do assert @user.valid? end test "name should be present" do @user.name = " " assert_not @user.valid? end test "email should be present" do @user.email = " " assert_not @user.valid? end test "name should not be too long" do @user.name = "a" * 51 assert_not @user.valid? end test "email should not be too long" do @user.email = "a" * 244 + "@example.com" assert_not @user.valid? end test "email validation should accept valid addresses" do valid_addresses = %w[[email protected] [email protected] [email protected] [email protected] [email protected]] valid_addresses.each do |valid_address| @user.email = valid_address assert @user.valid?, "#{valid_address.inspect} should be valid" end end test "email validation should reject invalid addresses" do invalid_addresses = %w[user@example,com user_at_foo.org user.name@example. foo@bar_baz.com foo@bar+baz.com [email protected]] invalid_addresses.each do |invalid_address| @user.email = invalid_address assert_not @user.valid?, "#{invalid_address.inspect} should be invalid" end end test "email addresses should be unique" do duplicate_user = @user.dup duplicate_user.email = @user.email.upcase @user.save assert_not duplicate_user.valid? end test "email addresses should be saved as lower-case" do mixed_case_email = "[email protected]" @user.email = mixed_case_email @user.save assert_equal mixed_case_email.downcase, @user.reload.email end test "password should be present (nonblank)" do @user.password = @user.password_confirmation = " " * 6 assert_not @user.valid? end test "password should have a minimum length" do @user.password = @user.password_confirmation = "a" * 5 assert_not @user.valid? end test "authenticated? should return false for a user with nil digest" do assert_not @user.authenticated?(:remember, '') end test "associated microposts should be destroyed" do @user.save @user.microposts.create!(content: "Lorem ipsum") assert_difference 'Micropost.count', -1 do @user.destroy end end end
28.136364
78
0.671244
f795c534cb71462c62ed757a867f9cae4a60d589
318
module ActionCable # Returns the version of the currently loaded Action Cable as a <tt>Gem::Version</tt>. def self.gem_version Gem::Version.new VERSION::STRING end module VERSION MAJOR = 5 MINOR = 1 TINY = 6 PRE = nil STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end end
19.875
88
0.644654
384c0a36e70b91e115437ddedbfa048c56f61b6c
3,995
require_relative '../../../../spec_helper.rb' describe Salus::Scanners::PackageVersion::NPMPackageScanner do let(:path) { 'spec/fixtures/package_version/npm_package_version_scanner/' } let(:config_file) { YAML.load_file("#{path}/salus.yml") } let(:config_file_with_block) { YAML.load_file("#{path}/salus_fail_with_block.yml") } let(:scanner_config) { config_file['scanner_configs']["NPMPackageScanner"] } let(:scanner_config_with_block) { config_file_with_block['scanner_configs']["NPMPackageScanner"] } describe '#should_run?' do it 'should return false when package lock file is absent' do repo = Salus::Repo.new('spec/fixtures/blank_repository') scanner = Salus::Scanners::PackageVersion::NPMPackageScanner.new(repository: repo, config: {}) expect(scanner.should_run?).to eq(false) end it 'should return true if package lock is present' do repo = Salus::Repo.new('spec/fixtures/npm_audit/success') scanner = Salus::Scanners::PackageVersion::NPMPackageScanner.new(repository: repo, config: {}) expect(scanner.should_run?).to eq(true) end end describe '#run' do context 'package-lock file present' do it 'should fail when package in repo does not fall within the specified package range' do repo = Salus::Repo.new('spec/fixtures/npm_audit/failure') scanner = Salus::Scanners::PackageVersion::NPMPackageScanner.new(repository: repo, config: scanner_config) scanner.run logs = scanner.report.to_h[:logs] expect(scanner.report.passed?).to eq(false) expect(JSON.parse(logs)).to eq( [ "Package version for (mobx) (3.6.2) is less than minimum configured version (3.6.3) "\ "on line {13} in package-lock.json.", "Package version for (uglify-js) (1.2.3) is greater than maximum configured version "\ "(0.10.3) on line {18} in package-lock.json." ] ) end it 'should fail when package in repo matched blocked range' do repo = Salus::Repo.new('spec/fixtures/npm_audit/failure') scanner = Salus::Scanners::PackageVersion::NPMPackageScanner.new(repository: repo, config: scanner_config_with_block) scanner.run logs = scanner.report.to_h[:logs] expect(scanner.report.passed?).to eq(false) expect(JSON.parse(logs)).to eq( [ "Package version for (mobx) (3.6.2) matches the configured blocked version"\ " (3.1.1,3.6.2) on line {13} in package-lock.json." ] ) end it 'should pass when package-lock file exists and nothing is configured for the scanner' do repo = Salus::Repo.new('spec/fixtures/npm_audit/failure') scanner = Salus::Scanners::PackageVersion::NPMPackageScanner.new(repository: repo, config: {}) scanner.run expect(scanner.report.passed?).to eq(true) end it 'should pass when package falls within specified package range' do repo = Salus::Repo.new('spec/fixtures/npm_audit/failure') config = scanner_config config['package_versions']['mobx']['min_version'] = '3.6.0' config['package_versions']['uglify-js']['max_version'] = '1.3.4' config['package_versions']['mobx']['block'] = '1.1.1' scanner = Salus::Scanners::PackageVersion::NPMPackageScanner.new(repository: repo, config: config) scanner.run expect(scanner.report.passed?).to eq(true) end it 'should pass when package-lock file exists and nothing is configured for any package' do repo = Salus::Repo.new('spec/fixtures/npm_audit/failure') config = config_file config['scanner_configs']["NPMPackageScanner"] = [] scanner = Salus::Scanners::PackageVersion::NPMPackageScanner.new(repository: repo, config: config) scanner.run expect(scanner.report.passed?).to eq(true) end end end end
44.388889
100
0.65582
7a492cc3e39eb0fa0c947236bbe6cb901851da8a
1,146
cask 'clamxav' do if MacOS.release <= :tiger version '2.2.1' sha256 'e075b21fe5154f31dcbde86e492531c87c67ab44ad75294d3063f32ae1e58278' elsif MacOS.release <= :leopard version '2.5.1' sha256 '02a7529c74d11724e2d0e8226ac83a0d3cfb599afb354d02f6609632d69d9eb1' else version '2.8.8' sha256 'd9a460ecf762cacf8ae3ef93d04ce1b223fd1ea2c54327b7bc231e8fbd516cd3' appcast 'https://www.clamxav.com/sparkle/appcast.xml', :sha256 => 'e68625af3cc82a17dc19f7e378b74b0e15d61dc9b16ace1cb5f0bdc308d27389' end url "https://www.clamxav.com/downloads/ClamXav_#{version}.dmg" name 'ClamXav' homepage 'https://www.clamxav.com/' license :commercial app 'ClamXav.app' postflight do suppress_move_to_applications end zap :delete => [ '~/Library/Caches/uk.co.markallan.clamxav', '~/Library/Logs/clamXav-scan.log', # todo glob/expand needed here '~/Library/Logs/clamXav-scan.log.0.bz2', ] caveats do # this happens sometime after installation, but still worth warning about files_in_usr_local end end
29.384615
89
0.687609
0855313d6ac4e9135fa4baa710894fd560d1364b
231
require "opensupport/engine" module Opensupport # Your code goes here... # Make this available in the host's initializer, e.g Opensupport.resource_names = ["products", "product_variants"] mattr_accessor :resource_names end
25.666667
116
0.766234
624b991dba3b376eec8044f76b1b9504650c2f3e
4,185
module Gollum =begin FileView requires that: - All files in root dir are processed first - Then all the folders are sorted and processed =end class FileView def initialize pages @pages = pages end def enclose_tree string %Q(<ol class="tree">\n) + string + %Q(</ol>) end def new_page page name = page.name %Q( <li class="file"><a href="#{name}">#{name}</a></li>\n) end def new_folder page new_sub_folder ::File.dirname(page.path), page.name end def new_sub_folder path, name <<-HTML <li> <label>#{path}</label> <input type="checkbox" checked /> <ol> <li class="file"><a href="#{name}">#{name}</a></li> HTML end def end_folder <<-HTML </ol> </li> HTML end def render_files html = '' count = @pages.size folder_start = -1 # Process all pages until folders start count.times do | index | page = @pages[ index ] path = page.path unless path.include? '/' # Page processed (not contained in a folder) html += new_page page else # Folders start at the next index folder_start = index break # Pages finished, move on to folders end end # If there are no folders, then we're done. return enclose_tree(html) if folder_start <= -1 # Handle special case of only one folder. if (count - folder_start == 1) page = @pages[ folder_start ] name = page.name html += <<-HTML <li> <label>#{::File.dirname(page.path)}</label> <input type="checkbox" checked /> <ol> <li class="file"><a href="#{name}">#{name}</a></li> </ol> </li> HTML return enclose_tree html end sorted_folders = [] (folder_start).upto count - 1 do | index | sorted_folders += [[ @pages[ index ].path, index ]] end # http://stackoverflow.com/questions/3482814/sorting-list-of-string-paths-in-vb-net sorted_folders.sort! do |first,second| a = first[0] b = second[0] # use :: operator because gollum defines its own conflicting File class dir_compare = ::File.dirname(a) <=> ::File.dirname(b) # Sort based on directory name unless they're equal (0) in # which case sort based on file name. if dir_compare == 0 ::File.basename(a) <=> ::File.basename(b) else dir_compare end end # Process first folder page = @pages[ sorted_folders[ 0 ][1] ] html += new_folder page last_folder = ::File.dirname page.path # define last_folder # keep track of folder depth, 0 = at root. depth = 0 # process rest of folders 1.upto(sorted_folders.size - 1) do | index | page = @pages[ sorted_folders[ index ][1] ] path = page.path folder = ::File.dirname path if last_folder == folder # same folder html += new_page page elsif folder.include?('/') # check if we're going up or down a depth level if last_folder.scan('/').size > folder.scan('/').size # end tag for 1 subfolder & 1 parent folder # so emit 2 end tags 2.times { html += end_folder; } depth -= 1 else depth += 1 end # subfolder html += new_sub_folder ::File.dirname(page.path).split('/').last, page.name else # depth+1 because we need an additional end_folder (depth+1).times { html += end_folder; } depth = 0 # New root folder html += new_folder page end last_folder = folder end # Process last folder's ending tags. (depth+1).times { depth.times { html += end_folder; } depth = 0 } # return the completed html enclose_tree html end # end render_files end # end FileView class end # end Gollum module
27
89
0.538351
bb528530ebad64ea453c68a091200137299ca642
1,537
require './models/grid' require './errors/configuration_file_not_found_error' class Game attr_reader :current_grid, :previous_grid, :history, :round_count, :finish_reason RESOURCE_FILE_PATH = 'file_samples' USER_FILE_PATH = 'user_files' SEPARATOR = File::Separator FILE_EXTENSION = 'csv' def initialize(grid) @current_grid = grid @previous_grid = nil @round_count = 0 @state_not_change = false @history = [] @finish_reason = "" end def do_iteration @previous_grid = @current_grid.dup @history.push(@previous_grid) @current_grid = @current_grid.next_state @round_count += 1 if @current_grid == @previous_grid @state_not_change = true @finish_reason = "Конфигурация по сравнению с предыдущей не изменилась" end end def self.find(number) file = "#{RESOURCE_FILE_PATH}#{SEPARATOR}configuration_#{number}.#{FILE_EXTENSION}" file = "#{USER_FILE_PATH}#{SEPARATOR}configuration_#{number}.#{FILE_EXTENSION}" unless File.exists?(file) raise ConfigurationFileNotFoundError unless File.exists?(file) self.new(Grid.from_file(file)) end def stop? !at_least_one_alive? || @state_not_change || in_history? end def in_history? res = @history.any? do |insp_grid| insp_grid == @current_grid end @finish_reason = "Такая конфигурация уже существовала" if res res end def at_least_one_alive? res = @current_grid.at_least_one_alive? @finish_reason = "Нет ни одной живой клетки" if !res res end end
26.964912
109
0.703318
5d95792840af6f6df6a48ec3a16f460de4d128cd
1,761
require "rails_helper" describe DogsController, type: :controller do before do sign_in create(:user) end describe "#index" do context "not logged in" do it "can't get to index" do sign_out :user get :index expect(response).to redirect_to new_user_session_path end end context "logged in" do it "can get to index" do get :index expect(response).to have_http_status(:success) end end end describe "#new" do context "not logged in" do it "can't get to new page" do sign_out :user get :new expect(response).to redirect_to new_user_session_path end end context "logged in" do it "can get to new page" do get :new expect(response).to have_http_status(:success) end end end describe "#create" do context "when dog is valid" do it "redirects to #show" do # TODO: See to refactor this dog = stub_valid_dog post :create, params: { dog: attributes_for(:dog) } expect(response).to redirect_to(dog) end end context "when dog is invalid" do it "renders the 'new' template" do # TODO: See to refactor this dog = stub_invalid_dog post :create, params: { dog: attributes_for(:dog) } expect(response).to render_template(:new) end end end private def stub_valid_dog Dog.new.tap do |dog| allow(Dog).to receive(:new).and_return dog allow(dog).to receive(:save).and_return(true) end end def stub_invalid_dog Dog.new.tap do |dog| allow(Dog).to receive(:new).and_return dog allow(dog).to receive(:save).and_return(false) end end end
20.476744
61
0.611584
1a8f4bdceb2d18e2c304a7f78dedfeefa4e467d7
522
Spree::Order.class_eval do checkout_flow do go_to_state :address go_to_state :delivery, if: ->(order) { order.delivery_required? } go_to_state :payment, if: ->(order) { order.payment_required? } go_to_state :confirm, if: ->(order) { order.confirmation_required? } go_to_state :complete remove_transition from: :delivery, to: :confirm end def delivery_required? products.not_plan.any? end end Spree::Order.state_machine.after_transition to: :complete, do: :after_complete_callbacks
29
88
0.727969
189f326b492095dd30de7873addc496264572d71
322
# 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 end module Azure::ContainerRegistry end module Azure::ContainerRegistry::Mgmt end module Azure::ContainerRegistry::Mgmt::V2019_06_01_preview end
32.2
70
0.804348
f8732514edda920e55c07c92c3db614db5902584
19,165
# frozen_string_literal: true # encoding: UTF-8 require 'test_helper' class FormBuilderTest < ActionView::TestCase def with_custom_form_for(object, *args, &block) with_concat_custom_form_for(object) do |f| f.input(*args, &block) end end test 'nested simple fields yields an instance of FormBuilder' do simple_form_for :user do |f| f.simple_fields_for :posts do |posts_form| assert posts_form.instance_of?(SimpleForm::FormBuilder) end end end test 'builder input is html safe' do simple_form_for @user do |f| assert f.input(:name).html_safe? end end test 'builder works without controller' do stub_any_instance ActionView::TestCase, :controller, nil do simple_form_for @user do |f| assert f.input(:name) end end end test 'builder works with decorated object responsive to #to_model' do assert_nothing_raised do with_form_for @decorated_user, :name end end test 'builder input allows a block to configure input' do with_form_for @user, :name do text_field_tag :foo, :bar, id: :cool end assert_no_select 'input.string' assert_select 'input#cool' end test 'builder allows adding custom input mappings for default input types' do swap SimpleForm, input_mappings: { /count$/ => :integer } do with_form_for @user, :post_count assert_no_select 'form input#user_post_count.string' assert_select 'form input#user_post_count.numeric.integer' end end test 'builder does not override custom input mappings for custom collection' do swap SimpleForm, input_mappings: { /gender$/ => :check_boxes } do with_concat_form_for @user do |f| f.input :gender, collection: %i[male female] end assert_no_select 'select option', 'Male' assert_select 'input[type=checkbox][value=male]' end end test 'builder allows to skip input_type class' do swap SimpleForm, generate_additional_classes_for: %i[label wrapper] do with_form_for @user, :post_count assert_no_select "form input#user_post_count.integer" assert_select "form input#user_post_count" end end test 'builder allows to add additional classes only for wrapper' do swap SimpleForm, generate_additional_classes_for: [:wrapper] do with_form_for @user, :post_count assert_no_select "form input#user_post_count.string" assert_no_select "form label#user_post_count.string" assert_select "form div.input.string" end end test 'builder allows adding custom input mappings for integer input types' do swap SimpleForm, input_mappings: { /lock_version/ => :hidden } do with_form_for @user, :lock_version assert_no_select 'form input#user_lock_version.integer' assert_select 'form input#user_lock_version.hidden' end end test 'builder uses the first matching custom input map when more than one matches' do swap SimpleForm, input_mappings: { /count$/ => :integer, /^post_/ => :password } do with_form_for @user, :post_count assert_no_select 'form input#user_post_count.password' assert_select 'form input#user_post_count.numeric.integer' end end test 'builder uses the custom map only for matched attributes' do swap SimpleForm, input_mappings: { /lock_version/ => :hidden } do with_form_for @user, :post_count assert_no_select 'form input#user_post_count.hidden' assert_select 'form input#user_post_count.string' end end test 'builder allow to use numbers in the model name' do user = UserNumber1And2.build(tags: [Tag.new(nil, 'Tag1')]) with_concat_form_for(user, url: '/') do |f| f.simple_fields_for(:tags) do |tags| tags.input :name end end assert_select 'form .user_number1_and2_tags_name' assert_no_select 'form .user_number1_and2_tags_1_name' end # INPUT TYPES test 'builder generates text fields for string columns' do with_form_for @user, :name assert_select 'form input#user_name.string' end test 'builder generates text areas for text columns' do with_form_for @user, :description assert_no_select 'form input#user_description.string' assert_select 'form textarea#user_description.text' end test 'builder generates text areas for text columns when hinted' do with_form_for @user, :description, as: :text assert_no_select 'form input#user_description.string' assert_select 'form textarea#user_description.text' end test 'builder generates text field for text columns when hinted' do with_form_for @user, :description, as: :string assert_no_select 'form textarea#user_description.text' assert_select 'form input#user_description.string' end test 'builder generates text areas for hstore columns' do with_form_for @user, :hstore assert_no_select 'form input#user_hstore.string' assert_select 'form textarea#user_hstore.text' end test 'builder generates text areas for json columns' do with_form_for @user, :json assert_no_select 'form input#user_json.string' assert_select 'form textarea#user_json.text' end test 'builder generates text areas for jsonb columns' do with_form_for @user, :jsonb assert_no_select 'form input#user_jsonb.string' assert_select 'form textarea#user_jsonb.text' end test 'builder generates a checkbox for boolean columns' do with_form_for @user, :active assert_select 'form input[type=checkbox]#user_active.boolean' end test 'builder uses integer text field for integer columns' do with_form_for @user, :age assert_select 'form input#user_age.numeric.integer' end test 'builder generates decimal text field for decimal columns' do with_form_for @user, :credit_limit assert_select 'form input#user_credit_limit.numeric.decimal' end test 'builder generates uuid fields for uuid columns' do with_form_for @user, :uuid if defined? ActiveModel::Type assert_select 'form input#user_uuid.string.string' else assert_select 'form input#user_uuid.string.uuid' end end test 'builder generates string fields for citext columns' do with_form_for @user, :citext assert_select 'form input#user_citext.string' end test 'builder generates password fields for columns that matches password' do with_form_for @user, :password assert_select 'form input#user_password.password' end test 'builder generates country fields for columns that matches country' do with_form_for @user, :residence_country assert_select 'form select#user_residence_country.country' end test 'builder generates time_zone fields for columns that matches time_zone' do with_form_for @user, :time_zone assert_select 'form select#user_time_zone.time_zone' end test 'builder generates email fields for columns that matches email' do with_form_for @user, :email assert_select 'form input#user_email.string.email' end test 'builder generates tel fields for columns that matches phone' do with_form_for @user, :phone_number assert_select 'form input#user_phone_number.string.tel' end test 'builder generates url fields for columns that matches url' do with_form_for @user, :url assert_select 'form input#user_url.string.url' end test 'builder generates date select for date columns' do with_form_for @user, :born_at assert_select 'form select#user_born_at_1i.date' end test 'builder generates time select for time columns' do with_form_for @user, :delivery_time assert_select 'form select#user_delivery_time_4i.time' end test 'builder generates datetime select for datetime columns' do with_form_for @user, :created_at assert_select 'form select#user_created_at_1i.datetime' end test 'builder generates datetime select for timestamp columns' do with_form_for @user, :updated_at assert_select 'form select#user_updated_at_1i.datetime' end test 'builder generates file for file columns' do @user.avatar = MiniTest::Mock.new @user.avatar.expect(:public_filename, true) @user.avatar.expect(:!, false) with_form_for @user, :avatar assert_select 'form input#user_avatar.file' end test 'builder generates file for activestorage entries' do @user.avatar = MiniTest::Mock.new @user.avatar.expect(:attached?, false) @user.avatar.expect(:!, false) with_form_for @user, :avatar assert_select 'form input#user_avatar.file' end test 'builder generates file for attributes that are real db columns but have file methods' do @user.home_picture = MiniTest::Mock.new @user.home_picture.expect(:mounted_as, true) @user.home_picture.expect(:!, false) with_form_for @user, :home_picture assert_select 'form input#user_home_picture.file' end test 'build generates select if a collection is given' do with_form_for @user, :age, collection: 1..60 assert_select 'form select#user_age.select' end test 'builder does not generate url fields for columns that contain only the letters url' do with_form_for @user, :hourly assert_no_select 'form input#user_url.string.url' assert_select 'form input#user_hourly.string' end test 'builder allows overriding default input type for text' do with_form_for @user, :name, as: :text assert_no_select 'form input#user_name' assert_select 'form textarea#user_name.text' end test 'builder allows overriding default input type for radio_buttons' do with_form_for @user, :active, as: :radio_buttons assert_no_select 'form input[type=checkbox]' assert_select 'form input.radio_buttons[type=radio]', count: 2 end test 'builder allows overriding default input type for string' do with_form_for @user, :born_at, as: :string assert_no_select 'form select' assert_select 'form input#user_born_at.string' end # COMMON OPTIONS # Remove this test when SimpleForm.form_class is removed in 4.x test 'builder adds chosen form class' do ActiveSupport::Deprecation.silence do swap SimpleForm, form_class: :my_custom_class do with_form_for @user, :name assert_select 'form.my_custom_class' end end end # Remove this test when SimpleForm.form_class is removed in 4.x test 'builder adds chosen form class and default form class' do ActiveSupport::Deprecation.silence do swap SimpleForm, form_class: "my_custom_class", default_form_class: "my_default_class" do with_form_for @user, :name assert_select 'form.my_custom_class.my_default_class' end end end test 'builder adds default form class' do swap SimpleForm, default_form_class: "default_class" do with_form_for @user, :name assert_select 'form.default_class' end end test 'builder allows passing options to input' do with_form_for @user, :name, input_html: { class: 'my_input', id: 'my_input' } assert_select 'form input#my_input.my_input.string' end test 'builder does not propagate input options to wrapper' do with_form_for @user, :name, input_html: { class: 'my_input', id: 'my_input' } assert_no_select 'form div.input.my_input.string' assert_select 'form input#my_input.my_input.string' end test 'builder does not propagate input options to wrapper with custom wrapper' do swap_wrapper :default, custom_wrapper_with_wrapped_input do with_form_for @user, :name, input_html: { class: 'my_input' } assert_no_select 'form div.input.my_input' assert_select 'form input.my_input.string' end end test 'builder does not propagate label options to wrapper with custom wrapper' do swap_wrapper :default, custom_wrapper_with_wrapped_label do with_form_for @user, :name, label_html: { class: 'my_label' } assert_no_select 'form div.label.my_label' assert_select 'form label.my_label.string' end end test 'builder generates an input with label' do with_form_for @user, :name assert_select 'form label.string[for=user_name]', /Name/ end test 'builder is able to disable the label for an input' do with_form_for @user, :name, label: false assert_no_select 'form label' end test 'builder is able to disable the label for an input and return a html safe string' do with_form_for @user, :name, label: false, wrapper: custom_wrapper_with_wrapped_label_input assert_select 'form input#user_name' end test 'builder uses custom label' do with_form_for @user, :name, label: 'Yay!' assert_select 'form label', /Yay!/ end test 'builder passes options to label' do with_form_for @user, :name, label_html: { id: "cool" } assert_select 'form label#cool', /Name/ end test 'builder does not generate hints for an input' do with_form_for @user, :name assert_no_select 'span.hint' end test 'builder is able to add a hint for an input' do with_form_for @user, :name, hint: 'test' assert_select 'span.hint', 'test' end test 'builder is able to disable a hint even if it exists in i18n' do store_translations(:en, simple_form: { hints: { name: 'Hint test' } }) do stub_any_instance(SimpleForm::Inputs::Base, :hint, -> { raise 'Never' }) do with_form_for @user, :name, hint: false assert_no_select 'span.hint' end end end test 'builder passes options to hint' do with_form_for @user, :name, hint: 'test', hint_html: { id: "cool" } assert_select 'span.hint#cool', 'test' end test 'builder generates errors for attribute without errors' do with_form_for @user, :credit_limit assert_no_select 'span.errors' end test 'builder generates errors for attribute with errors' do with_form_for @user, :name assert_select 'span.error', "cannot be blank" end test 'builder is able to disable showing errors for an input' do with_form_for @user, :name, error: false assert_no_select 'span.error' end test 'builder passes options to errors' do with_form_for @user, :name, error_html: { id: "cool" } assert_select 'span.error#cool', "cannot be blank" end test 'placeholder does not be generated when set to false' do store_translations(:en, simple_form: { placeholders: { user: { name: 'Name goes here' } } }) do with_form_for @user, :name, placeholder: false assert_no_select 'input[placeholder]' end end # DEFAULT OPTIONS %i[input input_field].each do |method| test "builder receives a default argument and pass it to the inputs when calling '#{method}'" do with_concat_form_for @user, defaults: { input_html: { class: 'default_class' } } do |f| f.public_send(method, :name) end assert_select 'input.default_class' end test "builder receives a default argument and pass it to the inputs without changing the defaults when calling '#{method}'" do with_concat_form_for @user, defaults: { input_html: { class: 'default_class', id: 'default_id' } } do |f| concat(f.public_send(method, :name)) concat(f.public_send(method, :credit_limit)) end assert_select "input.string.default_class[name='user[name]']" assert_no_select "input.string[name='user[credit_limit]']" end test "builder receives a default argument and pass it to the inputs and nested form when calling '#{method}'" do @user.company = Company.new(1, 'Empresa') with_concat_form_for @user, defaults: { input_html: { class: 'default_class' } } do |f| concat(f.public_send(method, :name)) concat(f.simple_fields_for(:company) do |company_form| concat(company_form.public_send(method, :name)) end) end assert_select "input.string.default_class[name='user[name]']" assert_select "input.string.default_class[name='user[company_attributes][name]']" end end test "builder receives a default argument and pass it to the inputs when calling 'input', respecting the specific options" do with_concat_form_for @user, defaults: { input_html: { class: 'default_class' } } do |f| f.input :name, input_html: { id: 'specific_id' } end assert_select 'input.default_class#specific_id' end test "builder receives a default argument and pass it to the inputs when calling 'input_field', respecting the specific options" do with_concat_form_for @user, defaults: { input_html: { class: 'default_class' } } do |f| f.input_field :name, id: 'specific_id' end assert_select 'input.default_class#specific_id' end test "builder receives a default argument and pass it to the inputs when calling 'input', overwriting the defaults with specific options" do with_concat_form_for @user, defaults: { input_html: { class: 'default_class', id: 'default_id' } } do |f| f.input :name, input_html: { id: 'specific_id' } end assert_select 'input.default_class#specific_id' end test "builder receives a default argument and pass it to the inputs when calling 'input_field', overwriting the defaults with specific options" do with_concat_form_for @user, defaults: { input_html: { class: 'default_class', id: 'default_id' } } do |f| f.input_field :name, id: 'specific_id' end assert_select 'input.default_class#specific_id' end # WITHOUT OBJECT test 'builder generates properly when object is not present' do with_form_for :project, :name assert_select 'form input.string#project_name' end test 'builder generates password fields based on attribute name when object is not present' do with_form_for :project, :password_confirmation assert_select 'form input[type=password].password#project_password_confirmation' end test 'builder generates text fields by default for all attributes when object is not present' do with_form_for :project, :created_at assert_select 'form input.string#project_created_at' with_form_for :project, :budget assert_select 'form input.string#project_budget' end test 'builder allows overriding input type when object is not present' do with_form_for :project, :created_at, as: :datetime assert_select 'form select.datetime#project_created_at_1i' with_form_for :project, :budget, as: :decimal assert_select 'form input.decimal#project_budget' end # CUSTOM FORM BUILDER test 'custom builder inherits mappings' do with_custom_form_for @user, :email assert_select 'form input[type=email]#user_email.custom' end test 'form with CustomMapTypeFormBuilder uses custom map type builder' do with_concat_custom_mapping_form_for(:user) do |user| assert user.instance_of?(CustomMapTypeFormBuilder) end end test 'form with CustomMapTypeFormBuilder uses custom mapping' do with_concat_custom_mapping_form_for(:user) do |user| assert_equal SimpleForm::Inputs::StringInput, user.class.mappings[:custom_type] end end test 'form without CustomMapTypeFormBuilder does not use custom mapping' do with_concat_form_for(:user) do |user| assert_nil user.class.mappings[:custom_type] end end end
35.359779
148
0.727159
ac230a71783d0e89db53e1795801b8b7531fb8fb
4,234
module Bosh::Director module Addon DEPLOYMENT_LEVEL = :deployment RUNTIME_LEVEL = :runtime class Addon extend ValidationHelper attr_reader :name def initialize(name, job_hashes, addon_include, addon_exclude) @name = name @addon_job_hashes = job_hashes @addon_include = addon_include @addon_exclude = addon_exclude @links_parser = Bosh::Director::Links::LinksParser.new end def jobs @addon_job_hashes end def self.parse(addon_hash, addon_level = RUNTIME_LEVEL) name = safe_property(addon_hash, 'name', class: String) addon_job_hashes = safe_property(addon_hash, 'jobs', class: Array, default: []) parsed_addon_jobs = addon_job_hashes.map do |addon_job_hash| parse_and_validate_job(addon_job_hash) end addon_include = Filter.parse(safe_property(addon_hash, 'include', class: Hash, optional: true), :include, addon_level) addon_exclude = Filter.parse(safe_property(addon_hash, 'exclude', class: Hash, optional: true), :exclude, addon_level) validate_no_addon_properties(addon_hash, name) new(name, parsed_addon_jobs, addon_include, addon_exclude) end def applies?(deployment_name, deployment_teams, deployment_instance_group) @addon_include.applies?(deployment_name, deployment_teams, deployment_instance_group) && !@addon_exclude.applies?(deployment_name, deployment_teams, deployment_instance_group) end def add_to_deployment(deployment) eligible_instance_groups = deployment.instance_groups.select do |instance_group| applies?(deployment.name, deployment.team_names, instance_group) end add_addon_jobs_to_instance_groups(deployment, eligible_instance_groups) unless eligible_instance_groups.empty? end def releases @addon_job_hashes.map do |addon| addon['release'] end.uniq end def self.parse_and_validate_job(addon_job) { 'name' => safe_property(addon_job, 'name', class: String), 'release' => safe_property(addon_job, 'release', class: String), 'provides' => safe_property(addon_job, 'provides', class: Hash, default: {}), 'consumes' => safe_property(addon_job, 'consumes', class: Hash, default: {}), 'properties' => safe_property(addon_job, 'properties', class: Hash, optional: true, default: {}), } end def self.validate_no_addon_properties(addon_hash, name) addon_level_properties = safe_property(addon_hash, 'properties', class: Hash, optional: true) if addon_level_properties raise V1DeprecatedAddOnProperties, "Addon '#{name}' specifies 'properties' which is not supported. 'properties' are only "\ "allowed in the 'jobs' array" end end private_class_method :parse_and_validate_job, :validate_no_addon_properties private def add_addon_jobs_to_instance_groups(deployment, eligible_instance_groups) @addon_job_hashes.each do |addon_job_hash| deployment_release_version = deployment.release(addon_job_hash['release']) deployment_release_version.bind_model addon_job_object = DeploymentPlan::Job.new(deployment_release_version, addon_job_hash['name']) addon_job_object.bind_models eligible_instance_groups.each do |instance_group| instance_group_name = instance_group.name job_properties = addon_job_hash['properties'] addon_job_object.add_properties(job_properties, instance_group_name) @links_parser.parse_providers_from_job( addon_job_hash, deployment.model, addon_job_object.model, job_properties: job_properties, instance_group_name: instance_group_name, ) @links_parser.parse_consumers_from_job( addon_job_hash, deployment.model, addon_job_object.model, instance_group_name: instance_group_name ) instance_group.add_job(addon_job_object) end end end end end end
37.803571
126
0.679972
bf084529fd76d7e94b797d3eaf2e8018cc1ca5e3
2,176
class PostTestApp < Sinatra::Base register Sinatra::Chiro app_description "POST parameter tester" endpoint 'Form String tester', 'Tests the validation of a String type form parameter' do form(:string, 'arbitrary parameter of string type', :type => String, :optional => false) post '/test/form/string' do "Valid" end end endpoint 'Form Date tester', 'Tests the validation of a Date type form parameter' do form(:date, 'arbitrary parameter of date type', :type => Date, :optional => false) response({:date => '1993-07-05'}) post '/test/form/date' do "Valid" end end endpoint 'Form Time tester', 'Tests the validation of a Time type form parameter' do form(:time, 'arbitrary parameter of time type', :type => Time, :optional => false) post '/test/form/time' do "Valid" end end endpoint 'Form Fixnum tester', 'Tests the validation of a Fixnum type form parameter' do form(:fixnum, 'arbitrary parameter of fixnum type', :type => Fixnum, :optional => false) post '/test/form/fixnum' do "Valid" end end endpoint 'Form Float tester', 'Tests the validation of a Float type form parameter' do form(:float, 'arbitrary parameter of float type', :type => Float, :optional => false) post '/test/form/float' do "Valid" end end endpoint 'Form Datetime tester', 'Tests the validation of a Datetime type form parameter' do form(:datetime, 'arbitrary parameter of datetime type', :type => DateTime, :optional => false) post '/test/form/datetime' do "Valid" end end endpoint 'Form Boolean tester', 'Tests the validation of a Boolean type form parameter' do form(:boolean, 'arbitrary parameter of boolean type', :type => :boolean, :optional => false) post '/test/form/boolean' do "Valid" end end endpoint 'Form Regexp tester', 'Tests the validation of a gender form parameter which is a regular expression type' do form(:gender, 'gender parameter of regexp type', :type => /^male$|^female$/, :optional => false, :comment => 'Must be "male" or "female"') post '/test/form/gender' do "Valid" end end end
33.476923
142
0.668658
7a7ca23265756f1dc80219df3ec9183c659567a8
214
require 'facter' Facter.add(:windows_common_appdata) do confine :operatingsystem => :windows if Facter.value(:osfamily) == "windows" require 'win32/dir' end setcode do Dir::COMMON_APPDATA end end
19.454545
41
0.714953
1a4e8245ce43179c8567f72bd6cdaee81d28ab41
275
require_relative "../test_helper" describe "list_buckets" do it "should give list of buckets" do response = CONNECTION.list_buckets assert(response.is_a?(Excon::Response)) assert(response.body['buckets'].detect {|b| b['bucketName'] == TEST_BUCKET}) end end
25
80
0.716364
792b059bf8a22f704f66f9fd572662ff6f38a48e
967
def authorize_key_for_root(config, *key_paths) [*key_paths, nil].each do |key_path| if key_path.nil? fail "Public key not found at following paths: #{key_paths.join(', ')}" end full_key_path = File.expand_path(key_path) if File.exists?(full_key_path) config.vm.provision 'file', run: 'once', source: full_key_path, destination: '/home/vagrant/root_pubkey' config.vm.provision 'shell', privileged: true, run: 'once', inline: "echo \"Creating /root/.ssh/authorized_keys with #{key_path}\" && " + 'rm -f /root/.ssh/authorized_keys && ' + 'mkdir -p /root/.ssh &&' + 'mv /home/vagrant/root_pubkey /root/.ssh/authorized_keys && ' + 'chown root:root /root/.ssh/authorized_keys && ' + 'chmod 600 /root/.ssh/authorized_keys && ' + 'rm -f /home/vagrant/root_pubkey && ' + 'echo "Done!"' break end end end
31.193548
79
0.583247
79f13f3762b2d0f6c63637ba2da933023994f270
327
name 'lvm' maintainer 'Opscode, Inc.' maintainer_email '[email protected]' license 'Apache 2.0' description 'Installs lvm2 package' version '1.2.3' supports 'centos' supports 'debian' supports 'redhat' supports 'sles' supports 'ubuntu' recipe 'lvm', 'Installs lvm2 package'
21.8
41
0.651376
e9d32c5c7dcc6a7dc4ae5849140f1bda666c7bfe
8,215
require_relative '../../spec_helper' require_relative 'fixtures/classes' require_relative '../process/fixtures/common' describe "IO.popen" do ProcessSpecs.use_system_ruby(self) before :each do @fname = tmp("IO_popen_spec") @io = nil @var = "$FOO" platform_is :windows do @var = "%FOO%" end end after :each do @io.close if @io and [email protected]? rm_r @fname end it "returns an open IO" do @io = IO.popen(ruby_cmd('exit'), "r") @io.closed?.should be_false end it "reads a read-only pipe" do @io = IO.popen('echo foo', "r") @io.read.should == "foo\n" end it "raises IOError when writing a read-only pipe" do @io = IO.popen('echo foo', "r") -> { @io.write('bar') }.should raise_error(IOError) @io.read.should == "foo\n" end it "sees an infinitely looping subprocess exit when read pipe is closed" do io = IO.popen ruby_cmd('r = loop{puts "y"; 0} rescue 1; exit r'), 'r' io.close $?.exitstatus.should_not == 0 end it "writes to a write-only pipe" do @io = IO.popen(ruby_cmd('IO.copy_stream(STDIN,STDOUT)', args: "> #{@fname}"), "w") @io.write("bar") @io.close File.read(@fname).should == "bar" end it "raises IOError when reading a write-only pipe" do @io = IO.popen(ruby_cmd('IO.copy_stream(STDIN,STDOUT)'), "w") -> { @io.read }.should raise_error(IOError) end it "reads and writes a read/write pipe" do @io = IO.popen(ruby_cmd('IO.copy_stream(STDIN,STDOUT)'), "r+") @io.write("bar") @io.read(3).should == "bar" end it "waits for the child to finish" do @io = IO.popen(ruby_cmd('IO.copy_stream(STDIN,STDOUT)', args: "> #{@fname}"), "w") @io.write("bar") @io.close $?.exitstatus.should == 0 File.read(@fname).should == "bar" end it "does not throw an exception if child exited and has been waited for" do @io = IO.popen([*ruby_exe, '-e', 'sleep']) pid = @io.pid Process.kill "KILL", pid @io.close platform_is_not :windows do $?.should.signaled? end platform_is :windows do $?.should.exited? end end it "returns an instance of a subclass when called on a subclass" do @io = IOSpecs::SubIO.popen(ruby_cmd('exit'), "r") @io.should be_an_instance_of(IOSpecs::SubIO) end it "coerces mode argument with #to_str" do mode = mock("mode") mode.should_receive(:to_str).and_return("r") @io = IO.popen(ruby_cmd('exit 0'), mode) end describe "with a block" do it "yields an open IO to the block" do IO.popen(ruby_cmd('exit'), "r") do |io| io.closed?.should be_false end end it "yields an instance of a subclass when called on a subclass" do IOSpecs::SubIO.popen(ruby_cmd('exit'), "r") do |io| io.should be_an_instance_of(IOSpecs::SubIO) end end it "closes the IO after yielding" do io = IO.popen(ruby_cmd('exit'), "r") { |_io| _io } io.closed?.should be_true end it "allows the IO to be closed inside the block" do io = IO.popen(ruby_cmd('exit'), 'r') { |_io| _io.close; _io } io.closed?.should be_true end it "returns the value of the block" do IO.popen(ruby_cmd('exit'), "r") { :hello }.should == :hello end end platform_is_not :windows do it "starts returns a forked process if the command is -" do io = IO.popen("-") if io # parent begin io.gets.should == "hello from child\n" ensure io.close end else # child puts "hello from child" exit! end end end it "has the given external encoding" do @io = IO.popen(ruby_cmd('exit'), external_encoding: Encoding::EUC_JP) @io.external_encoding.should == Encoding::EUC_JP end it "has the given internal encoding" do @io = IO.popen(ruby_cmd('exit'), internal_encoding: Encoding::EUC_JP) @io.internal_encoding.should == Encoding::EUC_JP end it "sets the internal encoding to nil if it's the same as the external encoding" do @io = IO.popen(ruby_cmd('exit'), external_encoding: Encoding::EUC_JP, internal_encoding: Encoding::EUC_JP) @io.internal_encoding.should be_nil end context "with a leading ENV Hash" do it "accepts a single String command" do IO.popen({"FOO" => "bar"}, "echo #{@var}") do |io| io.read.should == "bar\n" end end it "accepts a single String command, and an IO mode" do IO.popen({"FOO" => "bar"}, "echo #{@var}", "r") do |io| io.read.should == "bar\n" end end it "accepts a single String command with a trailing Hash of Process.exec options" do IO.popen({"FOO" => "bar"}, ruby_cmd('STDERR.puts ENV["FOO"]'), err: [:child, :out]) do |io| io.read.should == "bar\n" end end it "accepts a single String command with a trailing Hash of Process.exec options, and an IO mode" do IO.popen({"FOO" => "bar"}, ruby_cmd('STDERR.puts ENV["FOO"]'), "r", err: [:child, :out]) do |io| io.read.should == "bar\n" end end it "accepts an Array of command and arguments" do exe, *args = ruby_exe IO.popen({"FOO" => "bar"}, [[exe, "specfu"], *args, "-e", "puts ENV['FOO']"]) do |io| io.read.should == "bar\n" end end it "accepts an Array of command and arguments, and an IO mode" do exe, *args = ruby_exe IO.popen({"FOO" => "bar"}, [[exe, "specfu"], *args, "-e", "puts ENV['FOO']"], "r") do |io| io.read.should == "bar\n" end end it "accepts an Array command with a separate trailing Hash of Process.exec options" do IO.popen({"FOO" => "bar"}, [*ruby_exe, "-e", "STDERR.puts ENV['FOO']"], err: [:child, :out]) do |io| io.read.should == "bar\n" end end it "accepts an Array command with a separate trailing Hash of Process.exec options, and an IO mode" do IO.popen({"FOO" => "bar"}, [*ruby_exe, "-e", "STDERR.puts ENV['FOO']"], "r", err: [:child, :out]) do |io| io.read.should == "bar\n" end end end context "with a leading Array argument" do it "uses the Array as command plus args for the child process" do IO.popen([*ruby_exe, "-e", "puts 'hello'"]) do |io| io.read.should == "hello\n" end end it "accepts a leading ENV Hash" do IO.popen([{"FOO" => "bar"}, *ruby_exe, "-e", "puts ENV['FOO']"]) do |io| io.read.should == "bar\n" end end it "accepts a trailing Hash of Process.exec options" do IO.popen([*ruby_exe, "does_not_exist", {err: [:child, :out]}]) do |io| io.read.should =~ /LoadError/ end end it "accepts an IO mode argument following the Array" do IO.popen([*ruby_exe, "does_not_exist", {err: [:child, :out]}], "r") do |io| io.read.should =~ /LoadError/ end end it "accepts [env, command, arg1, arg2, ..., exec options]" do IO.popen([{"FOO" => "bar"}, *ruby_exe, "-e", "STDERR.puts ENV[:FOO.to_s]", err: [:child, :out]]) do |io| io.read.should == "bar\n" end end it "accepts '[env, command, arg1, arg2, ..., exec options], mode'" do IO.popen([{"FOO" => "bar"}, *ruby_exe, "-e", "STDERR.puts ENV[:FOO.to_s]", err: [:child, :out]], "r") do |io| io.read.should == "bar\n" end end it "accepts '[env, command, arg1, arg2, ..., exec options], mode, IO options'" do IO.popen([{"FOO" => "bar"}, *ruby_exe, "-e", "STDERR.puts ENV[:FOO.to_s]", err: [:child, :out]], "r", internal_encoding: Encoding::EUC_JP) do |io| io.read.should == "bar\n" io.internal_encoding.should == Encoding::EUC_JP end end it "accepts '[env, command, arg1, arg2, ...], mode, IO + exec options'" do IO.popen([{"FOO" => "bar"}, *ruby_exe, "-e", "STDERR.puts ENV[:FOO.to_s]"], "r", err: [:child, :out], internal_encoding: Encoding::EUC_JP) do |io| io.read.should == "bar\n" io.internal_encoding.should == Encoding::EUC_JP end end end end
30.202206
106
0.580158
bb7139608edbc3bc9ec3428ae466e9a4217b5498
221
class FixVisibleUntil < ActiveRecord::Migration[4.2] def self.up rename_column :assignments , :visable_until, :visible_at end def self.down rename_column :assignments, :visible_at, :visable_until end end
22.1
60
0.751131
018c7926b7d232bb6b33fb16731e674a1f310dd0
1,830
# Copyright (c) 2017-present, Facebook, Inc. All rights reserved. # # You are hereby granted a non-exclusive, worldwide, royalty-free license to use, # copy, modify, and distribute this software in source code or binary form for use # in connection with the web services and APIs provided by Facebook. # # As with any software that integrates with the Facebook platform, your use of # this software is subject to the Facebook Platform Policy # [http://developers.facebook.com/policy/]. This copyright 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 'facebook_ads' access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<CUSTOM_AUDIENCE_ID>' FacebookAds.configure do |config| config.access_token = access_token config.app_secret = app_secret end custom_audience = FacebookAds::CustomAudience.get(id) users = custom_audience.users.create({ payload: {'schema':['EMAIL','MADID','APPUID','LOOKALIKE_VALUE'],'app_ids':['<appID>'],'data':[['b36a83701f1c3191e19722d6f90274bc1b5501fe69ebf33313e440fe4b0fe210','6032d997-3ab0-4de0-aa16-8af0e5b482fb','1234567890','0.9'],['2b3b2b9ce842ab8b6a6c614cb1f9604bb8a0d502d1af49c526b72b10894e95b5','B67385F8-9A82-4670-8C0A-6F9EA7513F5F','','0'],['898628e28890f937bdf009391def42879c401a4bcf1b5fd24e738d9f5da8cbbb','','9876543210','0.4']]}, })
53.823529
433
0.778689
ffe235eac4ea2b3d9f23a64cc526c35d5c30c1e2
632
require 'fog/core/model' module Fog module Openstack class Planning class Role < Fog::Model identity :uuid attribute :description attribute :name attribute :uuid def initialize(attributes) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end def add_to_plan(plan_uuid) service.add_role_to_plan(plan_uuid, uuid) end def remove_from_plan(plan_uuid) service.remove_role_from_plan(plan_uuid, uuid) end end end end end
21.066667
77
0.620253
4ac824c57c5a11385da504799b4c8039dfe6e009
1,825
require 'spec_helper' describe "Shipping Methods" do stub_authorization! let!(:zone) { create(:global_zone) } let!(:shipping_method) { create(:shipping_method, :zones => [zone]) } after do Capybara.ignore_hidden_elements = true end before do Capybara.ignore_hidden_elements = false # HACK: To work around no email prompting on check out Spree::Order.any_instance.stub(:require_email => false) create(:check_payment_method, :environment => 'test') visit spree.admin_path click_link "Configuration" click_link "Shipping Methods" end context "show" do it "should display existing shipping methods" do within_row(1) do column_text(1).should == shipping_method.name column_text(2).should == zone.name column_text(3).should == "Flat Rate" column_text(4).should == "Both" end end end context "create" do it "should be able to create a new shipping method" do click_link "New Shipping Method" fill_in "shipping_method_name", :with => "bullock cart" within("#shipping_method_categories_field") do check first("input[type='checkbox']")["name"] end click_on "Create" expect(current_path).to eql(spree.edit_admin_shipping_method_path(Spree::ShippingMethod.last)) end end # Regression test for #1331 context "update" do it "can change the calculator", :js => true do within("#listing_shipping_methods") do click_icon :edit end find(:css, ".calculator-settings-warning").should_not be_visible select2_search('Flexible Rate', :from => 'Calculator') find(:css, ".calculator-settings-warning").should be_visible click_button "Update" page.should_not have_content("Shipping method is not found") end end end
28.076923
100
0.679452
61ae637764e80ed63cf4c1d077033d4085b9c605
568
require File.join(File.dirname(__FILE__), 'abstract-php-extension') class Php55Yac < AbstractPhp55Extension init homepage 'https://github.com/laruence/yac' url 'https://github.com/laruence/yac.git', :branch => 'master' head 'https://github.com/laruence/yac.git' version 'latest' def install ENV.universal_binary if build.universal? safe_phpize system "./configure", "--prefix=#{prefix}", phpconfig system "make" prefix.install %w(modules/yac.so) write_config_file if build.with? "config-file" end end
27.047619
67
0.679577
382fcca14b8eef919f0ec38d9b080ce73133c0bf
2,585
class UsersController < Devise::RegistrationsController def edit render('sidebar/edit_profile', layout: 'sidebar') end def update self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key) if update_resource(resource, account_update_params) yield resource if block_given? bypass_sign_in resource, scope: resource_name flash[:notice] = 'Profile updated!' redirect_to(controller: 'sidebar', action: 'search') else clean_up_passwords(resource) render(json: {errors: resource.errors}, status: 500) end end def survey @user = current_user render('survey', layout: nil) end def mailing_address @user = current_user render('mailing_address', layout: nil) end def restricted_update self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key) if resource.update(restricted_account_update_params) yield resource if block_given? flash[:notice] = 'Profile updated!' render(json: {}, status: 204) else clean_up_passwords(resource) render(json: {errors: resource.errors}, status: 500) end end def create build_resource(sign_up_params) if resource.save yield resource if block_given? sign_in(resource_name, resource) ThingMailer.sign_up(resource) render(json: resource) else clean_up_passwords(resource) render(json: {errors: resource.errors}, status: 500) end end private def sign_up_params params.require(:user).permit(:address_1, :address_2, :city, :email, :first_name, :last_name, :organization, :password, :password_confirmation, :sms_number, :state, :voice_number, :username, :zip) end def account_update_params params.require(:user).permit(:address_1, :address_2, :city, :current_password, :email, :gender, :username, :first_name, :last_name, :organization, :password, :password_confirmation, :previousEnvironmentalActivities, :previousTreeWateringExperience, :remember_me, :rentOrOwn, :sms_number, :state, :valueForestryWork, :voice_number, :yearsInMinneapolis, :yob, :zip, :ethnicity => [], :heardOfAdoptATreeVia => []) end def restricted_account_update_params params.require(:user).permit(:address_1, :address_2, :city, :gender, :username, :first_name, :last_name, :organization, :previousEnvironmentalActivities, :previousTreeWateringExperience, :rentOrOwn, :sms_number, :state, :valueForestryWork, :voice_number, :yearsInMinneapolis, :yob, :zip, :ethnicity => [], :heardOfAdoptATreeVia => []) end end
38.014706
414
0.723017
03271b0ec8e37b6d9d1c6a574b6cd88a2f69b93a
1,414
# frozen_string_literal: true require 'securerandom' require 'tmpdir' module ProxyCrawl class ScreenshotsAPI < ProxyCrawl::API attr_reader :screenshot_path, :success, :remaining_requests, :screenshot_url INVALID_SAVE_TO_PATH_FILENAME = 'Filename must end with .jpg or .jpeg' SAVE_TO_PATH_FILENAME_PATTERN = /.+\.(jpg|JPG|jpeg|JPEG)$/.freeze def post raise 'Only GET is allowed for the ScreenshotsAPI' end def get(url, options = {}) screenshot_path = options.delete(:save_to_path) || generate_file_path raise INVALID_SAVE_TO_PATH_FILENAME unless SAVE_TO_PATH_FILENAME_PATTERN =~ screenshot_path response = super(url, options) file = File.open(screenshot_path, 'w+') file.write(response.body&.force_encoding('UTF-8')) @screenshot_path = screenshot_path yield(file) if block_given? response ensure file&.close end private def prepare_response(response, format) super(response, format) @remaining_requests = response['remaining_requests'].to_i @success = response['success'] == 'true' @screenshot_url = response['screenshot_url'] end def base_url 'https://api.proxycrawl.com/screenshots' end def generate_file_name "#{SecureRandom.urlsafe_base64}.jpg" end def generate_file_path File.join(Dir.tmpdir, generate_file_name) end end end
26.679245
97
0.699434
26e0b0d6446f1286afe470dabfe761aed196001a
4,737
describe Canvas::Course do let(:user_id) { Settings.canvas_proxy.test_user_id } let(:canvas_course_id) { '1121' } subject { Canvas::Course.new(:user_id => user_id, :canvas_course_id => canvas_course_id) } it { should respond_to(:canvas_course_id) } context 'when requesting course from canvas' do context 'if course exists in canvas' do it 'returns a string representation of itself' do expect(subject.to_s).to eq 'Canvas Course ID 1121' end it 'returns course hash' do course = subject.course[:body] expect(course['id']).to eq 1121 expect(course['account_id']).to eq 128847 expect(course['sis_course_id']).to eq 'CRS:STAT-5432-2013-D-757999' expect(course['course_code']).to eq 'STAT 5432 Fa2013' expect(course['name']).to eq 'Whither Statistics' expect(course['term']['sis_term_id']).to eq 'TERM:2013-D' expect(course['enrollments']).to be_an_instance_of Array expect(course['workflow_state']).to eq 'available' end it 'uses cache by default' do expect(Canvas::Course).to receive(:fetch_from_cache).and_return(cached: 'hash') course = subject.course expect(course[:cached]).to eq 'hash' end it 'bypasses cache when cache option is false' do expect(Canvas::Course).not_to receive(:fetch_from_cache) course = subject.course(cache: false)[:body] expect(course['id']).to eq 1121 expect(course['account_id']).to eq 128847 expect(course['sis_course_id']).to eq 'CRS:STAT-5432-2013-D-757999' expect(course['term']['sis_term_id']).to eq 'TERM:2013-D' expect(course['course_code']).to eq 'STAT 5432 Fa2013' expect(course['name']).to eq 'Whither Statistics' end end context 'if course does not exist in canvas' do before { subject.set_response(status: 404, body: '{"errors":[{"message":"The specified resource does not exist."}],"error_report_id":121214508}') } it 'returns a 404 response' do course = subject.course expect(course[:statusCode]).to eq 404 expect(course[:error]).to be_present expect(course).not_to include :body end end context 'on request failure' do let(:failing_request) { {method: :get} } let(:response) { subject.course } it_should_behave_like 'an unpaged Canvas proxy handling request failure' end end context 'when creating course site' do let(:api_path) { "accounts/#{canvas_account_id}/courses" } let(:course_name) { 'Project X' } let(:course_code) { 'Project X' } let(:canvas_account_id) { rand(999999).to_s } let(:sis_course_id) { 'PROJ:' + rand(999999).to_s } let(:term_id) { rand(9999).to_s } let(:request_options) do { :method => :post, :body => { 'account_id' => canvas_account_id, 'course' => { 'name' => 'Project X', 'course_code' => 'Project X', 'term_id' => term_id, 'sis_course_id' => sis_course_id } } } end let(:response_body) do { 'id' => rand(99999), 'account_id' => canvas_account_id, 'course_code' => course_code, 'enrollment_term_id' => term_id, 'name' => course_name, 'sis_course_id' => sis_course_id, 'workflow_state' => 'unpublished' } end it 'formats proper request' do expect(subject).to receive(:request_internal).with(api_path, request_options) subject.create(canvas_account_id, 'Project X', 'Project X', term_id, sis_course_id) end it 'returns response object' do subject.on_request(uri_matching: api_path, method: :post).set_response(status: 200, body: response_body.to_json) result = subject.create(canvas_account_id, 'Project X', 'Project X', term_id, sis_course_id) expect(result[:statusCode]).to eq 200 course_details = result[:body] expect(course_details['name']).to eq course_name expect(course_details['account_id']).to eq canvas_account_id expect(course_details['course_code']).to eq course_code expect(course_details['enrollment_term_id']).to eq term_id expect(course_details['sis_course_id']).to eq sis_course_id expect(course_details['workflow_state']).to eq 'unpublished' end context 'on request failure' do let(:failing_request) { {uri_matching: api_path, method: :post} } let(:response) { subject.create(canvas_account_id, 'Project X', 'Project X', term_id, sis_course_id) } it_should_behave_like 'an unpaged Canvas proxy handling request failure' end end end
39.806723
153
0.640068
7a69286b83d507561a088e179dff45d824bb77bb
1,150
require File.dirname(__FILE__) + '/../../spec_helper' # Returns an array containing the quotient and modulus obtained # by dividing num by aNumeric. If q, r = x.divmod(y), then # q = floor(float(x)/float(y)) # x = q*y + r describe "Numeric#divmod" do it "divmod right integers" do 13.divmod(4).should == [3,1] 4.divmod(13).should == [0,4] end it "divmod right integers and floats" do 13.divmod(4.0).should == [3,1] 4.divmod(13).should == [0,4] end it "divmod right the integers and floats" do 13.divmod(4.0).should == [3,1] 4.divmod(13).should == [0,4] end it "divmod right floats" do 13.0.divmod(4.0).should == [3.0,1.0] 4.0.divmod(13).should == [0.0,4.0] end it "should divmod right with bignums and integers" do (3**33).divmod( 100).should == [55590605665555, 23] end it "raise the expected exception" do should_raise(ArgumentError){ 13.divmod } should_raise(ZeroDivisionError){ 13.divmod(0) } should_raise(TypeError){ 13.divmod(nil) } should_raise(TypeError){ 13.divmod('test') } should_raise(TypeError){ 13.divmod(true) } end end
28.75
63
0.631304
f8acdcb51e9ec24f55afee8d9aac681e8d24e598
28,837
require 'cases/helper' require 'models/admin' require 'models/admin/account' require 'models/admin/randomly_named_c1' require 'models/admin/user' require 'models/binary' require 'models/book' require 'models/bulb' require 'models/category' require 'models/company' require 'models/computer' require 'models/course' require 'models/developer' require 'models/computer' require 'models/joke' require 'models/matey' require 'models/parrot' require 'models/pirate' require 'models/post' require 'models/randomly_named_c1' require 'models/reply' require 'models/ship' require 'models/task' require 'models/topic' require 'models/traffic_light' require 'models/treasure' require 'tempfile' class FixturesTest < ActiveRecord::TestCase self.use_instantiated_fixtures = true self.use_transactional_tests = false # other_topics fixture should not be included here fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries, :traffic_lights FIXTURES = %w( accounts binaries companies customers developers developers_projects entrants movies projects subscribers topics tasks ) MATCH_ATTRIBUTE_NAME = /[a-zA-Z][-\w]*/ def test_clean_fixtures FIXTURES.each do |name| fixtures = nil assert_nothing_raised { fixtures = create_fixtures(name).first } assert_kind_of(ActiveRecord::FixtureSet, fixtures) fixtures.each { |_name, fixture| fixture.each { |key, value| assert_match(MATCH_ATTRIBUTE_NAME, key) } } end end def test_broken_yaml_exception badyaml = Tempfile.new ['foo', '.yml'] badyaml.write 'a: : ' badyaml.flush dir = File.dirname badyaml.path name = File.basename badyaml.path, '.yml' assert_raises(ActiveRecord::Fixture::FormatError) do ActiveRecord::FixtureSet.create_fixtures(dir, name) end ensure badyaml.close badyaml.unlink end def test_create_fixtures fixtures = ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT, "parrots") assert Parrot.find_by_name('Curious George'), 'George is not in the database' assert fixtures.detect { |f| f.name == 'parrots' }, "no fixtures named 'parrots' in #{fixtures.map(&:name).inspect}" end def test_multiple_clean_fixtures fixtures_array = nil assert_nothing_raised { fixtures_array = create_fixtures(*FIXTURES) } assert_kind_of(Array, fixtures_array) fixtures_array.each { |fixtures| assert_kind_of(ActiveRecord::FixtureSet, fixtures) } end def test_create_symbol_fixtures fixtures = ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT, :collections, :collections => Course) { Course.connection } assert Course.find_by_name('Collection'), 'course is not in the database' assert fixtures.detect { |f| f.name == 'collections' }, "no fixtures named 'collections' in #{fixtures.map(&:name).inspect}" end def test_attributes topics = create_fixtures("topics").first assert_equal("The First Topic", topics["first"]["title"]) assert_nil(topics["second"]["author_email_address"]) end def test_inserts create_fixtures("topics") first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM topics WHERE author_name = 'David'") assert_equal("The First Topic", first_row["title"]) second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM topics WHERE author_name = 'Mary'") assert_nil(second_row["author_email_address"]) end if ActiveRecord::Base.connection.supports_migrations? def test_inserts_with_pre_and_suffix # Reset cache to make finds on the new table work ActiveRecord::FixtureSet.reset_cache ActiveRecord::Base.connection.create_table :prefix_other_topics_suffix do |t| t.column :title, :string t.column :author_name, :string t.column :author_email_address, :string t.column :written_on, :datetime t.column :bonus_time, :time t.column :last_read, :date t.column :content, :string t.column :approved, :boolean, :default => true t.column :replies_count, :integer, :default => 0 t.column :parent_id, :integer t.column :type, :string, :limit => 50 end # Store existing prefix/suffix old_prefix = ActiveRecord::Base.table_name_prefix old_suffix = ActiveRecord::Base.table_name_suffix # Set a prefix/suffix we can test against ActiveRecord::Base.table_name_prefix = 'prefix_' ActiveRecord::Base.table_name_suffix = '_suffix' other_topic_klass = Class.new(ActiveRecord::Base) do def self.name "OtherTopic" end end topics = [create_fixtures("other_topics")].flatten.first # This checks for a caching problem which causes a bug in the fixtures # class-level configuration helper. assert_not_nil topics, "Fixture data inserted, but fixture objects not returned from create" first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_other_topics_suffix WHERE author_name = 'David'") assert_not_nil first_row, "The prefix_other_topics_suffix table appears to be empty despite create_fixtures: the row with author_name = 'David' was not found" assert_equal("The First Topic", first_row["title"]) second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_other_topics_suffix WHERE author_name = 'Mary'") assert_nil(second_row["author_email_address"]) assert_equal :prefix_other_topics_suffix, topics.table_name.to_sym # This assertion should preferably be the last in the list, because calling # other_topic_klass.table_name sets a class-level instance variable assert_equal :prefix_other_topics_suffix, other_topic_klass.table_name.to_sym ensure # Restore prefix/suffix to its previous values ActiveRecord::Base.table_name_prefix = old_prefix ActiveRecord::Base.table_name_suffix = old_suffix ActiveRecord::Base.connection.drop_table :prefix_other_topics_suffix rescue nil end end def test_insert_with_datetime create_fixtures("tasks") first = Task.find(1) assert first end def test_logger_level_invariant level = ActiveRecord::Base.logger.level create_fixtures('topics') assert_equal level, ActiveRecord::Base.logger.level end def test_instantiation topics = create_fixtures("topics").first assert_kind_of Topic, topics["first"].find end def test_complete_instantiation assert_equal "The First Topic", @first.title end def test_fixtures_from_root_yml_with_instantiation # assert_equal 2, @accounts.size assert_equal 50, @unknown.credit_limit end def test_erb_in_fixtures assert_equal "fixture_5", @dev_5.name end def test_empty_yaml_fixture assert_not_nil ActiveRecord::FixtureSet.new( Account.connection, "accounts", Account, FIXTURES_ROOT + "/naked/yml/accounts") end def test_empty_yaml_fixture_with_a_comment_in_it assert_not_nil ActiveRecord::FixtureSet.new( Account.connection, "companies", Company, FIXTURES_ROOT + "/naked/yml/companies") end def test_nonexistent_fixture_file nonexistent_fixture_path = FIXTURES_ROOT + "/imnothere" #sanity check to make sure that this file never exists assert Dir[nonexistent_fixture_path+"*"].empty? assert_raise(Errno::ENOENT) do ActiveRecord::FixtureSet.new( Account.connection, "companies", Company, nonexistent_fixture_path) end end def test_dirty_dirty_yaml_file assert_raise(ActiveRecord::Fixture::FormatError) do ActiveRecord::FixtureSet.new( Account.connection, "courses", Course, FIXTURES_ROOT + "/naked/yml/courses") end end def test_omap_fixtures assert_nothing_raised do fixtures = ActiveRecord::FixtureSet.new(Account.connection, 'categories', Category, FIXTURES_ROOT + "/categories_ordered") fixtures.each.with_index do |(name, fixture), i| assert_equal "fixture_no_#{i}", name assert_equal "Category #{i}", fixture['name'] end end end def test_yml_file_in_subdirectory assert_equal(categories(:sub_special_1).name, "A special category in a subdir file") assert_equal(categories(:sub_special_1).class, SpecialCategory) end def test_subsubdir_file_with_arbitrary_name assert_equal(categories(:sub_special_3).name, "A special category in an arbitrarily named subsubdir file") assert_equal(categories(:sub_special_3).class, SpecialCategory) end def test_binary_in_fixtures data = File.open(ASSETS_ROOT + "/flowers.jpg", 'rb') { |f| f.read } data.force_encoding('ASCII-8BIT') data.freeze assert_equal data, @flowers.data end def test_serialized_fixtures assert_equal ["Green", "Red", "Orange"], traffic_lights(:uk).state end def test_fixtures_are_set_up_with_database_env_variable db_url_tmp = ENV['DATABASE_URL'] ENV['DATABASE_URL'] = "sqlite3::memory:" ActiveRecord::Base.stubs(:configurations).returns({}) test_case = Class.new(ActiveRecord::TestCase) do fixtures :accounts def test_fixtures assert accounts(:signals37) end end result = test_case.new(:test_fixtures).run assert result.passed?, "Expected #{result.name} to pass:\n#{result}" ensure ENV['DATABASE_URL'] = db_url_tmp end end class HasManyThroughFixture < ActiveSupport::TestCase def make_model(name) Class.new(ActiveRecord::Base) { define_singleton_method(:name) { name } } end def test_has_many_through_with_default_table_name pt = make_model "ParrotTreasure" parrot = make_model "Parrot" treasure = make_model "Treasure" pt.table_name = "parrots_treasures" pt.belongs_to :parrot, :class => parrot pt.belongs_to :treasure, :class => treasure parrot.has_many :parrot_treasures, :class => pt parrot.has_many :treasures, :through => :parrot_treasures parrots = File.join FIXTURES_ROOT, 'parrots' fs = ActiveRecord::FixtureSet.new parrot.connection, "parrots", parrot, parrots rows = fs.table_rows assert_equal load_has_and_belongs_to_many['parrots_treasures'], rows['parrots_treasures'] end def test_has_many_through_with_renamed_table pt = make_model "ParrotTreasure" parrot = make_model "Parrot" treasure = make_model "Treasure" pt.belongs_to :parrot, :class => parrot pt.belongs_to :treasure, :class => treasure parrot.has_many :parrot_treasures, :class => pt parrot.has_many :treasures, :through => :parrot_treasures parrots = File.join FIXTURES_ROOT, 'parrots' fs = ActiveRecord::FixtureSet.new parrot.connection, "parrots", parrot, parrots rows = fs.table_rows assert_equal load_has_and_belongs_to_many['parrots_treasures'], rows['parrot_treasures'] end def load_has_and_belongs_to_many parrot = make_model "Parrot" parrot.has_and_belongs_to_many :treasures parrots = File.join FIXTURES_ROOT, 'parrots' fs = ActiveRecord::FixtureSet.new parrot.connection, "parrots", parrot, parrots fs.table_rows end end if Account.connection.respond_to?(:reset_pk_sequence!) class FixturesResetPkSequenceTest < ActiveRecord::TestCase fixtures :accounts fixtures :companies def setup @instances = [Account.new(:credit_limit => 50), Company.new(:name => 'RoR Consulting'), Course.new(name: 'Test')] ActiveRecord::FixtureSet.reset_cache # make sure tables get reinitialized end def test_resets_to_min_pk_with_specified_pk_and_sequence @instances.each do |instance| model = instance.class model.delete_all model.connection.reset_pk_sequence!(model.table_name, model.primary_key, model.sequence_name) instance.save! assert_equal 1, instance.id, "Sequence reset for #{model.table_name} failed." end end def test_resets_to_min_pk_with_default_pk_and_sequence @instances.each do |instance| model = instance.class model.delete_all model.connection.reset_pk_sequence!(model.table_name) instance.save! assert_equal 1, instance.id, "Sequence reset for #{model.table_name} failed." end end def test_create_fixtures_resets_sequences_when_not_cached @instances.each do |instance| max_id = create_fixtures(instance.class.table_name).first.fixtures.inject(0) do |_max_id, (_, fixture)| fixture_id = fixture['id'].to_i fixture_id > _max_id ? fixture_id : _max_id end # Clone the last fixture to check that it gets the next greatest id. instance.save! assert_equal max_id + 1, instance.id, "Sequence reset for #{instance.class.table_name} failed." end end end end class FixturesWithoutInstantiationTest < ActiveRecord::TestCase self.use_instantiated_fixtures = false fixtures :topics, :developers, :accounts def test_without_complete_instantiation assert !defined?(@first) assert !defined?(@topics) assert !defined?(@developers) assert !defined?(@accounts) end def test_fixtures_from_root_yml_without_instantiation assert !defined?(@unknown), "@unknown is not defined" end def test_visibility_of_accessor_method assert_equal false, respond_to?(:topics, false), "should be private method" assert_equal true, respond_to?(:topics, true), "confirm to respond surely" end def test_accessor_methods assert_equal "The First Topic", topics(:first).title assert_equal "Jamis", developers(:jamis).name assert_equal 50, accounts(:signals37).credit_limit end def test_accessor_methods_with_multiple_args assert_equal 2, topics(:first, :second).size assert_raise(StandardError) { topics([:first, :second]) } end def test_reloading_fixtures_through_accessor_methods assert_equal "The First Topic", topics(:first).title @loaded_fixtures['topics']['first'].expects(:find).returns(stub(:title => "Fresh Topic!")) assert_equal "Fresh Topic!", topics(:first, true).title end end class FixturesWithoutInstanceInstantiationTest < ActiveRecord::TestCase self.use_instantiated_fixtures = true self.use_instantiated_fixtures = :no_instances fixtures :topics, :developers, :accounts def test_without_instance_instantiation assert !defined?(@first), "@first is not defined" end end class TransactionalFixturesTest < ActiveRecord::TestCase self.use_instantiated_fixtures = true self.use_transactional_tests = true fixtures :topics def test_destroy assert_not_nil @first @first.destroy end def test_destroy_just_kidding assert_not_nil @first end end class MultipleFixturesTest < ActiveRecord::TestCase fixtures :topics fixtures :developers, :accounts def test_fixture_table_names assert_equal %w(topics developers accounts), fixture_table_names end end class SetupTest < ActiveRecord::TestCase # fixtures :topics def setup @first = true end def test_nothing end end class SetupSubclassTest < SetupTest def setup super @second = true end def test_subclassing_should_preserve_setups assert @first assert @second end end class OverlappingFixturesTest < ActiveRecord::TestCase fixtures :topics, :developers fixtures :developers, :accounts def test_fixture_table_names assert_equal %w(topics developers accounts), fixture_table_names end end class ForeignKeyFixturesTest < ActiveRecord::TestCase fixtures :fk_test_has_pk, :fk_test_has_fk # if foreign keys are implemented and fixtures # are not deleted in reverse order then this test # case will raise StatementInvalid def test_number1 assert true end def test_number2 assert true end end class OverRideFixtureMethodTest < ActiveRecord::TestCase fixtures :topics def topics(name) topic = super topic.title = 'omg' topic end def test_fixture_methods_can_be_overridden x = topics :first assert_equal 'omg', x.title end end class CheckSetTableNameFixturesTest < ActiveRecord::TestCase set_fixture_class :funny_jokes => Joke fixtures :funny_jokes # Set to false to blow away fixtures cache and ensure our fixtures are loaded # and thus takes into account our set_fixture_class self.use_transactional_tests = false def test_table_method assert_kind_of Joke, funny_jokes(:a_joke) end end class FixtureNameIsNotTableNameFixturesTest < ActiveRecord::TestCase set_fixture_class :items => Book fixtures :items # Set to false to blow away fixtures cache and ensure our fixtures are loaded # and thus takes into account our set_fixture_class self.use_transactional_tests = false def test_named_accessor assert_kind_of Book, items(:dvd) end end class FixtureNameIsNotTableNameMultipleFixturesTest < ActiveRecord::TestCase set_fixture_class :items => Book, :funny_jokes => Joke fixtures :items, :funny_jokes # Set to false to blow away fixtures cache and ensure our fixtures are loaded # and thus takes into account our set_fixture_class self.use_transactional_tests = false def test_named_accessor_of_differently_named_fixture assert_kind_of Book, items(:dvd) end def test_named_accessor_of_same_named_fixture assert_kind_of Joke, funny_jokes(:a_joke) end end class CustomConnectionFixturesTest < ActiveRecord::TestCase set_fixture_class :courses => Course fixtures :courses self.use_transactional_tests = false def test_leaky_destroy assert_nothing_raised { courses(:ruby) } courses(:ruby).destroy end def test_it_twice_in_whatever_order_to_check_for_fixture_leakage test_leaky_destroy end end class TransactionalFixturesOnCustomConnectionTest < ActiveRecord::TestCase set_fixture_class :courses => Course fixtures :courses self.use_transactional_tests = true def test_leaky_destroy assert_nothing_raised { courses(:ruby) } courses(:ruby).destroy end def test_it_twice_in_whatever_order_to_check_for_fixture_leakage test_leaky_destroy end end class InvalidTableNameFixturesTest < ActiveRecord::TestCase fixtures :funny_jokes # Set to false to blow away fixtures cache and ensure our fixtures are loaded # and thus takes into account our lack of set_fixture_class self.use_transactional_tests = false def test_raises_error assert_raise ActiveRecord::FixtureClassNotFound do funny_jokes(:a_joke) end end end class CheckEscapedYamlFixturesTest < ActiveRecord::TestCase set_fixture_class :funny_jokes => Joke fixtures :funny_jokes # Set to false to blow away fixtures cache and ensure our fixtures are loaded # and thus takes into account our set_fixture_class self.use_transactional_tests = false def test_proper_escaped_fixture assert_equal "The \\n Aristocrats\nAte the candy\n", funny_jokes(:another_joke).name end end class DevelopersProject; end class ManyToManyFixturesWithClassDefined < ActiveRecord::TestCase fixtures :developers_projects def test_this_should_run_cleanly assert true end end class FixturesBrokenRollbackTest < ActiveRecord::TestCase def blank_setup @fixture_connections = [ActiveRecord::Base.connection] end alias_method :ar_setup_fixtures, :setup_fixtures alias_method :setup_fixtures, :blank_setup alias_method :setup, :blank_setup def blank_teardown; end alias_method :ar_teardown_fixtures, :teardown_fixtures alias_method :teardown_fixtures, :blank_teardown alias_method :teardown, :blank_teardown def test_no_rollback_in_teardown_unless_transaction_active assert_equal 0, ActiveRecord::Base.connection.open_transactions assert_raise(RuntimeError) { ar_setup_fixtures } assert_equal 0, ActiveRecord::Base.connection.open_transactions assert_nothing_raised { ar_teardown_fixtures } assert_equal 0, ActiveRecord::Base.connection.open_transactions end private def load_fixtures(config) raise 'argh' end end class LoadAllFixturesTest < ActiveRecord::TestCase def test_all_there self.class.fixture_path = FIXTURES_ROOT + "/all" self.class.fixtures :all if File.symlink? FIXTURES_ROOT + "/all/admin" assert_equal %w(admin/accounts admin/users developers people tasks), fixture_table_names.sort end ensure ActiveRecord::FixtureSet.reset_cache end end class LoadAllFixturesWithPathnameTest < ActiveRecord::TestCase def test_all_there self.class.fixture_path = Pathname.new(FIXTURES_ROOT).join('all') self.class.fixtures :all if File.symlink? FIXTURES_ROOT + "/all/admin" assert_equal %w(admin/accounts admin/users developers people tasks), fixture_table_names.sort end ensure ActiveRecord::FixtureSet.reset_cache end end class FasterFixturesTest < ActiveRecord::TestCase self.use_transactional_tests = false fixtures :categories, :authors def load_extra_fixture(name) fixture = create_fixtures(name).first assert fixture.is_a?(ActiveRecord::FixtureSet) @loaded_fixtures[fixture.table_name] = fixture end def test_cache assert ActiveRecord::FixtureSet.fixture_is_cached?(ActiveRecord::Base.connection, 'categories') assert ActiveRecord::FixtureSet.fixture_is_cached?(ActiveRecord::Base.connection, 'authors') assert_no_queries do create_fixtures('categories') create_fixtures('authors') end load_extra_fixture('posts') assert ActiveRecord::FixtureSet.fixture_is_cached?(ActiveRecord::Base.connection, 'posts') self.class.setup_fixture_accessors :posts assert_equal 'Welcome to the weblog', posts(:welcome).title end end class FoxyFixturesTest < ActiveRecord::TestCase fixtures :parrots, :parrots_pirates, :pirates, :treasures, :mateys, :ships, :computers, :developers, :"admin/accounts", :"admin/users", :live_parrots, :dead_parrots if ActiveRecord::Base.connection.adapter_name == 'PostgreSQL' require 'models/uuid_parent' require 'models/uuid_child' fixtures :uuid_parents, :uuid_children end def test_identifies_strings assert_equal(ActiveRecord::FixtureSet.identify("foo"), ActiveRecord::FixtureSet.identify("foo")) assert_not_equal(ActiveRecord::FixtureSet.identify("foo"), ActiveRecord::FixtureSet.identify("FOO")) end def test_identifies_symbols assert_equal(ActiveRecord::FixtureSet.identify(:foo), ActiveRecord::FixtureSet.identify(:foo)) end def test_identifies_consistently assert_equal 207281424, ActiveRecord::FixtureSet.identify(:ruby) assert_equal 1066363776, ActiveRecord::FixtureSet.identify(:sapphire_2) assert_equal 'f92b6bda-0d0d-5fe1-9124-502b18badded', ActiveRecord::FixtureSet.identify(:daddy, :uuid) assert_equal 'b4b10018-ad47-595d-b42f-d8bdaa6d01bf', ActiveRecord::FixtureSet.identify(:sonny, :uuid) end TIMESTAMP_COLUMNS = %w(created_at created_on updated_at updated_on) def test_populates_timestamp_columns TIMESTAMP_COLUMNS.each do |property| assert_not_nil(parrots(:george).send(property), "should set #{property}") end end def test_does_not_populate_timestamp_columns_if_model_has_set_record_timestamps_to_false TIMESTAMP_COLUMNS.each do |property| assert_nil(ships(:black_pearl).send(property), "should not set #{property}") end end def test_populates_all_columns_with_the_same_time last = nil TIMESTAMP_COLUMNS.each do |property| current = parrots(:george).send(property) last ||= current assert_equal(last, current) last = current end end def test_only_populates_columns_that_exist assert_not_nil(pirates(:blackbeard).created_on) assert_not_nil(pirates(:blackbeard).updated_on) end def test_preserves_existing_fixture_data assert_equal(2.weeks.ago.to_date, pirates(:redbeard).created_on.to_date) assert_equal(2.weeks.ago.to_date, pirates(:redbeard).updated_on.to_date) end def test_generates_unique_ids assert_not_nil(parrots(:george).id) assert_not_equal(parrots(:george).id, parrots(:louis).id) end def test_automatically_sets_primary_key assert_not_nil(ships(:black_pearl)) end def test_preserves_existing_primary_key assert_equal(2, ships(:interceptor).id) end def test_resolves_belongs_to_symbols assert_equal(parrots(:george), pirates(:blackbeard).parrot) end def test_ignores_belongs_to_symbols_if_association_and_foreign_key_are_named_the_same assert_equal(developers(:david), computers(:workstation).developer) end def test_supports_join_tables assert(pirates(:blackbeard).parrots.include?(parrots(:george))) assert(pirates(:blackbeard).parrots.include?(parrots(:louis))) assert(parrots(:george).pirates.include?(pirates(:blackbeard))) end def test_supports_inline_habtm assert(parrots(:george).treasures.include?(treasures(:diamond))) assert(parrots(:george).treasures.include?(treasures(:sapphire))) assert(!parrots(:george).treasures.include?(treasures(:ruby))) end def test_supports_inline_habtm_with_specified_id assert(parrots(:polly).treasures.include?(treasures(:ruby))) assert(parrots(:polly).treasures.include?(treasures(:sapphire))) assert(!parrots(:polly).treasures.include?(treasures(:diamond))) end def test_supports_yaml_arrays assert(parrots(:louis).treasures.include?(treasures(:diamond))) assert(parrots(:louis).treasures.include?(treasures(:sapphire))) end def test_strips_DEFAULTS_key assert_raise(StandardError) { parrots(:DEFAULTS) } # this lets us do YAML defaults and not have an extra fixture entry %w(sapphire ruby).each { |t| assert(parrots(:davey).treasures.include?(treasures(t))) } end def test_supports_label_interpolation assert_equal("frederick", parrots(:frederick).name) end def test_supports_label_string_interpolation assert_equal("X marks the spot!", pirates(:mark).catchphrase) end def test_supports_label_interpolation_for_fixnum_label assert_equal("#1 pirate!", pirates(1).catchphrase) end def test_supports_polymorphic_belongs_to assert_equal(pirates(:redbeard), treasures(:sapphire).looter) assert_equal(parrots(:louis), treasures(:ruby).looter) end def test_only_generates_a_pk_if_necessary m = Matey.first m.pirate = pirates(:blackbeard) m.target = pirates(:redbeard) end def test_supports_sti assert_kind_of DeadParrot, parrots(:polly) assert_equal pirates(:blackbeard), parrots(:polly).killer end def test_supports_sti_with_respective_files assert_kind_of LiveParrot, live_parrots(:dusty) assert_kind_of DeadParrot, dead_parrots(:deadbird) assert_equal pirates(:blackbeard), dead_parrots(:deadbird).killer end def test_namespaced_models assert admin_accounts(:signals37).users.include?(admin_users(:david)) assert_equal 2, admin_accounts(:signals37).users.size end end class ActiveSupportSubclassWithFixturesTest < ActiveRecord::TestCase fixtures :parrots # This seemingly useless assertion catches a bug that caused the fixtures # setup code call nil[] def test_foo assert_equal parrots(:louis), Parrot.find_by_name("King Louis") end end class CustomNameForFixtureOrModelTest < ActiveRecord::TestCase ActiveRecord::FixtureSet.reset_cache set_fixture_class :randomly_named_a9 => ClassNameThatDoesNotFollowCONVENTIONS, :'admin/randomly_named_a9' => Admin::ClassNameThatDoesNotFollowCONVENTIONS1, 'admin/randomly_named_b0' => Admin::ClassNameThatDoesNotFollowCONVENTIONS2 fixtures :randomly_named_a9, 'admin/randomly_named_a9', :'admin/randomly_named_b0' def test_named_accessor_for_randomly_named_fixture_and_class assert_kind_of ClassNameThatDoesNotFollowCONVENTIONS, randomly_named_a9(:first_instance) end def test_named_accessor_for_randomly_named_namespaced_fixture_and_class assert_kind_of Admin::ClassNameThatDoesNotFollowCONVENTIONS1, admin_randomly_named_a9(:first_instance) assert_kind_of Admin::ClassNameThatDoesNotFollowCONVENTIONS2, admin_randomly_named_b0(:second_instance) end def test_table_name_is_defined_in_the_model assert_equal 'randomly_named_table2', ActiveRecord::FixtureSet::all_loaded_fixtures["admin/randomly_named_a9"].table_name assert_equal 'randomly_named_table2', Admin::ClassNameThatDoesNotFollowCONVENTIONS1.table_name end end class FixturesWithDefaultScopeTest < ActiveRecord::TestCase fixtures :bulbs test "inserts fixtures excluded by a default scope" do assert_equal 1, Bulb.count assert_equal 2, Bulb.unscoped.count end test "allows access to fixtures excluded by a default scope" do assert_equal "special", bulbs(:special).name end end
32.076752
164
0.750494
0378f1dd2cb09aeeef8608d6cd10f3e5e787bc38
3,810
# frozen_string_literal: true describe 'Ridgepole::Client#diff -> migrate', condition: '>= 5.1.0' do context 'with warning' do let(:actual_dsl) do erbh(<<-ERB) create_table "dept_manager", force: :cascade do |t| t.string "dept_no", limit: 4, null: false t.date "from_date", null: false t.date "to_date", null: false end create_table "employees", id: :serial, force: :cascade do |t| t.integer "emp_no", null: false t.date "birth_date", null: false t.string "first_name", limit: 14, null: false t.string "last_name", limit: 16, null: false t.string "gender", limit: 1, null: false t.date "hire_date", null: false end ERB end let(:expected_dsl) do erbh(<<-ERB) create_table "dept_manager", force: :cascade do |t| t.string "dept_no", limit: 4, null: false t.date "from_date", null: false t.date "to_date", null: false t.bigint "employee_id" end create_table "employees", id: :serial, force: :cascade do |t| t.integer "emp_no", null: false t.date "birth_date", null: false t.string "first_name", limit: 14, null: false t.string "last_name", limit: 16, null: false t.string "gender", limit: 1, null: false t.date "hire_date", null: false end ERB end before { subject.diff(actual_dsl).migrate } subject { client(check_relation_type: 'bigserial') } it { expect(Ridgepole::Logger.instance).to receive(:warn).with(<<-MSG) [WARNING] Relation column type is different. employees.id: {:type=>:integer} dept_manager.employee_id: {:type=>:bigint} MSG delta = subject.diff(expected_dsl) expect(delta.differ?).to be_truthy expect(subject.dump).to match_ruby actual_dsl delta.migrate expect(subject.dump).to match_ruby expected_dsl } end context 'with warning' do let(:actual_dsl) do erbh(<<-ERB) create_table "dept_manager", force: :cascade do |t| t.string "dept_no", limit: 4, null: false t.date "from_date", null: false t.date "to_date", null: false end create_table "employees", id: :serial, force: :cascade do |t| t.integer "emp_no", null: false t.date "birth_date", null: false t.string "first_name", limit: 14, null: false t.string "last_name", limit: 16, null: false t.string "gender", limit: 1, null: false t.date "hire_date", null: false end ERB end let(:expected_dsl) do erbh(<<-ERB) create_table "dept_manager", force: :cascade do |t| t.string "dept_no", limit: 4, null: false t.date "from_date", null: false t.date "to_date", null: false t.integer "employee_id" end create_table "employees", id: :serial, force: :cascade do |t| t.integer "emp_no", null: false t.date "birth_date", null: false t.string "first_name", limit: 14, null: false t.string "last_name", limit: 16, null: false t.string "gender", limit: 1, null: false t.date "hire_date", null: false end ERB end before { subject.diff(actual_dsl).migrate } subject { client(check_relation_type: 'bigserial') } it { expect(Ridgepole::Logger.instance).to_not receive(:warn) delta = subject.diff(expected_dsl) expect(delta.differ?).to be_truthy expect(subject.dump).to match_ruby actual_dsl delta.migrate expect(subject.dump).to match_ruby expected_dsl } end end
33.130435
71
0.581102
879b5ed5afd41749cdf7391fd2cb678d22eb304a
672
class LoginController < ApplicationController before_action :authenticate def index #render plain: "current_user_id: #{session[:current_user_id]} #{current_user.inspect}" #raise current_user.class.to_s redirect_to '/TaskBoard/' if current_user.is_a?(User) end private # Basic auth against local user table def authenticate authenticate_or_request_with_http_basic("myTaskboard Login") do |email, password| user = User.where(email: email, password: password).first rescue nil redirect_to controller: :login, action: :index, status: 403 and return if user.nil? session[:current_user_id] = user.id #rescue nil end end end
28
90
0.739583
ed24b8f94ac4f083b16ad0478f2e6a2447698b72
126
class RemoveActiveFromTeams < ActiveRecord::Migration[5.0] def change remove_column :teams, :active, :boolean end end
21
58
0.753968
1dc5c6abb2e133922a001c5e043b790de6980195
8,524
# frozen_string_literal: true require "test_helper" class IntegrationTest < ActionDispatch::IntegrationTest test "rendering component in a view" do get "/" assert_response :success assert_select("div", "Foo\n bar") end if Rails.version.to_f >= 6.1 test "rendering component with template annotations enabled" do get "/" assert_response :success assert_includes response.body, "BEGIN app/components/erb_component.rb" assert_select("div", "Foo\n bar") end end test "rendering component in a controller" do get "/controller_inline_baseline" assert_select("div", "bar") assert_response :success baseline_response = response.body get "/controller_inline" assert_select("div", "bar") assert_response :success inline_response = response.body assert_includes inline_response, baseline_response end test "rendering component in a controller using #render_to_string" do get "/controller_inline_baseline" assert_select("div", "bar") assert_response :success baseline_response = response.body get "/controller_to_string" assert_select("div", "bar") assert_response :success to_string_response = response.body assert_includes to_string_response, baseline_response end test "rendering component with content" do get "/content" assert_response :success assert_select "div.State--green" assert_select "div[title='Status: Open']" assert_includes response.body, "Open" end test "rendering component with content_for" do get "/content_areas" assert_response :success assert_select(".title h1", "Hi!") assert_select(".body p", "Did you know that 1+1=2?") assert_select(".footer h3", "Bye!") end test "rendering component with a partial" do get "/partial" assert_response :success assert_select("div", "hello,partial world!", count: 2) end test "rendering component without variant" do get "/variants" assert_response :success assert_includes response.body, "Default" end test "rendering component with tablet variant" do get "/variants?variant=tablet" assert_response :success assert_includes response.body, "Tablet" end test "rendering component several times with different variants" do get "/variants?variant=tablet" assert_response :success assert_includes response.body, "Tablet" get "/variants?variant=phone" assert_response :success assert_includes response.body, "Phone" get "/variants" assert_response :success assert_includes response.body, "Default" get "/variants?variant=tablet" assert_response :success assert_includes response.body, "Tablet" get "/variants?variant=phone" assert_response :success assert_includes response.body, "Phone" end test "rendering component with caching" do Rails.cache.clear ActionController::Base.perform_caching = true get "/cached?version=1" assert_response :success assert_includes response.body, "Cache 1" get "/cached?version=2" assert_response :success assert_includes response.body, "Cache 1" ActionController::Base.perform_caching = false Rails.cache.clear end test "optional rendering component depending on request context" do get "/render_check" assert_response :success assert_includes response.body, "Rendered" cookies[:shown] = true get "/render_check" assert_response :success refute_includes response.body, "Rendered" end test "renders component preview" do get "/rails/view_components/my_component/default" assert_includes response.body, "<div>hello,world!</div>" end test "renders preview component default preview" do get "/rails/view_components/preview_component/default" assert_includes response.body, "Click me!" end test "renders preview component default preview ignoring params" do get "/rails/view_components/preview_component/default?cta=CTA+from+params" assert_includes response.body, "Click me!" refute_includes response.body, "CTA from params" end test "renders preview component with_cta preview" do get "/rails/view_components/preview_component/without_cta" assert_includes response.body, "More lorem..." end test "renders preview component with content preview" do get "/rails/view_components/preview_component/with_content" assert_includes response.body, "some content" end test "renders preview component with tag helper-generated content preview" do get "/rails/view_components/preview_component/with_tag_helper_in_content" assert_includes response.body, "<span>some content</span>" end test "renders preview component with params preview with default values" do get "/rails/view_components/preview_component/with_params" assert_includes response.body, "Default CTA" assert_includes response.body, "Default title" end test "renders preview component with params preview with one param" do get "/rails/view_components/preview_component/with_params?cta=CTA+from+params" assert_includes response.body, "CTA from params" assert_includes response.body, "Default title" end test "renders preview component with params preview with multiple params" do get "/rails/view_components/preview_component/with_params?cta=CTA+from+params&title=Title+from+params" assert_includes response.body, "CTA from params" assert_includes response.body, "Title from params" end test "renders preview component with params preview ignoring unsupported params" do get "/rails/view_components/preview_component/with_params?cta=CTA+from+params&label=Label+from+params" assert_includes response.body, "CTA from params" assert_includes response.body, "Default title" refute_includes response.body, "Label from params" end test "renders badge component open preview" do get "/rails/view_components/issues/badge_component/open" assert_includes response.body, "Open" end test "renders badge component closed preview" do get "/rails/view_components/issues/badge_component/closed" assert_includes response.body, "Closed" end test "test preview renders" do get "/rails/view_components/preview_component/default" assert_select(".preview-component .btn", "Click me!") end test "test preview renders with layout" do get "/rails/view_components/my_component/default" assert_includes response.body, "ViewComponent - Admin - Test" assert_select("div", "hello,world!") end test "test preview renders without layout" do get "/rails/view_components/no_layout/default" assert_select("div", "hello,world!") end test "test preview renders application's layout by default" do get "/rails/view_components/preview_component/default" assert_select "title", "ViewComponent - Test" end test "test preview index renders rails application layout by default" do get "/rails/view_components" assert_select "title", "Component Previews" end test "test preview index of a component renders rails application layout by default" do get "/rails/view_components/preview_component" assert_select "title", "Component Previews for preview_component" end test "test preview related views are being rendered correctly" do get "/rails/view_components" assert_select "title", "Component Previews" get "/rails/view_components/preview_component/default" assert_select "title", "ViewComponent - Test" get "/rails/view_components/preview_component" assert_select "title", "Component Previews for preview_component" end test "renders collections" do get "/products" assert_select("h1", text: "Products for sale") assert_select("h1", text: "Product", count: 2) assert_select("h2", text: "Radio clock") assert_select("h2", text: "Mints") assert_select("p", text: "Today only", count: 2) assert_select("p", text: "Radio clock counter: 1") assert_select("p", text: "Mints counter: 2") end test "renders the previews in the configured route" do with_preview_route("/previews") do get "/previews" assert_select "title", "Component Previews" get "/previews/preview_component/default" assert_select "title", "ViewComponent - Test" get "/previews/preview_component" assert_select "title", "Component Previews for preview_component" end end end
28.700337
106
0.731699
11790e3766c70cdd84a798ef9a7aea9eee87c278
2,828
# coding: utf-8 =begin File : mvm_fw_test_gcov_helper.rb Author : Francesco Prelz e-mail : [email protected] Revision history : 6-May-2020 Original release Description: Digest gcov output and produce an overall coverage report. =end class Mvm_Fw_Test_Gcov_Helper attr_reader(:chsh, :cperc, :checked_lines, :total_lines, :gcov_files, :report) @total_lines = 0 @checked_lines = 0 @gcov_files = [] @chsh = {} @cperc = 0 @report = nil @target_dir = nil; @proj_str = nil def initialize(dir, csubstr) @curdir = Dir.pwd @target_dir = dir @proj_str = csubstr end def evaluate() @curdir = Dir.pwd if ((@target_dir) && (@target_dir.length > 0)) Dir.chdir(@target_dir) end @checked_lines = 0 @total_lines = 0 @chsh = {} @gcov_files = [] # Example gcov output format: # File '/usr/include/c++/8/tuple' # Lines executed:100.00% of 36 # Creating 'tuple.gcov' cur_file = nil file_used = true IO::popen("make gcov",'r',:err => File::NULL) do |f| f.each_line do |l| if (m=/File +'([^']+)'/.match(l)) if ((@proj_str) && (@proj_str.length > 0) && (!m[1].include? @proj_str)) cur_file = nil next end tfile = File.basename(m[1]) cur_file = tfile file_used = false elsif (m=/Lines executed: *([0-9\.]+)% +of +([0-9]+)/.match(l)) if ((cur_file) && (!file_used)) cur_frac = m[1].to_f / 100 cur_lines = m[2].to_f chk_lines = (cur_lines * cur_frac).round @total_lines += cur_lines.to_i @checked_lines += chk_lines @chsh[cur_file] = { :lines => cur_lines, :checked => chk_lines } file_used = true end elsif (m=/Creating +'([^']+)'/.match(l)) if (cur_file) @gcov_files.push(m[1]) end end end end @cperc = 0 if (@total_lines > 0) @cperc = (@checked_lines.to_f / @total_lines.to_f) * 100 end if (@proj_str != nil) Dir.chdir(@curdir) @report = @proj_str + ": " else @report = "" end @report << "coverage: " + @checked_lines.to_s + "/" + @total_lines.to_s + sprintf(" - %5.1f%%", @cperc) if ((@target_dir) && (@target_dir.length > 0)) Dir.chdir(@curdir) end end def reset() @curdir = Dir.pwd if ((@target_dir) && (@target_dir.length > 0)) Dir.chdir(@target_dir) end system("make clean_gcov", :err => File::NULL, :out => File::NULL) @checked_lines = 0 @total_lines = 0 @chsh = {} if ((@target_dir) && (@target_dir.length > 0)) Dir.chdir(@curdir) end end end
23.764706
76
0.531471
62e8a114ba1d44d369ecf9525ee01b156e0b5ee8
174
class AddNumMetareviewsRequiredToAssignments < ActiveRecord::Migration def change add_column :assignments, :num_metareviews_required, :integer, :default => 3 end end
29
79
0.798851
1cf94ac358d0f2d7f2dcb130fb617af60a2f080a
4,819
# frozen_string_literal: true require 'test_helper' class PaginatableArrayTest < ActiveSupport::TestCase setup do @array = Kaminari::PaginatableArray.new((1..100).to_a) end test 'initial state' do assert_equal 0, Kaminari::PaginatableArray.new.count end test 'specifying limit and offset when initializing' do assert_equal 3, Kaminari::PaginatableArray.new((1..100).to_a, limit: 10, offset: 20).current_page end sub_test_case '#page' do def assert_first_page_of_array(arr) assert_equal 25, arr.count assert_equal 1, arr.current_page assert_equal 1, arr.first end def assert_blank_array_page(arr) assert_equal 0, arr.count end test 'page 1' do assert_first_page_of_array @array.page(1) end test 'page 2' do arr = @array.page 2 assert_equal 25, arr.count assert_equal 2, arr.current_page assert_equal 26, arr.first end test 'page without an argument' do assert_first_page_of_array @array.page end test 'page < 1' do assert_first_page_of_array @array.page(0) end test 'page > max page' do assert_blank_array_page @array.page(5) end end sub_test_case '#per' do test 'page 1 per 5' do arr = @array.page(1).per(5) assert_equal 5, arr.count assert_equal 1, arr.first end test 'page 1 per 0' do assert_equal 0, @array.page(1).per(0).count end end sub_test_case '#padding' do test 'page 1 per 5 padding 1' do arr = @array.page(1).per(5).padding(1) assert_equal 5, arr.count assert_equal 2, arr.first end test 'page 1 per 5 padding "1" (as string)' do arr = @array.page(1).per(5).padding('1') assert_equal 5, arr.count assert_equal 2, arr.first end test 'page 19 per 5 padding 5' do arr = @array.page(19).per(5).padding(5) assert_equal 19, arr.current_page assert_equal 19, arr.total_pages end test 'per 25, padding 25' do assert_equal 3, @array.page(1).padding(25).total_pages end test 'Negative padding' do assert_raise(ArgumentError) { @array.page(1).per(5).padding(-1) } end end sub_test_case '#total_pages' do test 'per 25 (default)' do assert_equal 4, @array.page.total_pages end test 'per 7' do assert_equal 15, @array.page(2).per(7).total_pages end test 'per 65536' do assert_equal 1, @array.page(50).per(65536).total_pages end test 'per 0' do assert_raise(Kaminari::ZeroPerPageOperation) { @array.page(50).per(0).total_pages } end test 'per -1 (using default)' do assert_equal 4, @array.page(5).per(-1).total_pages end test 'per "String value that can not be converted into Number" (using default)' do assert_equal 4, @array.page(5).per('aho').total_pages end end sub_test_case '#current_page' do test 'any page, per 0' do assert_raise(Kaminari::ZeroPerPageOperation) { @array.page.per(0).current_page } end test 'page 1' do assert_equal 1, @array.page(1).current_page end test 'page 2' do assert_equal 2, @array.page(2).per(3).current_page end end sub_test_case '#next_page' do test 'page 1' do assert_equal 2, @array.page.next_page end test 'page 5' do assert_nil @array.page(5).next_page end end sub_test_case '#prev_page' do test 'page 1' do assert_nil @array.page.prev_page end test 'page 3' do assert_equal 2, @array.page(3).prev_page end test 'page 5' do assert_nil @array.page(5).prev_page end end sub_test_case '#count' do test 'page 1' do assert_equal 25, @array.page.count end test 'page 2' do assert_equal 25, @array.page(2).count end end sub_test_case 'when setting total count explicitly' do test 'array 1..10, page 5, per 10, total_count 9999' do arr = Kaminari::PaginatableArray.new((1..10).to_a, total_count: 9999).page(5).per(10) assert_equal 10, arr.count assert_equal 1, arr.first assert_equal 5, arr.current_page assert_equal 9999, arr.total_count end test 'array 1..15, page 1, per 10, total_count 15' do arr = Kaminari::PaginatableArray.new((1..15).to_a, total_count: 15).page(1).per(10) assert_equal 10, arr.count assert_equal 1, arr.first assert_equal 1, arr.current_page assert_equal 15, arr.total_count end test 'array 1..25, page 2, per 10, total_count 15' do arr = Kaminari::PaginatableArray.new((1..25).to_a, total_count: 15).page(2).per(10) assert_equal 5, arr.count assert_equal 11, arr.first assert_equal 2, arr.current_page assert_equal 15, arr.total_count end end end
23.975124
101
0.650965
791209c7c9be93d54ec446158de9cff1f0e1373d
1,183
require 'json' module Razorpay # Entity class is the base class for all Razorpay objects # This saves data in a hash internally, and makes it available # via direct methods class Entity attr_reader :attributes def initialize(attributes) @attributes = attributes end # This method fakes attr_reader, but uses # the @attributes hash as the source, instead of # instance variables def method_missing(name) if @attributes.key? name.to_s @attributes[name.to_s] else super end end def respond_to_missing?(method_name, include_private = false) @attributes.key?(method_name.to_s) || super end # Public: Convert the Entity object to JSON # Returns the JSON representation of the Entity (as a string) def to_json(*args) @attributes.to_json(*args) end # Mutates the entity in accordance with # the block passed to this construct # # Used to implement bang methods, by calling # the non-bang method in the passed block def with_a_bang mutated_entity = yield @attributes = mutated_entity.attributes mutated_entity end end end
25.170213
65
0.679628
28184d3618077e0318994b67de8f034687d564b3
120
require 'spec_helper' describe "reports/edit.html.erb" do pending "add some examples to (or delete) #{__FILE__}" end
20
56
0.741667
b95e3690a72bf33ab89d87f663acc3944d433262
237
module Spree module Api module V2 module Platform class PromotionCategorySerializer < BaseSerializer include ResourceSerializerConcern has_many :promotions end end end end end
16.928571
58
0.64557
5de3a3e8a1deacb738e0d6945687d9f9445dfcac
3,481
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle caching. if Rails.root.join('tmp', 'caching-dev.txt').exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :memory_store end # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Highlight code that triggered database queries in logs. config.active_record.verbose_query_logs = true # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = false # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker config.aws_region = ENV['AWS_REGION'] config.hub_environments = JSON.parse("{ \"development\": { \"bucket\": \"development-bucket\", \"hub_config_host\": \"http://localhost:50240\", \"secure_header\": \"false\" } }") config.cognito_aws_access_key_id = ENV['COGNITO_AWS_ACCESS_KEY_ID'] config.cognito_aws_secret_access_key = ENV['COGNITO_AWS_SECRET_ACCESS_KEY'] config.cognito_client_id = ENV['AWS_COGNITO_CLIENT_ID'] config.cognito_user_pool_id = ENV['AWS_COGNITO_USER_POOL_ID'] # Increase the timeout for devs config.session_expiry = 120.minutes config.session_inactivity = 120.minutes # To seed Cognito and check data integrity (uncomment, if needed to be run): config.after_initialize do # require 'auth/initial_seeder' # InitialSeeder.new # require 'data/integrity_checker' IntegrityChecker.new end config.after_initialize do require 'polling/scheduler' SCHEDULER = Polling::Scheduler.new require 'api/hub_config_api' HUB_CONFIG_API = HubConfigApi.new require 'polling/dev_cert_status_updater' CERT_STATUS_UPDATER = DevCertStatusUpdater.new end config.scheduler_polling_interval = ENV.fetch('SCHEDULER_POLLING_INTERVAL','5s') config.notify_key = ENV.fetch('NOTIFY_KEY', 'test-11111111-1111-1111-1111-111111111111-11111111-1111-1111-1111-111111111111') config.app_url = ENV.fetch('APP_URL', 'localhost:3000') end
33.471154
127
0.751221
4ad79ebd04de11d7ddaeaf035d778e43c0959375
500
require "capybara/poltergeist" POLTERGEIST_URL_BLACKLIST = %w{ tpc.googlesyndication.com www.googletagservices.com fonts.googleapis.com www.google-analytics.com api.mixpanel.com cdn.mxpnl.com tofu.example.com www.googletagmanager.com pagead2.googlesyndication.com } Capybara.register_driver :poltergeist do |app| Capybara::Poltergeist::Driver.new(app, url_blacklist: POLTERGEIST_URL_BLACKLIST, inspector: ENV["POLTERGEIST_DEBUG"]) end Capybara.javascript_driver = :poltergeist
25
119
0.802
e971509c95213be1fa5aae60dc5e452352e33660
2,413
module ICU module Collation def self.collate(locale, arr) Collator.new(locale).collate(arr) end def self.keywords enum_ptr = Lib.check_error { |error| Lib.ucol_getKeywords(error) } keywords = Lib.enum_ptr_to_array(enum_ptr) Lib.uenum_close enum_ptr hash = {} keywords.each do |keyword| enum_ptr = Lib.check_error { |error| Lib.ucol_getKeywordValues(keyword, error) } hash[keyword] = Lib.enum_ptr_to_array(enum_ptr) Lib.uenum_close(enum_ptr) end hash end def self.available_locales (0...Lib.ucol_countAvailable).map do |idx| Lib.ucol_getAvailable idx end end class Collator ULOC_VALID_LOCALE = 1 def initialize(locale) ptr = Lib.check_error { |error| Lib.ucol_open(locale, error) } @c = FFI::AutoPointer.new(ptr, Lib.method(:ucol_close)) end def locale Lib.check_error { |error| Lib.ucol_getLocale(@c, ULOC_VALID_LOCALE, error) } end def compare(a, b) Lib.ucol_strcoll( @c, UCharPointer.from_string(a), a.jlength, UCharPointer.from_string(b), b.jlength ) end def greater?(a, b) Lib.ucol_greater(@c, UCharPointer.from_string(a), a.jlength, UCharPointer.from_string(b), b.jlength) end def greater_or_equal?(a, b) Lib.ucol_greaterOrEqual(@c, UCharPointer.from_string(a), a.jlength, UCharPointer.from_string(b), b.jlength) end def equal?(*args) return super() if args.empty? if args.size != 2 raise ArgumentError, "wrong number of arguments (#{args.size} for 2)" end a, b = args Lib.ucol_equal(@c, UCharPointer.from_string(a), a.jlength, UCharPointer.from_string(b), b.jlength) end def collate(sortable) unless sortable.respond_to?(:sort) raise ArgumentError, "argument must respond to :sort with arity of 2" end sortable.sort { |a, b| compare a, b } end def rules @rules ||= begin length = FFI::MemoryPointer.new(:int) ptr = ICU::Lib.ucol_getRules(@c, length) ptr.read_array_of_uint16(length.read_int).pack("U*") end end end # Collator end # Collate end # ICU
26.516484
88
0.588893
1c64830c0ec2daf7f63e6169de9da292666f240a
3,757
############################################################################### # Copyright 2012 MarkLogic Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### require 'rbconfig' require 'rexml/text' def find_arg(args = []) args.each do |arg| ARGV.each do |a| if a == arg || a.match("^#{arg}=") index = ARGV.index(a) ARGV.slice!(index) return arg if a == arg if arg.match("^--") split = a.split '=' return a.split("=")[1] if split.length == 2 return arg end end end end nil end def load_prop_from_args(props) ARGV.each do |a| if a.match(/(^--)(ml\..*)(=)(.*)/) matches = a.match(/(^--)(ml\..*)(=)(.*)/).to_a ml_key = matches[2] ml_val = matches[4] if props.has_key?("#{ml_key}") props["#{ml_key}"] = ml_val else logger.warn "Property #{ml_key} does not exist. It will be skipped." end end end props end def pluralize(count, singular, plural = nil) count == 1 || count =~ /^1(\.0+)?$/ ? singular : plural end def is_windows? (RbConfig::CONFIG['host_os'] =~ /mswin|mingw/).nil? == false end def path_separator is_windows? ? ";" : ":" end def is_jar? __FILE__.match(/.*\.jar.*/) != nil end def copy_file(src, target) if is_jar? contents = read_file(src) File.open(target, "w") { |file| file.write(contents) } else FileUtils.cp(src, target) end end def read_file(filename) if is_jar? require 'java' stream = self.to_java.get_class.get_class_loader.get_resource_as_stream(filename) br = java.io.BufferedReader.new(java.io.InputStreamReader.new(stream)) contents = "" while (line = br.read_line()) contents = contents + line + "\n" end br.close() return contents else File.read(filename) end end def file_exists?(filename) if is_jar? require 'java' self.to_java.get_class.get_class_loader.get_resource_as_stream(filename) != nil else return File.exists?(filename) end end class String unless respond_to? :try def try(method) send method if respond_to? method end end def strip_heredoc indent = scan(/^[ \t]*(?=\S)/).min.try(:size) || 0 gsub(/^[ \t]{#{indent}}/, '') end def xquery_safe REXML::Text::normalize(self).gsub(/\{/, '{{').gsub(/\}/, '}}') end def xquery_unsafe REXML::Text::unnormalize(self).gsub(/\{\{/, '{').gsub(/\}\}/, '}') end end class Object def blank? respond_to?(:empty?) ? empty? : !self end def present? !blank? end def to_b present? && ['true', 'TRUE', 'yes', 'YES', 'y', 'Y', 't', 'T'].include?(self) end def optional_require(feature) begin require feature rescue LoadError end end end def parse_json(body) if (body.match('^\[\{"qid":')) items = [] JSON.parse(body).each do |item| items.push item['result'] end return items.join("\n") else return body end end def find_jar(jarname, jarpath = "../java/") matches = Dir.glob(ServerConfig.expand_path("#{jarpath}*#{jarname}*.jar")) raise "Missing #{jarname} jar." if matches.length == 0 matches[0] end
22.769697
85
0.591163
61e72fc485d3b586d97186e2071d0e4db374134d
23,767
# frozen_string_literal: true # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! # require "google/ads/google_ads/error" require "google/ads/google_ads/v6/services/ad_group_criterion_service_pb" module Google module Ads module GoogleAds module V6 module Services module AdGroupCriterionService ## # Client for the AdGroupCriterionService service. # # Service to manage ad group criteria. # class Client include Paths # @private attr_reader :ad_group_criterion_service_stub ## # Configure the AdGroupCriterionService Client class. # # See {::Google::Ads::GoogleAds::V6::Services::AdGroupCriterionService::Client::Configuration} # for a description of the configuration fields. # # ## Example # # To modify the configuration for all AdGroupCriterionService clients: # # ::Google::Ads::GoogleAds::V6::Services::AdGroupCriterionService::Client.configure do |config| # config.timeout = 10.0 # end # # @yield [config] Configure the Client client. # @yieldparam config [Client::Configuration] # # @return [Client::Configuration] # def self.configure @configure ||= begin default_config = Client::Configuration.new default_config.timeout = 3600.0 default_config.retry_policy = { initial_delay: 5.0, max_delay: 60.0, multiplier: 1.3, retry_codes: [14, 4] } default_config end yield @configure if block_given? @configure end ## # Configure the AdGroupCriterionService Client instance. # # The configuration is set to the derived mode, meaning that values can be changed, # but structural changes (adding new fields, etc.) are not allowed. Structural changes # should be made on {Client.configure}. # # See {::Google::Ads::GoogleAds::V6::Services::AdGroupCriterionService::Client::Configuration} # for a description of the configuration fields. # # @yield [config] Configure the Client client. # @yieldparam config [Client::Configuration] # # @return [Client::Configuration] # def configure yield @config if block_given? @config end ## # Create a new AdGroupCriterionService client object. # # ## Examples # # To create a new AdGroupCriterionService client with the default # configuration: # # client = ::Google::Ads::GoogleAds::V6::Services::AdGroupCriterionService::Client.new # # To create a new AdGroupCriterionService client with a custom # configuration: # # client = ::Google::Ads::GoogleAds::V6::Services::AdGroupCriterionService::Client.new do |config| # config.timeout = 10.0 # end # # @yield [config] Configure the AdGroupCriterionService client. # @yieldparam config [Client::Configuration] # def initialize # These require statements are intentionally placed here to initialize # the gRPC module only when it's required. # See https://github.com/googleapis/toolkit/issues/446 require "gapic/grpc" require "google/ads/google_ads/v6/services/ad_group_criterion_service_services_pb" # Create the configuration object @config = Configuration.new Client.configure # Yield the configuration if needed yield @config if block_given? # Create credentials credentials = @config.credentials credentials ||= Credentials.default scope: @config.scope if credentials.is_a?(String) || credentials.is_a?(Hash) credentials = Credentials.new credentials, scope: @config.scope end @quota_project_id = @config.quota_project @quota_project_id ||= credentials.quota_project_id if credentials.respond_to? :quota_project_id @ad_group_criterion_service_stub = ::Gapic::ServiceStub.new( ::Google::Ads::GoogleAds::V6::Services::AdGroupCriterionService::Stub, credentials: credentials, endpoint: @config.endpoint, channel_args: @config.channel_args, interceptors: @config.interceptors ) end # Service calls ## # Returns the requested criterion in full detail. # # @overload get_ad_group_criterion(request, options = nil) # Pass arguments to `get_ad_group_criterion` via a request object, either of type # {::Google::Ads::GoogleAds::V6::Services::GetAdGroupCriterionRequest} or an equivalent Hash. # # @param request [::Google::Ads::GoogleAds::V6::Services::GetAdGroupCriterionRequest, ::Hash] # A request object representing the call parameters. Required. To specify no # parameters, or to keep all the default parameter values, pass an empty Hash. # @param options [::Gapic::CallOptions, ::Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload get_ad_group_criterion(resource_name: nil) # Pass arguments to `get_ad_group_criterion` via keyword arguments. Note that at # least one keyword argument is required. To specify no parameters, or to keep all # the default parameter values, pass an empty Hash as a request object (see above). # # @param resource_name [::String] # Required. The resource name of the criterion to fetch. # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [::Google::Ads::GoogleAds::V6::Resources::AdGroupCriterion] # @yieldparam operation [::GRPC::ActiveCall::Operation] # # @return [::Google::Ads::GoogleAds::V6::Resources::AdGroupCriterion] # # @raise [Google::Ads::GoogleAds::Error] if the RPC is aborted. # def get_ad_group_criterion request, options = nil raise ::ArgumentError, "request must be provided" if request.nil? request = ::Gapic::Protobuf.coerce request, to: ::Google::Ads::GoogleAds::V6::Services::GetAdGroupCriterionRequest # Converts hash and nil to an options object options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.get_ad_group_criterion.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Ads::GoogleAds::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = { "resource_name" => request.resource_name } request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.get_ad_group_criterion.timeout, metadata: metadata, retry_policy: @config.rpcs.get_ad_group_criterion.retry_policy options.apply_defaults metadata: @config.metadata, retry_policy: @config.retry_policy @ad_group_criterion_service_stub.call_rpc :get_ad_group_criterion, request, options: options do |response, operation| yield response, operation if block_given? return response end # rescue GRPC::BadStatus => grpc_error # raise Google::Ads::GoogleAds::Error.new grpc_error.message end ## # Creates, updates, or removes criteria. Operation statuses are returned. # # @overload mutate_ad_group_criteria(request, options = nil) # Pass arguments to `mutate_ad_group_criteria` via a request object, either of type # {::Google::Ads::GoogleAds::V6::Services::MutateAdGroupCriteriaRequest} or an equivalent Hash. # # @param request [::Google::Ads::GoogleAds::V6::Services::MutateAdGroupCriteriaRequest, ::Hash] # A request object representing the call parameters. Required. To specify no # parameters, or to keep all the default parameter values, pass an empty Hash. # @param options [::Gapic::CallOptions, ::Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload mutate_ad_group_criteria(customer_id: nil, operations: nil, partial_failure: nil, validate_only: nil, response_content_type: nil) # Pass arguments to `mutate_ad_group_criteria` via keyword arguments. Note that at # least one keyword argument is required. To specify no parameters, or to keep all # the default parameter values, pass an empty Hash as a request object (see above). # # @param customer_id [::String] # Required. ID of the customer whose criteria are being modified. # @param operations [::Array<::Google::Ads::GoogleAds::V6::Services::AdGroupCriterionOperation, ::Hash>] # Required. The list of operations to perform on individual criteria. # @param partial_failure [::Boolean] # If true, successful operations will be carried out and invalid # operations will return errors. If false, all operations will be carried # out in one transaction if and only if they are all valid. # Default is false. # @param validate_only [::Boolean] # If true, the request is validated but not executed. Only errors are # returned, not results. # @param response_content_type [::Google::Ads::GoogleAds::V6::Enums::ResponseContentTypeEnum::ResponseContentType] # The response content type setting. Determines whether the mutable resource # or just the resource name should be returned post mutation. # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [::Google::Ads::GoogleAds::V6::Services::MutateAdGroupCriteriaResponse] # @yieldparam operation [::GRPC::ActiveCall::Operation] # # @return [::Google::Ads::GoogleAds::V6::Services::MutateAdGroupCriteriaResponse] # # @raise [Google::Ads::GoogleAds::Error] if the RPC is aborted. # def mutate_ad_group_criteria request, options = nil raise ::ArgumentError, "request must be provided" if request.nil? request = ::Gapic::Protobuf.coerce request, to: ::Google::Ads::GoogleAds::V6::Services::MutateAdGroupCriteriaRequest # Converts hash and nil to an options object options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.mutate_ad_group_criteria.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Ads::GoogleAds::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = { "customer_id" => request.customer_id } request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.mutate_ad_group_criteria.timeout, metadata: metadata, retry_policy: @config.rpcs.mutate_ad_group_criteria.retry_policy options.apply_defaults metadata: @config.metadata, retry_policy: @config.retry_policy @ad_group_criterion_service_stub.call_rpc :mutate_ad_group_criteria, request, options: options do |response, operation| yield response, operation if block_given? return response end # rescue GRPC::BadStatus => grpc_error # raise Google::Ads::GoogleAds::Error.new grpc_error.message end ## # Configuration class for the AdGroupCriterionService API. # # This class represents the configuration for AdGroupCriterionService, # providing control over timeouts, retry behavior, logging, transport # parameters, and other low-level controls. Certain parameters can also be # applied individually to specific RPCs. See # {::Google::Ads::GoogleAds::V6::Services::AdGroupCriterionService::Client::Configuration::Rpcs} # for a list of RPCs that can be configured independently. # # Configuration can be applied globally to all clients, or to a single client # on construction. # # # Examples # # To modify the global config, setting the timeout for get_ad_group_criterion # to 20 seconds, and all remaining timeouts to 10 seconds: # # ::Google::Ads::GoogleAds::V6::Services::AdGroupCriterionService::Client.configure do |config| # config.timeout = 10.0 # config.rpcs.get_ad_group_criterion.timeout = 20.0 # end # # To apply the above configuration only to a new client: # # client = ::Google::Ads::GoogleAds::V6::Services::AdGroupCriterionService::Client.new do |config| # config.timeout = 10.0 # config.rpcs.get_ad_group_criterion.timeout = 20.0 # end # # @!attribute [rw] endpoint # The hostname or hostname:port of the service endpoint. # Defaults to `"googleads.googleapis.com"`. # @return [::String] # @!attribute [rw] credentials # Credentials to send with calls. You may provide any of the following types: # * (`String`) The path to a service account key file in JSON format # * (`Hash`) A service account key as a Hash # * (`Google::Auth::Credentials`) A googleauth credentials object # (see the [googleauth docs](https://googleapis.dev/ruby/googleauth/latest/index.html)) # * (`Signet::OAuth2::Client`) A signet oauth2 client object # (see the [signet docs](https://googleapis.dev/ruby/signet/latest/Signet/OAuth2/Client.html)) # * (`GRPC::Core::Channel`) a gRPC channel with included credentials # * (`GRPC::Core::ChannelCredentials`) a gRPC credentails object # * (`nil`) indicating no credentials # @return [::Object] # @!attribute [rw] scope # The OAuth scopes # @return [::Array<::String>] # @!attribute [rw] lib_name # The library name as recorded in instrumentation and logging # @return [::String] # @!attribute [rw] lib_version # The library version as recorded in instrumentation and logging # @return [::String] # @!attribute [rw] channel_args # Extra parameters passed to the gRPC channel. Note: this is ignored if a # `GRPC::Core::Channel` object is provided as the credential. # @return [::Hash] # @!attribute [rw] interceptors # An array of interceptors that are run before calls are executed. # @return [::Array<::GRPC::ClientInterceptor>] # @!attribute [rw] timeout # The call timeout in seconds. # @return [::Numeric] # @!attribute [rw] metadata # Additional gRPC headers to be sent with the call. # @return [::Hash{::Symbol=>::String}] # @!attribute [rw] retry_policy # The retry policy. The value is a hash with the following keys: # * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds. # * `:max_delay` (*type:* `Numeric`) - The max delay in seconds. # * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier. # * `:retry_codes` (*type:* `Array<String>`) - The error codes that should # trigger a retry. # @return [::Hash] # @!attribute [rw] quota_project # A separate project against which to charge quota. # @return [::String] # class Configuration extend ::Gapic::Config config_attr :endpoint, "googleads.googleapis.com", ::String config_attr :credentials, nil do |value| allowed = [::String, ::Hash, ::Proc, ::Symbol, ::Google::Auth::Credentials, ::Signet::OAuth2::Client, nil] allowed += [::GRPC::Core::Channel, ::GRPC::Core::ChannelCredentials] if defined? ::GRPC allowed.any? { |klass| klass === value } end config_attr :scope, nil, ::String, ::Array, nil config_attr :lib_name, nil, ::String, nil config_attr :lib_version, nil, ::String, nil config_attr(:channel_args, { "grpc.service_config_disable_resolution"=>1 }, ::Hash, nil) config_attr :interceptors, nil, ::Array, nil config_attr :timeout, nil, ::Numeric, nil config_attr :metadata, nil, ::Hash, nil config_attr :retry_policy, nil, ::Hash, ::Proc, nil config_attr :quota_project, nil, ::String, nil # @private def initialize parent_config = nil @parent_config = parent_config unless parent_config.nil? yield self if block_given? end ## # Configurations for individual RPCs # @return [Rpcs] # def rpcs @rpcs ||= begin parent_rpcs = nil parent_rpcs = @parent_config.rpcs if defined?(@parent_config) && @parent_config&.respond_to?(:rpcs) Rpcs.new parent_rpcs end end ## # Configuration RPC class for the AdGroupCriterionService API. # # Includes fields providing the configuration for each RPC in this service. # Each configuration object is of type `Gapic::Config::Method` and includes # the following configuration fields: # # * `timeout` (*type:* `Numeric`) - The call timeout in milliseconds # * `metadata` (*type:* `Hash{Symbol=>String}`) - Additional gRPC headers # * `retry_policy (*type:* `Hash`) - The retry policy. The policy fields # include the following keys: # * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds. # * `:max_delay` (*type:* `Numeric`) - The max delay in seconds. # * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier. # * `:retry_codes` (*type:* `Array<String>`) - The error codes that should # trigger a retry. # class Rpcs ## # RPC-specific configuration for `get_ad_group_criterion` # @return [::Gapic::Config::Method] # attr_reader :get_ad_group_criterion ## # RPC-specific configuration for `mutate_ad_group_criteria` # @return [::Gapic::Config::Method] # attr_reader :mutate_ad_group_criteria # @private def initialize parent_rpcs = nil get_ad_group_criterion_config = parent_rpcs&.get_ad_group_criterion if parent_rpcs&.respond_to? :get_ad_group_criterion @get_ad_group_criterion = ::Gapic::Config::Method.new get_ad_group_criterion_config mutate_ad_group_criteria_config = parent_rpcs&.mutate_ad_group_criteria if parent_rpcs&.respond_to? :mutate_ad_group_criteria @mutate_ad_group_criteria = ::Gapic::Config::Method.new mutate_ad_group_criteria_config yield self if block_given? end end end end end end end end end end
51.779956
155
0.554635
38fd43a8a92cc743de015dffb2718e2076a93a18
2,090
# Copyright (c) 2020-2021 Andy Maleh # # 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 'glimmer' require 'glimmer/dsl/expression' require 'glimmer/dsl/parent_expression' module Glimmer module DSL module Tk class WidgetExpression < Expression include ParentExpression EXCLUDED_KEYWORDS = %w[root] def can_interpret?(parent, keyword, *args, &block) !EXCLUDED_KEYWORDS.include?(keyword) and Glimmer::Tk::WidgetProxy.widget_exists?(keyword) (parent.respond_to?(:tk) or args.first.respond_to?(:tk)) end def interpret(parent, keyword, *args, &block) if keyword == 'toplevel' && args.first.respond_to?(:tk) parent = args.first args[0] = args.first.tk end Glimmer::Tk::WidgetProxy.create(keyword, parent, args, &block) end def add_content(parent, keyword, *args, &block) super parent.post_add_content end end end end end require 'glimmer/tk/widget_proxy'
35.423729
72
0.695215
87211ec264ef1e6c85c8697490156fd47369231f
3,164
# # Author:: Serdar Sutay (<[email protected]>) # Copyright:: Copyright 2014-2016, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "spec_helper" require "functional/resource/base" describe Chef::Resource::Bash, :unix_only do let(:code) { "echo hello" } let(:resource) { resource = Chef::Resource::Bash.new("foo_resource", run_context) resource.code(code) resource } describe "when setting the command attribute" do let (:command) { "wizard racket" } # in Chef-12 the `command` attribute is largely useless, but does set the identity attribute # so that notifications need to target the value of the command. it will not run the `command` # and if it is given without a code block then it does nothing and always succeeds. describe "in Chef-12", chef: "< 13" do it "gets the commmand attribute from the name" do expect(resource.command).to eql("foo_resource") end it "sets the resource identity to the command name" do resource.command command expect(resource.identity).to eql(command) end it "warns when the code is not present and a useless `command` is present" do expect(Chef::Log).to receive(:warn).with(/coding error/) expect(Chef::Log).to receive(:warn).with(/deprecated/) resource.code nil resource.command command expect { resource.run_action(:run) }.not_to raise_error end describe "when the code is not present" do let(:code) { nil } it "warns" do expect(Chef::Log).to receive(:warn) expect { resource.run_action(:run) }.not_to raise_error end end end # in Chef-13 the `command` attribute needs to be for internal use only describe "in Chef-13", chef: ">= 13" do it "should raise an exception when trying to set the command" do expect { resource.command command }.to raise_error # FIXME: add a real error in Chef-13 end it "should initialize the command to nil" do expect(resource.command).to be_nil end describe "when the code is not present" do let(:code) { nil } it "raises an exception" do expect { resource.run_action(:run) }.to raise_error # FIXME: add a real error in Chef-13 expect { resource.run_action(:run) }.not_to raise_error end end end end it "times out when a timeout is set on the resource" do resource.code "sleep 600" resource.timeout 0.1 expect { resource.run_action(:run) }.to raise_error(Mixlib::ShellOut::CommandTimeout) end end
35.550562
99
0.675411
6a256c9254a798db6c4bb2fd1e9d851cd8cedb9b
494
require_relative '../../../../../test_helper' module Deliverhq module Request class MessageListTest < Minitest::Test def setup @message_list_response = {'records' => [{ 'id' => 1234, 'body' => 'foo' }]} end def test_list Deliverhq::Request::Base.stub :http_get, @message_list_response, ["messages", {page: 1}] do assert_equal 1, Request::Message.list(1).count end end end end end
21.478261
99
0.548583
26692934456a8e9e628e3cd0043f528c19a3f488
14,671
# frozen_string_literal: true module SortingHelper def sort_options_hash { sort_value_created_date => sort_title_created_date, sort_value_downvotes => sort_title_downvotes, sort_value_due_date => sort_title_due_date, sort_value_due_date_later => sort_title_due_date_later, sort_value_due_date_soon => sort_title_due_date_soon, sort_value_label_priority => sort_title_label_priority, sort_value_largest_group => sort_title_largest_group, sort_value_largest_repo => sort_title_largest_repo, sort_value_milestone => sort_title_milestone, sort_value_milestone_later => sort_title_milestone_later, sort_value_milestone_soon => sort_title_milestone_soon, sort_value_name => sort_title_name, sort_value_name_desc => sort_title_name_desc, sort_value_oldest_created => sort_title_oldest_created, sort_value_oldest_signin => sort_title_oldest_signin, sort_value_oldest_updated => sort_title_oldest_updated, sort_value_recently_created => sort_title_recently_created, sort_value_recently_signin => sort_title_recently_signin, sort_value_recently_updated => sort_title_recently_updated, sort_value_popularity => sort_title_popularity, sort_value_priority => sort_title_priority, sort_value_upvotes => sort_title_upvotes, sort_value_contacted_date => sort_title_contacted_date, sort_value_relative_position => sort_title_relative_position } end def projects_sort_options_hash Feature.enabled?(:project_list_filter_bar) && !current_controller?('admin/projects') ? projects_sort_common_options_hash : old_projects_sort_options_hash end # TODO: Simplify these sorting options # https://gitlab.com/gitlab-org/gitlab-ce/issues/60798 # https://gitlab.com/gitlab-org/gitlab-ee/merge_requests/11209#note_162234858 def old_projects_sort_options_hash options = { sort_value_latest_activity => sort_title_latest_activity, sort_value_name => sort_title_name, sort_value_oldest_activity => sort_title_oldest_activity, sort_value_oldest_created => sort_title_oldest_created, sort_value_recently_created => sort_title_recently_created, sort_value_stars_desc => sort_title_most_stars } if current_controller?('admin/projects') options[sort_value_largest_repo] = sort_title_largest_repo end options end def projects_sort_common_options_hash { sort_value_latest_activity => sort_title_latest_activity, sort_value_recently_created => sort_title_created_date, sort_value_name => sort_title_name, sort_value_stars_desc => sort_title_stars } end def projects_sort_option_titles { sort_value_latest_activity => sort_title_latest_activity, sort_value_recently_created => sort_title_created_date, sort_value_name => sort_title_name, sort_value_stars_desc => sort_title_stars, sort_value_oldest_activity => sort_title_latest_activity, sort_value_oldest_created => sort_title_created_date, sort_value_name_desc => sort_title_name, sort_value_stars_asc => sort_title_stars } end def projects_reverse_sort_options_hash { sort_value_latest_activity => sort_value_oldest_activity, sort_value_recently_created => sort_value_oldest_created, sort_value_name => sort_value_name_desc, sort_value_stars_desc => sort_value_stars_asc, sort_value_oldest_activity => sort_value_latest_activity, sort_value_oldest_created => sort_value_recently_created, sort_value_name_desc => sort_value_name, sort_value_stars_asc => sort_value_stars_desc } end def groups_sort_options_hash { sort_value_name => sort_title_name, sort_value_name_desc => sort_title_name_desc, sort_value_recently_created => sort_title_recently_created, sort_value_oldest_created => sort_title_oldest_created, sort_value_recently_updated => sort_title_recently_updated, sort_value_oldest_updated => sort_title_oldest_updated } end def subgroups_sort_options_hash groups_sort_options_hash.merge( sort_value_stars_desc => sort_title_most_stars ) end def admin_groups_sort_options_hash groups_sort_options_hash.merge( sort_value_largest_group => sort_title_largest_group ) end def member_sort_options_hash { sort_value_access_level_asc => sort_title_access_level_asc, sort_value_access_level_desc => sort_title_access_level_desc, sort_value_last_joined => sort_title_last_joined, sort_value_name => sort_title_name_asc, sort_value_name_desc => sort_title_name_desc, sort_value_oldest_joined => sort_title_oldest_joined, sort_value_oldest_signin => sort_title_oldest_signin, sort_value_recently_signin => sort_title_recently_signin } end def milestone_sort_options_hash { sort_value_name => sort_title_name_asc, sort_value_name_desc => sort_title_name_desc, sort_value_due_date_later => sort_title_due_date_later, sort_value_due_date_soon => sort_title_due_date_soon, sort_value_start_date_later => sort_title_start_date_later, sort_value_start_date_soon => sort_title_start_date_soon } end def branches_sort_options_hash { sort_value_name => sort_title_name, sort_value_oldest_updated => sort_title_oldest_updated, sort_value_recently_updated => sort_title_recently_updated } end def tags_sort_options_hash { sort_value_name => sort_title_name, sort_value_oldest_updated => sort_title_oldest_updated, sort_value_recently_updated => sort_title_recently_updated } end def label_sort_options_hash { sort_value_name => sort_title_name, sort_value_name_desc => sort_title_name_desc, sort_value_recently_created => sort_title_recently_created, sort_value_oldest_created => sort_title_oldest_created, sort_value_recently_updated => sort_title_recently_updated, sort_value_oldest_updated => sort_title_oldest_updated } end def users_sort_options_hash { sort_value_name => sort_title_name, sort_value_recently_signin => sort_title_recently_signin, sort_value_oldest_signin => sort_title_oldest_signin, sort_value_recently_created => sort_title_recently_created, sort_value_oldest_created => sort_title_oldest_created, sort_value_recently_updated => sort_title_recently_updated, sort_value_oldest_updated => sort_title_oldest_updated, sort_value_recently_last_activity => sort_title_recently_last_activity, sort_value_oldest_last_activity => sort_title_oldest_last_activity } end def sortable_item(item, path, sorted_by) link_to item, path, class: sorted_by == item ? 'is-active' : '' end def issuable_sort_option_overrides { sort_value_oldest_created => sort_value_created_date, sort_value_oldest_updated => sort_value_recently_updated, sort_value_milestone_later => sort_value_milestone, sort_value_due_date_later => sort_value_due_date, sort_value_least_popular => sort_value_popularity } end def issuable_reverse_sort_order_hash { sort_value_created_date => sort_value_oldest_created, sort_value_recently_created => sort_value_oldest_created, sort_value_recently_updated => sort_value_oldest_updated, sort_value_milestone => sort_value_milestone_later, sort_value_due_date => sort_value_due_date_later, sort_value_due_date_soon => sort_value_due_date_later, sort_value_popularity => sort_value_least_popular, sort_value_most_popular => sort_value_least_popular }.merge(issuable_sort_option_overrides) end def issuable_sort_option_title(sort_value) sort_value = issuable_sort_option_overrides[sort_value] || sort_value sort_options_hash[sort_value] end def issuable_sort_icon_suffix(sort_value) case sort_value when sort_value_milestone, sort_value_due_date, /_asc\z/ 'lowest' else 'highest' end end # TODO: dedupicate issuable and project sort direction # https://gitlab.com/gitlab-org/gitlab-ce/issues/60798 def issuable_sort_direction_button(sort_value) link_class = 'btn btn-default has-tooltip reverse-sort-btn qa-reverse-sort' reverse_sort = issuable_reverse_sort_order_hash[sort_value] if reverse_sort reverse_url = page_filter_path(sort: reverse_sort) else reverse_url = '#' link_class += ' disabled' end link_to(reverse_url, type: 'button', class: link_class, title: s_('SortOptions|Sort direction')) do sprite_icon("sort-#{issuable_sort_icon_suffix(sort_value)}", size: 16) end end def project_sort_direction_button(sort_value) link_class = 'btn btn-default has-tooltip reverse-sort-btn qa-reverse-sort' reverse_sort = projects_reverse_sort_options_hash[sort_value] if reverse_sort reverse_url = filter_projects_path(sort: reverse_sort) else reverse_url = '#' link_class += ' disabled' end link_to(reverse_url, type: 'button', class: link_class, title: s_('SortOptions|Sort direction')) do sprite_icon("sort-#{issuable_sort_icon_suffix(sort_value)}", size: 16) end end # Titles. def sort_title_access_level_asc s_('SortOptions|Access level, ascending') end def sort_title_access_level_desc s_('SortOptions|Access level, descending') end def sort_title_created_date s_('SortOptions|Created date') end def sort_title_downvotes s_('SortOptions|Least popular') end def sort_title_due_date s_('SortOptions|Due date') end def sort_title_due_date_later s_('SortOptions|Due later') end def sort_title_due_date_soon s_('SortOptions|Due soon') end def sort_title_label_priority s_('SortOptions|Label priority') end def sort_title_largest_group s_('SortOptions|Largest group') end def sort_title_largest_repo s_('SortOptions|Largest repository') end def sort_title_last_joined s_('SortOptions|Last joined') end def sort_title_latest_activity s_('SortOptions|Last updated') end def sort_title_milestone s_('SortOptions|Milestone due date') end def sort_title_milestone_later s_('SortOptions|Milestone due later') end def sort_title_milestone_soon s_('SortOptions|Milestone due soon') end def sort_title_name s_('SortOptions|Name') end def sort_title_name_asc s_('SortOptions|Name, ascending') end def sort_title_name_desc s_('SortOptions|Name, descending') end def sort_title_oldest_activity s_('SortOptions|Oldest updated') end def sort_title_oldest_created s_('SortOptions|Oldest created') end def sort_title_oldest_joined s_('SortOptions|Oldest joined') end def sort_title_oldest_signin s_('SortOptions|Oldest sign in') end def sort_title_oldest_updated s_('SortOptions|Oldest updated') end def sort_title_popularity s_('SortOptions|Popularity') end def sort_title_priority s_('SortOptions|Priority') end def sort_title_recently_created s_('SortOptions|Last created') end def sort_title_recently_signin s_('SortOptions|Recent sign in') end def sort_title_recently_updated s_('SortOptions|Last updated') end def sort_title_start_date_later s_('SortOptions|Start later') end def sort_title_start_date_soon s_('SortOptions|Start soon') end def sort_title_upvotes s_('SortOptions|Most popular') end def sort_title_contacted_date s_('SortOptions|Last Contact') end def sort_title_most_stars s_('SortOptions|Most stars') end def sort_title_stars s_('SortOptions|Stars') end def sort_title_oldest_last_activity s_('SortOptions|Oldest last activity') end def sort_title_recently_last_activity s_('SortOptions|Recent last activity') end def sort_title_relative_position s_('SortOptions|Manual') end # Values. def sort_value_access_level_asc 'access_level_asc' end def sort_value_access_level_desc 'access_level_desc' end def sort_value_created_date 'created_date' end def sort_value_downvotes 'downvotes_desc' end def sort_value_due_date 'due_date' end def sort_value_due_date_later 'due_date_desc' end def sort_value_due_date_soon 'due_date_asc' end def sort_value_label_priority 'label_priority' end def sort_value_largest_group 'storage_size_desc' end def sort_value_largest_repo 'storage_size_desc' end def sort_value_last_joined 'last_joined' end def sort_value_latest_activity 'latest_activity_desc' end def sort_value_milestone 'milestone' end def sort_value_milestone_later 'milestone_due_desc' end def sort_value_milestone_soon 'milestone_due_asc' end def sort_value_name 'name_asc' end def sort_value_name_desc 'name_desc' end def sort_value_oldest_activity 'latest_activity_asc' end def sort_value_oldest_created 'created_asc' end def sort_value_oldest_signin 'oldest_sign_in' end def sort_value_oldest_joined 'oldest_joined' end def sort_value_oldest_updated 'updated_asc' end def sort_value_popularity 'popularity' end def sort_value_most_popular 'popularity_desc' end def sort_value_least_popular 'popularity_asc' end def sort_value_priority 'priority' end def sort_value_recently_created 'created_desc' end def sort_value_recently_signin 'recent_sign_in' end def sort_value_recently_updated 'updated_desc' end def sort_value_start_date_later 'start_date_desc' end def sort_value_start_date_soon 'start_date_asc' end def sort_value_upvotes 'upvotes_desc' end def sort_value_contacted_date 'contacted_asc' end def sort_value_stars_desc 'stars_desc' end def sort_value_stars_asc 'stars_asc' end def sort_value_oldest_last_activity 'last_activity_on_asc' end def sort_value_recently_last_activity 'last_activity_on_desc' end def sort_value_relative_position 'relative_position' end end
26.292115
157
0.740645
03ea9f60ddca247e6a50ef555640555b4ff665d2
512
class JobMessenger < ActiveRecord::Base def message_for_user case status when 'queued' 'Job is currently queued' when 'running' 'Job is currently running' when 'failed' "Job Has Failed: #{message}" when 'succeeded' 'Job has processed successfully' end end def failed? status == 'failed' end def succeeded? status == 'succeeded' end def queued? status == 'queued' end def running? status == 'running' end end
16.516129
40
0.597656
1c0ae9487c4623bad7cb0a72eb270c5ca914a8e8
816
module GovukTechDocs class Redirects LEADING_SLASH = %r[\A\/].freeze def initialize(context) @context = context end def redirects all_redirects = redirects_from_config + redirects_from_frontmatter all_redirects.map do |from, to| # Middleman needs paths without leading slashes [from.sub(LEADING_SLASH, ""), to: to.sub(LEADING_SLASH, "")] end end private attr_reader :context def redirects_from_config context.config[:tech_docs][:redirects].to_a end def redirects_from_frontmatter reds = [] context.sitemap.resources.each do |page| next unless page.data.old_paths page.data.old_paths.each do |old_path| reds << [old_path, page.path] end end reds end end end
20.4
72
0.640931
39f1f50cac72f834500a8ae01f61326968f28e3d
973
# frozen_string_literal: true require 'tzispa/utils/tz_string' module Tzispa module Utils class Indenter using Tzispa::Utils::TzString DEFAULT_INDENT_CHAR = ' ' DEFAULT_INDENT_SIZE = 2 attr_reader :sbuff, :indent_char, :instr def initialize(indent_size = nil, indent_char = nil) @indent_size = indent_size || DEFAULT_INDENT_SIZE @indent_current = 0 @indent_char = indent_char || DEFAULT_INDENT_CHAR @instr = String.new end def <<(item) ss = item.to_s.indentize(@indent_current, @indent_char) @instr.concat ss self end def to_s @instr end def indent @indent_current += @indent_size self end def unindent if (@indent_current - @indent_size).positive? @indent_current -= @indent_size else @indent_current = 0 end self end end end end
18.358491
63
0.589928
333416577478203a59880bd2be18c754d50e4605
42,331
# frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end it "should allow the share of visitors see an alternative to be specified" do ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 }) expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should allow alternative weighting interface as a single hash" do ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"]) expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2]) end it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment")).to eq "one" expect(ab_test("my_experiment") do |_, meta| meta end).to eq("Meta1") end end context "is not defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: nil } } end it "should be passed to helper block" do expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq({}) end it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment") do |_, meta| meta end).to eq({}) end end end describe "ab_finished" do context "for an experiment that the user participates in" do before(:each) do @experiment_name = "link_color" @alternatives = ["blue", "red"] @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) @alternative_name = ab_test(@experiment_name, *@alternatives) @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count end it "should increment the counter for the completed alternative" do ab_finished(@experiment_name) new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should set experiment's finished key if reset is false" do ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should not increment the counter if reset is false and the experiment has been already finished" do 2.times { ab_finished(@experiment_name, { reset: false }) } new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" a = ab_test("button_size", "small", "big") expect(a).to eq("small") expect { ab_finished("button_size") }.not_to change { Split::Alternative.new(a, "button_size").completed_count } end it "should clear out the user's participation from their session" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should not clear out the users session if reset is false" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should reset the users session when experiment is not versioned" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should reset the users session when experiment is versioned" do @experiment.increment_version @alternative_name = ab_test(@experiment_name, *@alternatives) expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end context "when on_trial_complete is set" do before { Split.configuration.on_trial_complete = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_finished(@experiment_name) end it "should not call the method without alternative" do ab_user[@experiment.key] = nil expect(self).not_to receive(:some_method) ab_finished(@experiment_name) end end end context "for an experiment that the user is excluded from" do before do alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end
36.970306
145
0.63783
1d069282affe603c277c2d0c93dbbd77488c266e
350
# frozen_string_literal: true class CreateReleases < ActiveRecord::Migration[6.0] def change create_table :releases do |t| t.string :name t.date :start_date t.date :finish_date t.text :description t.boolean :active t.references :project, null: false, foreign_key: true t.timestamps end end end
20.588235
59
0.665714
f8c55a284936d6ab26a9b6cc82c7b7604e489bf7
8,335
# -*- coding: binary -*- require 'uri' require 'rex/proto/http' module Rex module Proto module Http ### # # HTTP request class. # ### class Request < Packet PostRequests = ['POST', 'SEARCH'] ## # # Some individual request types. # ## # # HTTP GET request class wrapper. # class Get < Request def initialize(uri = '/', proto = DefaultProtocol) super('GET', uri, proto) end end # # HTTP POST request class wrapper. # class Post < Request def initialize(uri = '/', proto = DefaultProtocol) super('POST', uri, proto) end end # # HTTP PUT request class wrapper. # class Put < Request def initialize(uri = '/', proto = DefaultProtocol) super('PUT', uri, proto) end end # # Initializes an instance of an HTTP request with the supplied method, URI, # and protocol. # def initialize(method = 'GET', uri = '/', proto = DefaultProtocol) super() self.method = method self.raw_uri = uri self.uri_parts = {} self.proto = proto || DefaultProtocol self.chunk_min_size = 1 self.chunk_max_size = 10 self.uri_encode_mode = 'hex-normal' if self.method == 'GET' || self.method == 'CONNECT' self.auto_cl = false end update_uri_parts end # # Updates the command parts for this specific packet type. # def update_cmd_parts(str) if (md = str.match(/^(.+?)\s+(.+?)\s+HTTP\/(.+?)\r?\n?$/i)) self.method = md[1] self.raw_uri = CGI.unescape(md[2]) self.proto = md[3] update_uri_parts else raise RuntimeError, "Invalid request command string", caller end end # # Split the URI into the resource being requested and its query string. # def update_uri_parts # If it has a query string, get the parts. if ((self.raw_uri) and (md = self.raw_uri.match(/(.+?)\?(.*)$/))) self.uri_parts['QueryString'] = parse_cgi_qstring(md[2]) self.uri_parts['Resource'] = md[1] # Otherwise, just assume that the URI is equal to the resource being # requested. else self.uri_parts['QueryString'] = {} self.uri_parts['Resource'] = self.raw_uri end self.normalize!(resource) # Set the relative resource to the actual resource. self.relative_resource = resource end # normalize out multiple slashes, directory traversal, and self referrential directories def normalize!(str) i = 0 while (str.gsub!(/(\/\.\/|\/\w+\/\.\.\/|\/\/)/,'/')); i += 1; end i end # Puts a URI back together based on the URI parts def uri str = self.uri_parts['Resource'].dup || '/' # /././././ if self.junk_self_referring_directories str.gsub!(/\//) { '/.' * (rand(3) + 1) + '/' } end # /%3faaa=bbbbb # which could possibly decode to "/?aaa=bbbbb", which if the IDS normalizes first, then splits the URI on ?, then it can be bypassed if self.junk_param_start str.sub!(/\//, '/%3f' + Rex::Text.rand_text_alpha(rand(5) + 1) + '=' + Rex::Text.rand_text_alpha(rand(10) + 1) + '/../') end # /RAND/../RAND../ if self.junk_directories str.gsub!(/\//) { dirs = '' (rand(5)+5).times { dirs << '/' + Rex::Text.rand_text_alpha(rand(5) + 1) + '/..' } dirs + '/' } end # //// # # NOTE: this must be done after all other odd directory junk, since they would cancel this out, except junk_end_of_uri, since that a specific slash in a specific place if self.junk_slashes str.gsub!(/\//) { '/' * (rand(3) + 2) } str.sub!(/^[\/]+/, '/') # only one beginning slash! end # /%20HTTP/1.0%0d%0a/../../ # which decodes to "/ HTTP/1.0\r\n" if self.junk_end_of_uri str.sub!(/^\//, '/%20HTTP/1.0%0d%0a/../../') end Rex::Text.uri_encode(str, self.uri_encode_mode) if !PostRequests.include?(self.method) if param_string.size > 0 str << '?' + param_string end end str end def param_string params=[] self.uri_parts['QueryString'].each_pair { |param, value| # inject a random number of params in between each param if self.junk_params rand(10)+5.times { params.push(Rex::Text.rand_text_alpha(rand(16) + 5) + '=' + Rex::Text.rand_text_alpha(rand(10) + 1)) } end if value.kind_of?(Array) value.each { |subvalue| params.push(Rex::Text.uri_encode(param, self.uri_encode_mode) + '=' + Rex::Text.uri_encode(subvalue, self.uri_encode_mode)) } else if !value.nil? params.push(Rex::Text.uri_encode(param, self.uri_encode_mode) + '=' + Rex::Text.uri_encode(value, self.uri_encode_mode)) else params.push(Rex::Text.uri_encode(param, self.uri_encode_mode)) end end } # inject some junk params at the end of the param list, just to be sure :P if self.junk_params rand(10)+5.times { params.push(Rex::Text.rand_text_alpha(rand(32) + 5) + '=' + Rex::Text.rand_text_alpha(rand(64) + 5)) } end params.join('&') end # Updates the underlying URI structure def uri=(str) self.raw_uri = str update_uri_parts end # Returns a request packet def to_s str = '' if self.junk_pipeline host = '' if self.headers['Host'] host = "Host: #{self.headers['Host']}\r\n" end str << "GET / HTTP/1.1\r\n#{host}Connection: Keep-Alive\r\n\r\n" * self.junk_pipeline self.headers['Connection'] = 'Closed' end str + super end def body str = super || '' if str.length > 0 return str end if PostRequests.include?(self.method) return param_string end '' end # # Returns the command string derived from the three values. # def cmd_string proto_str = (self.proto =~ /^\d/) ? "HTTP/#{self.proto}" : self.proto "#{self.method} #{self.uri} #{proto_str}\r\n" end # # Returns the resource that is being requested. # def resource self.uri_parts['Resource'] end # # Changes the resource URI. This is used when making a request relative to # a given mount point. # def resource=(rsrc) self.uri_parts['Resource'] = rsrc end # # If there were CGI parameters in the URI, this will hold a hash of each # variable to value. If there is more than one value for a given variable, # an array of each value is returned. # def qstring self.uri_parts['QueryString'] end # # Returns a hash of variables that contain information about the request, # such as the remote host information. # # TODO # def meta_vars end # # The method being used for the request (e.g. GET). # attr_accessor :method # # The raw URI being requested, before any mucking gets to it # attr_accessor :raw_uri # # The split up parts of the URI. # attr_accessor :uri_parts # # The protocol to be sent with the request. # attr_accessor :proto # # The resource path relative to the root of a server mount point. # attr_accessor :relative_resource # add junk directories attr_accessor :junk_directories # add junk slashes attr_accessor :junk_slashes # add junk self referring directories (aka /././././) attr_accessor :junk_self_referring_directories # add junk params attr_accessor :junk_params # add junk pipeline requests attr_accessor :junk_pipeline # add junk start of params attr_accessor :junk_param_start # add junk end of URI attr_accessor :junk_end_of_uri # encoding uri attr_accessor :uri_encode_mode # # Parses a CGI query string into the var/val combinations. # def parse_cgi_qstring(str) qstring = {} # Delimit on each variable str.split(/[;&]/).each { |vv| var = vv val = '' if (md = vv.match(/(.+?)=(.*)/)) var = md[1] val = md[2] end # Add the item to the hash with logic to convert values to an array # if so desired. if (qstring.include?(var)) if (qstring[var].kind_of?(Array)) qstring[var] << val else curr = self.qstring[var] qstring[var] = [ curr, val ] end else qstring[var] = val end } return qstring end end end end end
23.21727
171
0.603119
e99abde007b4c8297200542d252799ff7af664c3
6,618
Rails.application.routes.draw do # Disable PUT for now since rails sends these :update and they aren't really the same thing. def put(*_args); end routing_helper = Insights::API::Common::Routing.new(self) prefix = "api" if ENV["PATH_PREFIX"].present? && ENV["APP_NAME"].present? prefix = File.join(ENV["PATH_PREFIX"], ENV["APP_NAME"]).gsub(/^\/+|\/+$/, "") end get "/health", :to => "status#health" scope :as => :api, :module => "api", :path => prefix do routing_helper.redirect_major_version("v3.1", prefix) routing_helper.redirect_major_version("v2.0", prefix) routing_helper.redirect_major_version("v1.0", prefix) namespace :v3x1, :path => "v3.1" do get "/openapi.json", :to => "root#openapi" post "/graphql", :to => "graphql#query" post "/bulk_create", :to => "bulk_create#create" resources :application_types, :only => [:index, :show] do resources :sources, :only => [:index] get "app_meta_data", :to => "app_meta_data#index" end resources :applications, :only => [:create, :destroy, :index, :show, :update] do resources :authentications, :only => [:index] post "pause", :to => "applications#pause" post "unpause", :to => "applications#unpause" end resources :application_authentications, :only => [:create, :destroy, :index, :show, :update] resources :authentications, :only => [:create, :destroy, :index, :show, :update] resources :endpoints, :only => [:create, :destroy, :index, :show, :update] do resources :authentications, :only => [:index] end resources :source_types, :only => [:index, :show] do resources :sources, :only => [:index] end resources :sources, :only => [:create, :destroy, :index, :show, :update] do post "check_availability", :to => "sources#check_availability", :action => "check_availability" resources :application_types, :only => [:index] resources :applications, :only => [:index] resources :authentications, :only => [:index] resources :endpoints, :only => [:index] post "pause", :to => "sources#pause" post "unpause", :to => "sources#unpause" end resources :app_meta_data, :only => [:index, :show,] end namespace :v3x0, :path => "v3.0" do get "/openapi.json", :to => "root#openapi" post "/graphql", :to => "graphql#query" resources :application_types, :only => [:index, :show] do resources :sources, :only => [:index] end resources :applications, :only => [:create, :destroy, :index, :show, :update] do resources :authentications, :only => [:index] end resources :application_authentications, :only => [:create, :destroy, :index, :show, :update] resources :authentications, :only => [:create, :destroy, :index, :show, :update] resources :endpoints, :only => [:create, :destroy, :index, :show, :update] do resources :authentications, :only => [:index] end resources :source_types, :only => [:index, :show] do resources :sources, :only => [:index] end resources :sources, :only => [:create, :destroy, :index, :show, :update] do post "check_availability", :to => "sources#check_availability", :action => "check_availability" resources :application_types, :only => [:index] resources :applications, :only => [:index] resources :authentications, :only => [:index] resources :endpoints, :only => [:index] end end namespace :v2x0, :path => "v2.0" do get "/openapi.json", :to => "root#openapi" post "/graphql", :to => "graphql#query" resources :application_types, :only => [:index, :show] do resources :sources, :only => [:index] end resources :applications, :only => [:create, :destroy, :index, :show, :update] do resources :authentications, :only => [:index] end resources :application_authentications, :only => [:create, :destroy, :index, :show, :update] resources :authentications, :only => [:create, :destroy, :index, :show, :update] resources :endpoints, :only => [:create, :destroy, :index, :show, :update] do resources :authentications, :only => [:index] end resources :source_types, :only => [:index, :show] do resources :sources, :only => [:index] end resources :sources, :only => [:create, :destroy, :index, :show, :update] do post "check_availability", :to => "sources#check_availability", :action => "check_availability" resources :application_types, :only => [:index] resources :applications, :only => [:index] resources :authentications, :only => [:index] resources :endpoints, :only => [:index] end end namespace :v1x0, :path => "v1.0" do get "/openapi.json", :to => "root#openapi" post "/graphql", :to => "graphql#query" resources :application_types, :only => [:index, :show] do resources :sources, :only => [:index] end resources :applications, :only => [:create, :destroy, :index, :show, :update] resources :authentications, :only => [:create, :destroy, :index, :show, :update] resources :endpoints, :only => [:create, :destroy, :index, :show, :update] do resources :authentications, :only => [:index] end resources :source_types, :only => [:index, :show] do resources :sources, :only => [:index] end resources :sources, :only => [:create, :destroy, :index, :show, :update] do post "check_availability", :to => "sources#check_availability", :action => "check_availability" resources :application_types, :only => [:index] resources :applications, :only => [:index] resources :authentications, :only => [:index] resources :endpoints, :only => [:index] end end end scope :as => :internal, :module => "internal", :path => "internal" do routing_helper.redirect_major_version("v1.0", "internal", :via => [:get]) namespace :v1x0, :path => "v1.0" do resources :authentications, :only => [:show] resources :tenants, :only => [:index, :show] end end end
46.93617
103
0.574192
b9df021a9ef2f63d83ec11e62e8db88fc79312d3
1,166
class Autobench < Formula desc "Automatic webserver benchmark tool" homepage "http://www.xenoclast.org/autobench/" url "http://www.xenoclast.org/autobench/downloads/autobench-2.1.2.tar.gz" sha256 "d8b4d30aaaf652df37dff18ee819d8f42751bc40272d288ee2a5d847eaf0423b" bottle do cellar :any_skip_relocation sha256 "daecaaf9c3a733c7667c5414371ba948896b0c0eb47dfd1b1ce876921c829390" => :sierra sha256 "37bb6f40825953f9ba176522bc64d74a6375304d7963331aee937417e339964f" => :el_capitan sha256 "9884556bd5f7ab7c29a0aa199328cbe609e04437b1ddce4703214ba65f15d40a" => :yosemite sha256 "d31d3625f06d036af97b6cc80d62856b9d3eecadb4ed9fe7a0cb9b96f8d9f9a0" => :mavericks sha256 "0246ec483143e1f752a6b7a22ddc11a5c213e795bb55c5296646bcedc05d3426" => :mountain_lion end depends_on "httperf" def install system "make", "PREFIX=#{prefix}", "MANDIR=#{man1}", "CC=#{ENV.cc}", "CFLAGS=#{ENV.cflags}", "install" end test do system "#{bin}/crfile", "-f", "#{testpath}/test", "-s", "42" assert File.exist? "test" assert_equal 42, File.size("test") end end
36.4375
95
0.711835
8750d72f2ab67368d9e9461a9bedb07a5b32647c
1,078
require 'spec_helper' describe 'odoo' do let(:pre_condition) do [ 'define ini_setting($ensure = nil, $path, $section, $key_val_separator = nil, $setting, $value = nil) {}' ] end let!(:stdlib_stubs) do MockFunction.new('create_ini_settings', type: :statement) do |_f| end end context 'with defaults for all parameters (debian)' do let :facts do { osfamily: 'Debian' } end it do should compile should have_resource_count(2) should contain_class('odoo') should contain_package('odoo') should contain_service('odoo') end end context 'with defaults for all parameters (red hat)' do let :facts do { osfamily: 'RedHat' } end it do should compile should have_resource_count(3) should contain_class('odoo') should contain_package('odoo') should contain_service('odoo') should contain_exec('/usr/bin/systemctl daemon-reload') end end end
20.730769
69
0.585343
181d0f0936f81614224afee2469aaf783d96df62
1,451
# frozen_string_literal: true # WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE require 'aws-sdk-core' require 'aws-sigv4' require_relative 'aws-sdk-kinesisvideo/types' require_relative 'aws-sdk-kinesisvideo/client_api' require_relative 'aws-sdk-kinesisvideo/client' require_relative 'aws-sdk-kinesisvideo/errors' require_relative 'aws-sdk-kinesisvideo/resource' require_relative 'aws-sdk-kinesisvideo/customizations' # This module provides support for Amazon Kinesis Video Streams. This module is available in the # `aws-sdk-kinesisvideo` gem. # # # Client # # The {Client} class provides one method for each API operation. Operation # methods each accept a hash of request parameters and return a response # structure. # # kinesis_video = Aws::KinesisVideo::Client.new # resp = kinesis_video.create_signaling_channel(params) # # See {Client} for more information. # # # Errors # # Errors returned from Amazon Kinesis Video Streams are defined in the # {Errors} module and all extend {Errors::ServiceError}. # # begin # # do stuff # rescue Aws::KinesisVideo::Errors::ServiceError # # rescues all Amazon Kinesis Video Streams API errors # end # # See {Errors} for more information. # # @!group service module Aws::KinesisVideo GEM_VERSION = '1.28.0' end
27.377358
96
0.75603
262d9434ddf7b0ce74ee291656471e374b2b9b44
709
require 'spec_helper' feature 'Group activity page', feature: true do let(:user) { create(:group_member, :developer, user: create(:user), group: group ).user } let(:group) { create(:group) } let(:path) { activity_group_path(group) } context 'when signed in' do before do sign_in(user) visit path end it_behaves_like "it has an RSS button with current_user's RSS token" it_behaves_like "an autodiscoverable RSS feed with current_user's RSS token" end context 'when signed out' do before do visit path end it_behaves_like "it has an RSS button without an RSS token" it_behaves_like "an autodiscoverable RSS feed without an RSS token" end end
26.259259
91
0.699577
d5f1a12f3ebb14a3b2ae838ca37a11b33c3a380b
1,114
# Encoding: UTF-8 {fileTypes: ["svn-commit.tmp", "svn-commit.2.tmp"], name: "svn-commit.tmp", patterns: [{captures: {1 => {name: "punctuation.definition.item.subversion-commit"}}, match: /^\s*(?<_1>•).*$\n?/, name: "meta.bullet-point.strong"}, {captures: {1 => {name: "punctuation.definition.item.subversion-commit"}}, match: /^\s*(?<_1>·).*$\n?/, name: "meta.bullet-point.light"}, {captures: {1 => {name: "punctuation.definition.item.subversion-commit"}}, match: /^\s*(?<_1>\*).*$\n?/, name: "meta.bullet-point.star"}, {begin: /(?<_1>^--(?<_2>This line, and those below, will be ignored| Diese und die folgenden Zeilen werden ignoriert )--$\n?)/, beginCaptures: {1 => {name: "meta.separator.svn"}}, end: "^--not gonna happen--$", name: "meta.scope.changed-files.svn", patterns: [{match: /^A\s+.*$\n?/, name: "markup.inserted.svn"}, {match: /^(?<_1>M|.M)\s+.*$\n?/, name: "markup.changed.svn"}, {match: /^D\s+.*$\n?/, name: "markup.deleted.svn"}]}], scopeName: "text.subversion-commit", uuid: "5B201F55-90BC-4A69-9A44-1BABE5A9FE99"}
42.846154
124
0.588869
bf752a1744666748803ea6e80468f8729dea0666
4,328
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::DataMigration::Mgmt::V2018_04_19 module Models # # Properties for the task that validates connection to SQL Server and also # validates source server requirements # class ConnectToSourceSqlServerTaskProperties < ProjectTaskProperties include MsRestAzure def initialize @taskType = "ConnectToSource.SqlServer" end attr_accessor :taskType # @return [ConnectToSourceSqlServerTaskInput] Task input attr_accessor :input # @return [Array<ConnectToSourceSqlServerTaskOutput>] Task output. This # is ignored if submitted. attr_accessor :output # # Mapper for ConnectToSourceSqlServerTaskProperties class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ConnectToSource.SqlServer', type: { name: 'Composite', class_name: 'ConnectToSourceSqlServerTaskProperties', model_properties: { errors: { client_side_validation: true, required: false, read_only: true, serialized_name: 'errors', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'ODataErrorElementType', type: { name: 'Composite', class_name: 'ODataError' } } } }, state: { client_side_validation: true, required: false, read_only: true, serialized_name: 'state', type: { name: 'String' } }, commands: { client_side_validation: true, required: false, read_only: true, serialized_name: 'commands', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'CommandPropertiesElementType', type: { name: 'Composite', polymorphic_discriminator: 'commandType', uber_parent: 'CommandProperties', class_name: 'CommandProperties' } } } }, taskType: { client_side_validation: true, required: true, serialized_name: 'taskType', type: { name: 'String' } }, input: { client_side_validation: true, required: false, serialized_name: 'input', type: { name: 'Composite', class_name: 'ConnectToSourceSqlServerTaskInput' } }, output: { client_side_validation: true, required: false, read_only: true, serialized_name: 'output', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'ConnectToSourceSqlServerTaskOutputElementType', type: { name: 'Composite', polymorphic_discriminator: 'resultType', uber_parent: 'ConnectToSourceSqlServerTaskOutput', class_name: 'ConnectToSourceSqlServerTaskOutput' } } } } } } } end end end end
32.298507
87
0.465342
e95046a30d1839d03e9e0cb7d09a46ee7b63f91b
1,847
Pod::Spec.new do |s| s.name = "iOSSnapshotTestCase" s.module_name = "FBSnapshotTestCase" s.version = "4.0.0" s.summary = "Snapshot view unit tests for iOS" s.description = <<-DESC A "snapshot test case" takes a configured UIView or CALayer and uses the renderInContext: method to get an image snapshot of its contents. It compares this snapshot to a "reference image" stored in your source code repository and fails the test if the two images don't match. DESC s.homepage = "https://github.com/uber/ios-snapshot-test-case" s.license = 'MIT' s.author = 'Uber' s.source = { :git => "https://github.com/uber/ios-snapshot-test-case.git", :tag => s.version.to_s } s.ios.deployment_target = '8.1' s.tvos.deployment_target = '9.0' s.requires_arc = true s.frameworks = 'XCTest','UIKit','Foundation','QuartzCore' s.pod_target_xcconfig = { 'ENABLE_BITCODE' => 'NO' } s.user_target_xcconfig = { 'FRAMEWORK_SEARCH_PATHS' => '$(PLATFORM_DIR)/Developer/Library/Frameworks' } s.default_subspecs = 'SwiftSupport' s.swift_version = '4.0' s.subspec 'Core' do |cs| cs.source_files = 'FBSnapshotTestCase/**/*.{h,m}', 'FBSnapshotTestCase/*.{h,m}' cs.public_header_files = 'FBSnapshotTestCase/FBSnapshotTestCase.h','FBSnapshotTestCase/FBSnapshotTestCasePlatform.h','FBSnapshotTestCase/FBSnapshotTestController.h' cs.private_header_files = 'FBSnapshotTestCase/Categories/UIImage+Compare.h','FBSnapshotTestCase/Categories/UIImage+Diff.h','FBSnapshotTestCase/Categories/UIImage+Snapshot.h' end s.subspec 'SwiftSupport' do |cs| cs.dependency 'iOSSnapshotTestCase/Core' cs.source_files = 'FBSnapshotTestCase/**/*.swift' end end
51.305556
177
0.663238
1d8034b4aad2a9fb7cb8944af30f96f4d4284664
538
class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user if user.role? :super_admin can :manage, :all elsif user.role? :product_admin can :manage, [Product, Asset, Issue] elsif user.role? :product_team can :read, [Product, Asset] # manage products, assets he owns can :manage, Product do |product| product.try(:owner) == user end can :manage, Asset do |asset| asset.assetable.try(:owner) == user end end end end
24.454545
43
0.613383
bf98ca71ba843dc5bbabf244623ea383fa988c46
436
require File.expand_path("../../../../base", __FILE__) require "vagrant/registry" describe Vagrant::Plugin::V2::Components do let(:instance) { described_class.new } describe "configs" do it "should have configs" do instance.configs.should be_kind_of(Hash) end it "should default the values to registries" do instance.configs[:i_probably_dont_exist].should be_kind_of(Vagrant::Registry) end end end
24.222222
83
0.711009
6ad9111e65bc08f26eb347ba7fa19b4552c9d3f0
628
ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../dummy/config/environment.rb", __FILE__) require 'rspec/rails' Dir[File.dirname(__FILE__) + '/fabricators/*.rb'].each { |file| require file } mongoid_file = File.join(File.dirname(__FILE__), "dummy", "config", "mongoid.yml") @settings = YAML.load(ERB.new(File.new(mongoid_file).read).result) Mongoid.configure do |config| config.from_hash(@settings['test']) end RSpec.configure do |config| config.mock_with :rspec config.after :suite do Mongoid.master.collections.select do |collection| collection.name !~ /system/ end.each(&:drop) end end
27.304348
82
0.708599
abc9096824632d8b23a996d8e36aa62cf72f7fe2
3,668
module SmartAnswer class NextStepsForYourBusinessFlow < Flow def define name "next-steps-for-your-business" start_page_content_id "4d7751b5-d860-4812-aa36-5b8c57253ff2" flow_content_id "981e0708-9fa5-42fb-baf5-ee5630a9b722" status :draft response_store :query_parameters # ====================================================================== # What is your company registration number? # ====================================================================== value_question :crn do on_response do |response| self.calculator = Calculators::NextStepsForYourBusinessCalculator.new calculator.crn = response end next_node do question :annual_turnover end end # ====================================================================== # Will your business take more than £85,000 in a 12 month period? # ====================================================================== radio :annual_turnover do option :more_than_85k option :less_than_85k option :not_sure on_response do |response| calculator.annual_turnover = response end next_node do question :employ_someone end end # ====================================================================== # Do you want to employ someone? # ====================================================================== radio :employ_someone do option :yes option :already_employ option :no option :not_sure on_response do |response| calculator.employ_someone = response end next_node do question :business_intent end end # ====================================================================== # Does your business do any of the following? # ====================================================================== checkbox_question :business_intent do option :buy_abroad option :sell_abroad option :sell_online none_option on_response do |response| calculator.business_intent = response.split(",") end next_node do question :business_support end end # ====================================================================== # Are you looking for financial support for: # ====================================================================== checkbox_question :business_support do option :started_finance option :growing_finance option :covid_finance none_option on_response do |response| calculator.business_support = response.split(",") end next_node do question :business_premises end end # ====================================================================== # Where are you running your business? # ====================================================================== radio :business_premises do option :home option :renting option :elsewhere on_response do |response| calculator.business_premises = response end next_node do outcome :results end end # ====================================================================== # Outcome # ====================================================================== outcome :results do view_template "smart_answers/custom_result" end end end end
30.31405
79
0.430752
626aba200d15b60253757520466bbe3929aa7126
435
Gitlab::Seeder.quiet do Issue.all.limit(10).each_with_index do |issue, i| 5.times do user = issue.project.team.users.sample Gitlab::Seeder.by_user(user) do Note.seed(:id, [{ project_id: issue.project.id, author_id: user.id, note: Faker::Lorem.sentence, noteable_id: issue.id, noteable_type: 'Issue' }]) print '.' end end end end
21.75
51
0.563218
6106fe9a93d3aa48148f201a2afa8fcf6b7fb28e
1,861
# -*- encoding: utf-8 -*- require File.expand_path('../lib/citizen_budget_model/version', __FILE__) Gem::Specification.new do |s| s.name = "citizen_budget_model" s.version = CitizenBudgetModel::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Open North"] s.email = ["[email protected]"] s.homepage = "http://github.com/opennorth/citizen_budget_model" s.summary = %q{The Citizen Budget budget simulation model} s.license = 'MIT' s.files = Dir["{app,config,db,lib}/**/*"] + ["LICENSE", "Rakefile", "README.md"] s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.add_dependency('rails', '~> 4.1.0') s.add_dependency('i18n', '<= 0.7') # 0.7 fallbacks can't reference unavailable locales s.add_dependency('pg') # uses array column types # ActiveRecord s.add_dependency('acts_as_list', '~> 0.4.0') s.add_dependency('paranoia', '~> 2.0.2') # Authentication s.add_dependency('devise', '~> 3.5.4') # Internationalization s.add_dependency('globalize', '~> 4.0.2') s.add_dependency('globalize-accessors', '~> 0.1.5') s.add_dependency('redis') # Testing s.add_development_dependency('coveralls') s.add_development_dependency('database_cleaner', '~> 1.2') s.add_development_dependency('factory_girl_rails', '~> 4.1') s.add_development_dependency('guard-bundler', '~> 2.0') s.add_development_dependency('guard-rspec', '~> 4.3') s.add_development_dependency('rspec-rails', '~> 3.0') s.add_development_dependency('shoulda-matchers', '~> 2.7') # Development s.add_development_dependency('pry-rails') s.add_development_dependency('gettext') # Optional #s.add_development_dependency('rails-i18n', '~> 4.0.0') s.add_development_dependency('devise-i18n', '~> 0.12.0') s.add_development_dependency('jquery-rails', '~> 3.1') end
36.490196
90
0.672757
33e32580ad609e24222c82611ccdc1dce83eb50f
4,655
# frozen_string_literal: true module Kindguardian # Utils module module Kindle SECTIONS_DIR = "#{EDITION_DIR}/sections" class << self # Converts HTML edition to Kindle mobi format # Having Calibre as an external dependency # To handle the conversion process def convert_to_mobi playorder = 1 images = [] manifest_items = [] document = Templates.edition_structure section_html_files = [] sections_all = (Pathname.new EDITION_DIR).join 'sections', '*' sections = Dir[sections_all].entries.sort.map do |section_dir| c = File.read("#{Pathname.new(section_dir)}/_section.txt") c.force_encoding('UTF-8') section_title = c.strip articles = Dir["#{Pathname.new(section_dir)}/*"].entries.reject { |x| File.basename(x) =~ /section/ }.sort section_html_files << (section_html_file = "#{Pathname.new(section_dir)}/section.html".to_s) idref = "item-#{section_dir.gsub(/\D/, '')}" document[:spine_items] << { idref: idref } manifest_items << { href: section_html_file, media: 'application/xhtml+xml', idref: idref } s = { path: section_dir, title: section_title, playorder: (playorder += 1), idref: idref, href: "#{Pathname.new(section_dir)}/section.html", articles: articles.map do |article_file| doc = Nokogiri::HTML(File.read(article_file, encoding: 'UTF-8')) title = doc.search('html/head/title').map(&:inner_text).first || 'no title' idref = "item-#{article_file.gsub(/\D/, '')}" document[:spine_items] << { idref: idref } article = { file: article_file, href: article_file, title: title, short_title: Utils.shorten(title, 60), author: doc.search('html/head/meta[@name=author]').map { |n| n[:content] }.first, description: doc.search('html/head/meta[@name=description]').map { |n| n[:content] }.first, playorder: (playorder += 1), idref: idref } manifest_items << { href: article[:file], media: 'application/xhtml+xml', idref: article[:idref] } article end } # Generates the section html out = Mustache.render Templates.get_template('section'), s File.open(section_html_file, 'w') { |f| f.puts out } s end document[:first_article] = sections[0][:articles][0] document['sections'] = sections document[:manifest_items] = manifest_items + images.map.with_index do |img, idx| { href: img[:href], media: img[:mimetype], idref: 'img-%03d' % idx } end # Copy masthead ::FileUtils.cp(File.join(File.dirname(__FILE__), '../..', 'templates/'\ "#{Utils.observer? ? 'observer' : 'guardian'}.gif"), "#{EDITION_DIR}/masthead.gif") Templates.render_template('opf', document, 'kindguardian.opf') Templates.render_template('ncx', document, 'nav-contents.ncx') Templates.render_template('contents', document, 'contents.html') calibre_conversion end # Method to perform the mobi conversion # Using Calibre convert script def calibre_conversion IOUtils.print_info 'Converting to Kindle mobi format' filename = "#{EDITION_DIR}/#{DAILY_EDITION.sub(' ', '_').downcase}-#{TODAY}.mobi" cover = Utils.edition_cover_url _, error_str, status = Open3.capture3( "#{Config.load[:calibre_ebook_convert]} "\ "#{EDITION_DIR}/kindguardian.opf "\ "#{filename} --smarten-punctuation #{"--cover='#{cover}'" unless cover.empty?}" ) abort "Calibre error: #{error_str}" unless status.success? IOUtils.print_info "Wrote #{filename}" rescue StandardError IOUtils.print_error 'ebook-convert binary not found.'\ 'Make sure to install Calibre and/or check the configuration for the correct path.' abort end end end end
40.12931
117
0.529968
bf16161daf0c0e6542cfcfa8f33e8b6c2841ca68
106
RSpec.configure do |config| config.include FactoryBot::Syntax::Methods end FactoryBot.find_definitions
17.666667
44
0.820755
0800e6e87074fa72888261e189c6e456cb9b3699
622
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :facebook_post, :class => 'Services::Facebook::Post' do message { Faker::Lorem.sentence } icon { "http://facebook.com/icon.png" } created_at { Time.now } updated_at { Time.now } association :author, factory: :facebook_user, strategy: :build factory :facebook_post_with_comments do ignore do comments_count 5 end after :build do |post, evaluator| FactoryGirl.build_list :facebook_comment, evaluator.comments_count, commentable: post end end end end
28.272727
93
0.692926
acab0e3ae08cafd6a834d8a281957d13316066ae
3,468
module Sigdump VERSION = "0.2.4" def self.setup(signal=ENV['SIGDUMP_SIGNAL'] || 'SIGCONT', path=ENV['SIGDUMP_PATH']) Kernel.trap(signal) do begin dump(path) rescue end end end def self.dump(path=ENV['SIGDUMP_PATH']) _open_dump_path(path) do |io| io.write "Sigdump at #{Time.now} process #{Process.pid} (#{$0})\n" dump_all_thread_backtrace(io) dump_gc_stat(io) dump_object_count(io) dump_gc_profiler_result(io) end end def self.dump_all_thread_backtrace(io) use_java_bean = defined?(Thread.current.to_java.getNativeThread.getId) if use_java_bean begin bean = java.lang.management.ManagementFactory.getThreadMXBean java_stacktrace_map = Hash[bean.getThreadInfo(bean.getAllThreadIds, true, true).map {|t| [t.getThreadId, t.toString] }] rescue # security error may happen end end Thread.list.each do |thread| dump_backtrace(thread, io) if java_stacktrace_map io.write " In Java " + java_stacktrace_map[thread.to_java.getNativeThread.getId] io.flush end end nil end def self.dump_backtrace(thread, io) status = thread.status if status == nil status = "finished" elsif status == false status = "error" end io.write " Thread #{thread} status=#{status} priority=#{thread.priority}\n" thread.backtrace.each {|bt| io.write " #{bt}\n" } io.flush nil end def self.dump_object_count(io) if defined?(ObjectSpace.count_objects) # ObjectSpace doesn't work in JRuby io.write " Built-in objects:\n" ObjectSpace.count_objects.sort_by {|k,v| -v }.each {|k,v| io.write "%10s: %s\n" % [_fn(v), k] } string_size = 0 array_size = 0 hash_size = 0 cmap = {} ObjectSpace.each_object {|o| c = o.class cmap[c] = (cmap[c] || 0) + 1 if c == String string_size += o.bytesize elsif c == Array array_size = o.size elsif c == Hash hash_size = o.size end } io.write " All objects:\n" cmap.sort_by {|k,v| -v }.each {|k,v| io.write "%10s: %s\n" % [_fn(v), k] } io.write " String #{_fn(string_size)} bytes\n" io.write " Array #{_fn(array_size)} elements\n" io.write " Hash #{_fn(hash_size)} pairs\n" io.flush end nil end def self.dump_gc_stat(io) io.write " GC stat:\n" GC.stat.each do |key, val| io.write " #{key}: #{val}\n" end io.flush nil end def self.dump_gc_profiler_result(io) return unless defined?(GC::Profiler) && GC::Profiler.enabled? io.write " GC profiling result:\n" io.write " Total garbage collection time: %f\n" % GC::Profiler.total_time io.write GC::Profiler.result GC::Profiler.clear io.flush nil end def self._fn(num) s = num.to_s if formatted = s.gsub!(/(\d)(?=(?:\d{3})+(?!\d))/, "\\1,") formatted else s end end private_class_method :_fn def self._open_dump_path(path, &block) case path when nil, "" path = "/tmp/sigdump-#{Process.pid}.log" File.open(path, "a", &block) when IO yield path when "-" yield STDOUT when "+" yield STDERR else File.open(path, "a", &block) end end private_class_method :_open_dump_path end
23.275168
127
0.585928
ed1c8510c81b7eb62ca7760caa2ac966c95294dc
1,551
# -*- encoding: utf-8 -*- # stub: logstash-filter-split 2.0.5 ruby lib Gem::Specification.new do |s| s.name = "logstash-filter-split" s.version = "2.0.5" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.metadata = { "logstash_group" => "filter", "logstash_plugin" => "true" } if s.respond_to? :metadata= s.require_paths = ["lib"] s.authors = ["Elastic"] s.date = "2016-03-30" s.description = "This gem is a logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/plugin install gemname. This gem is not a stand-alone program" s.email = "[email protected]" s.homepage = "http://www.elastic.co/guide/en/logstash/current/index.html" s.licenses = ["Apache License (2.0)"] s.rubygems_version = "2.4.8" s.summary = "The split filter is for splitting multiline messages into separate events." s.installed_by_version = "2.4.8" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<logstash-core-plugin-api>, ["~> 1.0"]) s.add_development_dependency(%q<logstash-devutils>, [">= 0"]) else s.add_dependency(%q<logstash-core-plugin-api>, ["~> 1.0"]) s.add_dependency(%q<logstash-devutils>, [">= 0"]) end else s.add_dependency(%q<logstash-core-plugin-api>, ["~> 1.0"]) s.add_dependency(%q<logstash-devutils>, [">= 0"]) end end
41.918919
192
0.680851
017f3a9fc7b00032085a34c1b98a7fe06508ee1f
1,682
# -*- encoding: utf-8 -*- # stub: xpath 3.1.0 ruby lib Gem::Specification.new do |s| s.name = "xpath" s.version = "3.1.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Jonas Nicklas"] s.cert_chain = ["gem-public_cert.pem"] s.date = "2018-05-26" s.description = "XPath is a Ruby DSL for generating XPath expressions" s.email = ["[email protected]"] s.homepage = "https://github.com/teamcapybara/xpath" s.licenses = ["MIT"] s.required_ruby_version = Gem::Requirement.new(">= 2.2") s.rubygems_version = "2.5.1" s.summary = "Generate XPath expressions from Ruby" s.installed_by_version = "2.5.1" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<nokogiri>, ["~> 1.8"]) s.add_development_dependency(%q<rspec>, ["~> 3.0"]) s.add_development_dependency(%q<yard>, [">= 0.5.8"]) s.add_development_dependency(%q<rake>, [">= 0"]) s.add_development_dependency(%q<pry>, [">= 0"]) else s.add_dependency(%q<nokogiri>, ["~> 1.8"]) s.add_dependency(%q<rspec>, ["~> 3.0"]) s.add_dependency(%q<yard>, [">= 0.5.8"]) s.add_dependency(%q<rake>, [">= 0"]) s.add_dependency(%q<pry>, [">= 0"]) end else s.add_dependency(%q<nokogiri>, ["~> 1.8"]) s.add_dependency(%q<rspec>, ["~> 3.0"]) s.add_dependency(%q<yard>, [">= 0.5.8"]) s.add_dependency(%q<rake>, [">= 0"]) s.add_dependency(%q<pry>, [">= 0"]) end end
35.787234
105
0.62069
4acb2c6fbb43676e873606f35378e1edcefa48f0
1,266
require 'test_helper' class ProductsControllerTest < ActionDispatch::IntegrationTest setup do @product = products(:one) @title = "The Great Book #{rand(1000)}" end test "should get index" do get products_url assert_response :success end test "should get new" do get new_product_url assert_response :success end test "should create product" do assert_difference('Product.count') do post products_url, params: { product: { description: @product.description, image_url: @product.image_url, price: @product.price, title: @title } } end assert_redirected_to product_url(Product.last) end test "should show product" do get product_url(@product) assert_response :success end test "should get edit" do get edit_product_url(@product) assert_response :success end test "should update product" do patch product_url(@product), params: { product: { description: @product.description, image_url: @product.image_url, price: @product.price, title: @title } } assert_redirected_to product_url(@product) end test "should destroy product" do assert_difference('Product.count', -1) do delete product_url(@product) end assert_redirected_to products_url end end
25.32
160
0.71643
01483aa5e0ed826a0647d23a85a34c033f2aab8c
132
require 'test_helper' class Webcore::Test < ActiveSupport::TestCase test "truth" do assert_kind_of Module, Webcore end end
16.5
45
0.75
384b038443e1fff04027c764f3659697c01c98e5
2,245
# # Copyright (C) 2009-2011 the original author or authors. # See the notice.md file distributed with this work for additional # information regarding copyright ownership. # # 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. # RestygwtRailsExample::Application.configure do # Settings specified here will take precedence over those in config/application.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Print deprecation notices to the stderr config.active_support.deprecation = :stderr end
41.574074
85
0.77461