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
|
---|---|---|---|---|---|
1defb255f68b122cdf745a51e3d3acccb5c5725a | 1,381 | module TestHelpers
module Events
class Alb < Base
self.event = {
"requestContext" => {
"elb" => {
"targetGroupArn" => "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/myawesomelambda-1rndy3u8psl2j/3f1bcbeec09c9050"}
},
"httpMethod" => "GET",
"path" => "/",
"multiValueQueryStringParameters" => {"colors[]" => ["blue", "red"]},
"multiValueHeaders" => {
"accept" => ["text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"],
"accept-encoding" => ["gzip"],
"connection" => ["Keep-Alive"],
"cookie" => ["signal1=test; signal2=control"],
"host" => ["myawesomelambda.example.com"],
"user-agent" => ["Amazon CloudFront"],
"via" => ["2.0 3dc5b7040885724e78019cc31f0ef3d9.cloudfront.net (CloudFront)"],
"x-amz-cf-id" => ["BSlDkHoVD8-009TATJzymLqSBzViE_6jj7DlkiJkub-PpDb8wI4Pxw=="],
"x-amzn-trace-id" => ["Root=1-5e7c160a-0a9065c7a28a428cd8b98215"],
"x-forwarded-for" => ["72.218.219.201", "72.218.219.201", "34.195.252.132"],
"x-forwarded-host" => ["myawesomelambda.example.com"],
"x-forwarded-port" => ["443"],
"x-forwarded-proto" => ["https"]
},
"body" => "",
"isBase64Encoded" => false
}.freeze
end
end
end
| 39.457143 | 145 | 0.553222 |
e249b51807a4246fbf12d92eb71ca1c8145b1141 | 428 | module Cmor::Partners
class CategoriesController < Cmor::Core::Backend::ResourcesController::Base
include Rao::ResourcesController::ActsAsListConcern
include Rao::ResourcesController::ActsAsPublishedConcern
def self.resource_class
Cmor::Partners::Category
end
private
def permitted_params
params.require(:category).permit(:locale, :identifier, :name, :body, :published)
end
end
end | 26.75 | 86 | 0.740654 |
6a28d837b79be83a45e1992ace729c1336cb3335 | 617 | # Copyright (c) 2009-2012 VMware, Inc.
require 'bosh_agent'
module Bosh::Agent
class UnknownInfrastructure < StandardError; end
class Infrastructure
def initialize(infrastructure_name)
@name = infrastructure_name
infrastructure = File.join(File.dirname(__FILE__), 'infrastructure', "#{infrastructure_name}.rb")
if File.exist?(infrastructure)
require infrastructure
else
raise UnknownInfrastructure, "infrastructure '#{infrastructure_name}' not found"
end
end
def infrastructure
Infrastructure.const_get(@name.capitalize).new
end
end
end
| 23.730769 | 103 | 0.713128 |
79a5017468fcb63bc8b5fe37588e1e73418489c2 | 1,897 | class Fish < Formula
desc "User-friendly command-line shell for UNIX-like operating systems"
homepage "https://fishshell.com"
url "https://github.com/fish-shell/fish-shell/releases/download/3.0.2/fish-3.0.2.tar.gz"
sha256 "14728ccc6b8e053d01526ebbd0822ca4eb0235e6487e832ec1d0d22f1395430e"
bottle do
root_url "https://linuxbrew.bintray.com/bottles"
cellar :any
sha256 "0dda76c64b0e2b4f1bfe48b816346f54a3fd9531550439caadadc6a1641c6d6b" => :mojave
sha256 "aaa15fbea68f8414084124da4347aec31484a3ab6320daf5f1cd54e208bf32c1" => :high_sierra
sha256 "65eb56f5d3e5978051743e0e1a6616983f34922cad65cbe0964b671d9bf4437e" => :sierra
sha256 "8fc29cc02ed7bd7f253f686bf5a066761581b282ae0a01fcb2a0eabb389e378b" => :x86_64_linux
end
head do
url "https://github.com/fish-shell/fish-shell.git", :shallow => false
depends_on "doxygen" => :build
end
depends_on "cmake" => :build
depends_on "pcre2"
depends_on "ncurses" unless OS.mac?
def install
# In Homebrew's 'superenv' sed's path will be incompatible, so
# the correct path is passed into configure here.
args = %W[
-Dextra_functionsdir=#{HOMEBREW_PREFIX}/share/fish/vendor_functions.d
-Dextra_completionsdir=#{HOMEBREW_PREFIX}/share/fish/vendor_completions.d
-Dextra_confdir=#{HOMEBREW_PREFIX}/share/fish/vendor_conf.d
]
args << "-DSED=/usr/bin/sed" if OS.mac?
system "cmake", ".", *std_cmake_args, *args
system "make", "install"
end
def post_install
(pkgshare/"vendor_functions.d").mkpath
(pkgshare/"vendor_completions.d").mkpath
(pkgshare/"vendor_conf.d").mkpath
end
def caveats; <<~EOS
You will need to add:
#{HOMEBREW_PREFIX}/bin/fish
to /etc/shells.
Then run:
chsh -s #{HOMEBREW_PREFIX}/bin/fish
to make fish your default shell.
EOS
end
test do
system "#{bin}/fish", "-c", "echo"
end
end
| 31.616667 | 94 | 0.721139 |
62442967037065d2dae5046238daaa343c37f155 | 3,567 | # frozen_string_literal: false
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** Type: MMv1 ***
#
# ----------------------------------------------------------------------------
#
# This file is automatically generated by Magic Modules and manual
# changes will be clobbered when the file is regenerated.
#
# Please read more about how to change this file in README.md and
# CONTRIBUTING.md located at the root of this package.
#
# ----------------------------------------------------------------------------
require 'gcp_backend'
class ComputeRegionInstanceGroups < GcpResourceBase
name 'google_compute_region_instance_groups'
desc 'RegionInstanceGroup plural resource'
supports platform: 'gcp'
attr_reader :table
filter_table_config = FilterTable.create
filter_table_config.add(:creation_timestamps, field: :creation_timestamp)
filter_table_config.add(:descriptions, field: :description)
filter_table_config.add(:ids, field: :id)
filter_table_config.add(:names, field: :name)
filter_table_config.add(:fingerprints, field: :fingerprint)
filter_table_config.add(:networks, field: :network)
filter_table_config.add(:zones, field: :zone)
filter_table_config.add(:sizes, field: :size)
filter_table_config.add(:regions, field: :region)
filter_table_config.add(:named_ports, field: :named_ports)
filter_table_config.connect(self, :table)
def initialize(params = {})
super(params.merge({ use_http_transport: true }))
@params = params
@table = fetch_wrapped_resource('items')
end
def fetch_wrapped_resource(wrap_path)
# fetch_resource returns an array of responses (to handle pagination)
result = @connection.fetch_all(product_url, resource_base_url, @params, 'Get')
return if result.nil?
# Conversion of string -> object hash to symbol -> object hash that InSpec needs
converted = []
result.each do |response|
next if response.nil? || !response.key?(wrap_path)
response[wrap_path].each do |hash|
hash_with_symbols = {}
hash.each_key do |key|
name, value = transform(key, hash)
hash_with_symbols[name] = value
end
converted.push(hash_with_symbols)
end
end
converted
end
def transform(key, value)
return transformers[key].call(value) if transformers.key?(key)
[key.to_sym, value]
end
def transformers
{
'creationTimestamp' => ->(obj) { return :creation_timestamp, parse_time_string(obj['creationTimestamp']) },
'description' => ->(obj) { return :description, obj['description'] },
'id' => ->(obj) { return :id, obj['id'] },
'name' => ->(obj) { return :name, obj['name'] },
'fingerprint' => ->(obj) { return :fingerprint, obj['fingerprint'] },
'network' => ->(obj) { return :network, obj['network'] },
'zone' => ->(obj) { return :zone, obj['zone'] },
'size' => ->(obj) { return :size, obj['size'] },
'region' => ->(obj) { return :region, obj['region'] },
'namedPorts' => ->(obj) { return :named_ports, GoogleInSpec::Compute::Property::RegionInstanceGroupNamedPortsArray.parse(obj['namedPorts'], to_s) },
}
end
# Handles parsing RFC3339 time string
def parse_time_string(time_string)
time_string ? Time.parse(time_string) : nil
end
private
def product_url(_ = nil)
'https://compute.googleapis.com/compute/v1/'
end
def resource_base_url
'projects/{{project}}/regions/{{region}}/instanceGroups'
end
end
| 34.631068 | 154 | 0.634987 |
08fff1cc02112da6d4aa790bfb83ff3dcbc36261 | 897 |
require 'appl_work'
require 'db_admin_ms'
namespace :lib do
desc "launch regular work task"
task :run => :environment do
pc = ApplWork.new
#pc.parse_genes
#pc.select_genes
#pc.parse_gene_seqs
#pc.parse_gene_seqs_info
#pc.retrieve_naseq
#pc.ortho_run
#pc.msa_run
pc.blo_run
#pc.recomb_run
#pc.execute
end
desc "launch master tasks"
task :ms_launch => :environment do
#print "How many fake people do you want?"
#num_people = $stdin.gets.to_i
# num_people.times do
# Person.create(:first_name => Faker::Name.first_name,
# :last_name => Faker::Name.last_name)
#end
#print "#{num_people} created.\n"
hsa = HsqlMasterAdmin.new
#hsa.erase()
#hsa.create()
puts 'just finished the environement....'
puts Time.now
hsa.populate_job_description()
end
end | 16.017857 | 59 | 0.630992 |
1178169433b9cad325266ab670e8b28cd15511c6 | 5,248 | # frozen_string_literal: true
# typed: strict
module Redcord::Attribute
extend T::Sig
extend T::Helpers
# We implicitly determine what should be a range index on Redis based on Ruby
# type.
RangeIndexType = T.type_alias {
T.any(
Float,
Integer,
NilClass,
Numeric,
Time,
)
}
# Implicitly determine what data type can be a used in custom index on Redis based on Ruby type.
# Custom index currently supports positive integers with up to 19 characters in decimal notation,
# will raise error in Lua if bigger numbers are used.
CustomIndexType = T.type_alias {
T.any(
Integer,
Time,
)
}
sig { params(klass: T.class_of(T::Struct)).void }
def self.included(klass)
klass.extend(ClassMethods)
klass.include(InstanceMethods)
klass.class_variable_set(:@@index_attributes, Set.new)
klass.class_variable_set(:@@range_index_attributes, Set.new)
klass.class_variable_set(:@@custom_index_attributes, Hash.new)
klass.class_variable_set(:@@ttl, nil)
klass.class_variable_set(:@@shard_by_attribute, nil)
end
module ClassMethods
extend T::Sig
sig do
params(
name: Symbol,
type: T.untyped, # until smth better is proposed
options: T::Hash[Symbol, T.untyped],
).void
end
def attribute(name, type, options = {})
# TODO: support uniq options
# TODO: validate types
prop(name, type)
index_attribute(name, type) if options[:index]
end
sig { params(attr: Symbol, type: T.any(Class, T::Types::Base)).void }
def index_attribute(attr, type)
if should_range_index?(type)
class_variable_get(:@@range_index_attributes) << attr
else
class_variable_get(:@@index_attributes) << attr
end
end
sig { params(index_name: Symbol, attrs: T::Array[Symbol]).void }
def custom_index(index_name, attrs)
attrs.each do |attr|
type = props[attr][:type]
if !can_custom_index?(type)
raise(Redcord::WrongAttributeType, "Custom index doesn't support '#{type}' attributes.")
end
end
shard_by_attr = class_variable_get(:@@shard_by_attribute)
if shard_by_attr and shard_by_attr != attrs.first
raise(
Redcord::CustomIndexInvalidDesign,
"shard_by attribute '#{shard_by_attr}' must be placed first in '#{index_name}' index"
)
end
class_variable_get(:@@custom_index_attributes)[index_name] = attrs
end
sig { params(duration: T.nilable(ActiveSupport::Duration)).void }
def ttl(duration)
class_variable_set(:@@ttl, duration)
end
def shard_by_attribute(attr=nil)
return class_variable_get(:@@shard_by_attribute) if attr.nil?
# attr must be an non-index attribute (index: false)
if class_variable_get(:@@index_attributes).include?(attr) ||
class_variable_get(:@@range_index_attributes).include?(attr)
raise Redcord::InvalidAttribute, "Cannot shard by an index attribute '#{attr}'"
end
class_variable_get(:@@custom_index_attributes).each do |index_name, attrs|
if attr != attrs.first
raise(
Redcord::CustomIndexInvalidDesign,
"shard_by attribute '#{attr}' must be placed first in '#{index_name}' index"
)
end
# Delete the shard_by_attribute since it would be a constant in the
# custom index set
attrs.shift
end
class_variable_set(:@@shard_by_attribute, attr)
end
sig { returns(Integer) }
def _script_arg_ttl
class_variable_get(:@@ttl)&.to_i || -1
end
sig { returns(T::Array[Symbol]) }
def _script_arg_index_attrs
class_variable_get(:@@index_attributes).to_a
end
sig { returns(T::Array[Symbol]) }
def _script_arg_range_index_attrs
class_variable_get(:@@range_index_attributes).to_a
end
sig { returns(T::Hash[Symbol, T::Array]) }
def _script_arg_custom_index_attrs
class_variable_get(:@@custom_index_attributes)
end
private
sig { params(type: T.any(Class, T::Types::Base)).returns(T::Boolean) }
def should_range_index?(type)
# Change Ruby raw type to Sorbet type in order to call subtype_of?
type = T::Types::Simple.new(type) if type.is_a?(Class)
type.subtype_of?(RangeIndexType)
end
sig { params(type: T.any(Class, T::Types::Base)).returns(T::Boolean) }
def can_custom_index?(type)
# Change Ruby raw type to Sorbet type in order to call subtype_of?
type = T::Types::Simple.new(type) if type.is_a?(Class)
type.subtype_of?(CustomIndexType)
end
end
module InstanceMethods
extend T::Sig
sig { returns(T.nilable(String)) }
def hash_tag
attr = self.class.class_variable_get(:@@shard_by_attribute)
return nil if attr.nil?
# A blank hash tag would cause MOVED error in cluster mode
tag = send(attr)
default_tag = '__redcord_hash_tag_null__'
if tag == default_tag
raise Redcord::InvalidAttribute, "#{attr}=#{default_tag} conflicts with default hash_tag value"
end
"{#{tag || default_tag}}"
end
end
mixes_in_class_methods(ClassMethods)
end
| 29.483146 | 103 | 0.659489 |
6266b2ecb01afa9f20732a6bfd64374cdef3b5df | 191 | # This migration comes from shipit (originally 20180202220850)
class AddAbortedByToTasks < ActiveRecord::Migration[5.1]
def change
add_column :tasks, :aborted_by_id, :integer
end
end
| 27.285714 | 62 | 0.780105 |
4a40f4e8c2a5db3f75a780d9dc16c8595a0098ee | 979 | module Draper
# Provides access to helper methods - both Rails built-in helpers, and those
# defined in your application.
class HelperProxy
# @overload initialize(view_context)
def initialize(view_context = nil)
view_context ||= current_view_context # backwards compatibility
@view_context = view_context
end
# Sends helper methods to the view context.
def method_missing(method, *args, &block)
self.class.define_proxy method
send(method, *args, &block)
end
delegate :capture, to: :view_context
protected
attr_reader :view_context
private
def self.define_proxy(name)
define_method name do |*args, &block|
view_context.send(name, *args, &block)
end
end
def current_view_context
ActiveSupport::Deprecation.warn("wrong number of arguments (0 for 1) passed to Draper::HelperProxy.new", caller[1..-1])
Draper::ViewContext.current.view_context
end
end
end
| 25.102564 | 125 | 0.693565 |
ed1a7dae982b4a15e26bd867fb0d19f342774c9a | 14,509 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 File.dirname(__FILE__) + '/../../spec_helper.rb'
share_as :HaveSpecHelper do
def create_collection_owner_with(n)
owner = Spec::Expectations::Helper::CollectionOwner.new
(1..n).each do |n|
owner.add_to_collection_with_length_method(n)
owner.add_to_collection_with_size_method(n)
end
owner
end
before(:each) do
unless defined?(ActiveSupport::Inflector)
@active_support_was_not_defined
module ActiveSupport
class Inflector
def self.pluralize(string)
string.to_s + 's'
end
end
end
end
end
end
describe "should have(n).items" do
include HaveSpecHelper
it "should pass if target has a collection of items with n members" do
owner = create_collection_owner_with(3)
owner.should have(3).items_in_collection_with_length_method
owner.should have(3).items_in_collection_with_size_method
end
it "should convert :no to 0" do
owner = create_collection_owner_with(0)
owner.should have(:no).items_in_collection_with_length_method
owner.should have(:no).items_in_collection_with_size_method
end
it "should fail if target has a collection of items with < n members" do
owner = create_collection_owner_with(3)
lambda {
owner.should have(4).items_in_collection_with_length_method
}.should fail_with("expected 4 items_in_collection_with_length_method, got 3")
lambda {
owner.should have(4).items_in_collection_with_size_method
}.should fail_with("expected 4 items_in_collection_with_size_method, got 3")
end
it "should fail if target has a collection of items with > n members" do
owner = create_collection_owner_with(3)
lambda {
owner.should have(2).items_in_collection_with_length_method
}.should fail_with("expected 2 items_in_collection_with_length_method, got 3")
lambda {
owner.should have(2).items_in_collection_with_size_method
}.should fail_with("expected 2 items_in_collection_with_size_method, got 3")
end
end
describe 'should have(1).item when ActiveSupport::Inflector is defined' do
include HaveSpecHelper
it 'should pluralize the collection name' do
owner = create_collection_owner_with(1)
owner.should have(1).item
end
after(:each) do
if @active_support_was_not_defined
Object.__send__ :remove_const, :ActiveSupport
end
end
end
describe 'should have(1).item when Inflector is defined' do
include HaveSpecHelper
before(:each) do
unless defined?(Inflector)
@inflector_was_not_defined
class Inflector
def self.pluralize(string)
string.to_s + 's'
end
end
end
end
it 'should pluralize the collection name' do
owner = create_collection_owner_with(1)
owner.should have(1).item
end
after(:each) do
if @inflector_was_not_defined
Object.__send__ :remove_const, :Inflector
end
end
end
describe "should have(n).items where result responds to items but returns something other than a collection" do
it "should provide a meaningful error" do
owner = Class.new do
def items
Object.new
end
end.new
lambda do
owner.should have(3).items
end.should raise_error("expected items to be a collection but it does not respond to #length or #size")
end
end
describe "should_not have(n).items" do
include HaveSpecHelper
it "should pass if target has a collection of items with < n members" do
owner = create_collection_owner_with(3)
owner.should_not have(4).items_in_collection_with_length_method
owner.should_not have(4).items_in_collection_with_size_method
end
it "should pass if target has a collection of items with > n members" do
owner = create_collection_owner_with(3)
owner.should_not have(2).items_in_collection_with_length_method
owner.should_not have(2).items_in_collection_with_size_method
end
it "should fail if target has a collection of items with n members" do
owner = create_collection_owner_with(3)
lambda {
owner.should_not have(3).items_in_collection_with_length_method
}.should fail_with("expected target not to have 3 items_in_collection_with_length_method, got 3")
lambda {
owner.should_not have(3).items_in_collection_with_size_method
}.should fail_with("expected target not to have 3 items_in_collection_with_size_method, got 3")
end
end
describe "should have_exactly(n).items" do
include HaveSpecHelper
it "should pass if target has a collection of items with n members" do
owner = create_collection_owner_with(3)
owner.should have_exactly(3).items_in_collection_with_length_method
owner.should have_exactly(3).items_in_collection_with_size_method
end
it "should convert :no to 0" do
owner = create_collection_owner_with(0)
owner.should have_exactly(:no).items_in_collection_with_length_method
owner.should have_exactly(:no).items_in_collection_with_size_method
end
it "should fail if target has a collection of items with < n members" do
owner = create_collection_owner_with(3)
lambda {
owner.should have_exactly(4).items_in_collection_with_length_method
}.should fail_with("expected 4 items_in_collection_with_length_method, got 3")
lambda {
owner.should have_exactly(4).items_in_collection_with_size_method
}.should fail_with("expected 4 items_in_collection_with_size_method, got 3")
end
it "should fail if target has a collection of items with > n members" do
owner = create_collection_owner_with(3)
lambda {
owner.should have_exactly(2).items_in_collection_with_length_method
}.should fail_with("expected 2 items_in_collection_with_length_method, got 3")
lambda {
owner.should have_exactly(2).items_in_collection_with_size_method
}.should fail_with("expected 2 items_in_collection_with_size_method, got 3")
end
end
describe "should have_at_least(n).items" do
include HaveSpecHelper
it "should pass if target has a collection of items with n members" do
owner = create_collection_owner_with(3)
owner.should have_at_least(3).items_in_collection_with_length_method
owner.should have_at_least(3).items_in_collection_with_size_method
end
it "should pass if target has a collection of items with > n members" do
owner = create_collection_owner_with(3)
owner.should have_at_least(2).items_in_collection_with_length_method
owner.should have_at_least(2).items_in_collection_with_size_method
end
it "should fail if target has a collection of items with < n members" do
owner = create_collection_owner_with(3)
lambda {
owner.should have_at_least(4).items_in_collection_with_length_method
}.should fail_with("expected at least 4 items_in_collection_with_length_method, got 3")
lambda {
owner.should have_at_least(4).items_in_collection_with_size_method
}.should fail_with("expected at least 4 items_in_collection_with_size_method, got 3")
end
it "should provide educational negative failure messages" do
#given
owner = create_collection_owner_with(3)
length_matcher = have_at_least(3).items_in_collection_with_length_method
size_matcher = have_at_least(3).items_in_collection_with_size_method
#when
length_matcher.matches?(owner)
size_matcher.matches?(owner)
#then
length_matcher.negative_failure_message.should == <<-EOF
Isn't life confusing enough?
Instead of having to figure out the meaning of this:
should_not have_at_least(3).items_in_collection_with_length_method
We recommend that you use this instead:
should have_at_most(2).items_in_collection_with_length_method
EOF
size_matcher.negative_failure_message.should == <<-EOF
Isn't life confusing enough?
Instead of having to figure out the meaning of this:
should_not have_at_least(3).items_in_collection_with_size_method
We recommend that you use this instead:
should have_at_most(2).items_in_collection_with_size_method
EOF
end
end
describe "should have_at_most(n).items" do
include HaveSpecHelper
it "should pass if target has a collection of items with n members" do
owner = create_collection_owner_with(3)
owner.should have_at_most(3).items_in_collection_with_length_method
owner.should have_at_most(3).items_in_collection_with_size_method
end
it "should fail if target has a collection of items with > n members" do
owner = create_collection_owner_with(3)
lambda {
owner.should have_at_most(2).items_in_collection_with_length_method
}.should fail_with("expected at most 2 items_in_collection_with_length_method, got 3")
lambda {
owner.should have_at_most(2).items_in_collection_with_size_method
}.should fail_with("expected at most 2 items_in_collection_with_size_method, got 3")
end
it "should pass if target has a collection of items with < n members" do
owner = create_collection_owner_with(3)
owner.should have_at_most(4).items_in_collection_with_length_method
owner.should have_at_most(4).items_in_collection_with_size_method
end
it "should provide educational negative failure messages" do
#given
owner = create_collection_owner_with(3)
length_matcher = have_at_most(3).items_in_collection_with_length_method
size_matcher = have_at_most(3).items_in_collection_with_size_method
#when
length_matcher.matches?(owner)
size_matcher.matches?(owner)
#then
length_matcher.negative_failure_message.should == <<-EOF
Isn't life confusing enough?
Instead of having to figure out the meaning of this:
should_not have_at_most(3).items_in_collection_with_length_method
We recommend that you use this instead:
should have_at_least(4).items_in_collection_with_length_method
EOF
size_matcher.negative_failure_message.should == <<-EOF
Isn't life confusing enough?
Instead of having to figure out the meaning of this:
should_not have_at_most(3).items_in_collection_with_size_method
We recommend that you use this instead:
should have_at_least(4).items_in_collection_with_size_method
EOF
end
end
describe "have(n).items(args, block)" do
it "should pass args to target" do
target = mock("target")
target.should_receive(:items).with("arg1","arg2").and_return([1,2,3])
target.should have(3).items("arg1","arg2")
end
it "should pass block to target" do
target = mock("target")
block = lambda { 5 }
target.should_receive(:items).with("arg1","arg2", block).and_return([1,2,3])
target.should have(3).items("arg1","arg2", block)
end
end
describe "have(n).items where target IS a collection" do
it "should reference the number of items IN the collection" do
[1,2,3].should have(3).items
end
it "should fail when the number of items IN the collection is not as expected" do
lambda { [1,2,3].should have(7).items }.should fail_with("expected 7 items, got 3")
end
end
describe "have(n).characters where target IS a String" do
it "should pass if the length is correct" do
"this string".should have(11).characters
end
it "should fail if the length is incorrect" do
lambda { "this string".should have(12).characters }.should fail_with("expected 12 characters, got 11")
end
end
describe "have(n).things on an object which is not a collection nor contains one" do
it "should fail" do
lambda { Object.new.should have(2).things }.should raise_error(NoMethodError, /undefined method `things' for #<Object:/)
end
end
describe Spec::Matchers::Have, "for a collection owner that implements #send" do
include HaveSpecHelper
before(:each) do
@collection = Object.new
def @collection.floozles; [1,2] end
def @collection.send(*args); raise "DOH! Library developers shouldn't use #send!" end
end
it "should work in the straightforward case" do
lambda {
@collection.should have(2).floozles
}.should_not raise_error
end
it "should work when doing automatic pluralization" do
lambda {
@collection.should have_at_least(1).floozle
}.should_not raise_error
end
it "should blow up when the owner doesn't respond to that method" do
lambda {
@collection.should have(99).problems
}.should raise_error(NoMethodError, /problems/)
end
end
module Spec
module Matchers
describe Have do
it "should have method_missing as private" do
with_ruby '1.8' do
Have.private_instance_methods.should include("method_missing")
end
with_ruby '1.9' do
Have.private_instance_methods.should include(:method_missing)
end
end
describe "respond_to?" do
before :each do
@have = Have.new(:foo)
@a_method_which_have_defines = Have.instance_methods.first
@a_method_which_object_defines = Object.instance_methods.first
end
it "should be true for a method which Have defines" do
@have.should respond_to(@a_method_which_have_defines)
end
it "should be true for a method that it's superclass (Object) defines" do
@have.should respond_to(@a_method_which_object_defines)
end
it "should be false for a method which neither Object nor nor Have defines" do
@have.should_not respond_to(:foo_bar_baz)
end
it "should be false if the owner doesn't respond to the method" do
have = Have.new(99)
have.should_not respond_to(:problems)
end
it "should be true if the owner responds to the method" do
have = Have.new(:a_symbol)
have.should respond_to(:to_sym)
end
end
end
end
end
| 34.793765 | 124 | 0.74023 |
7a70d3a6caed0605fcd10222d8586b05d4a2c06a | 515 | require './config/environment'
class ApplicationController < Sinatra::Base
configure do
set :public_folder, 'public'
set :views, 'app/views'
enable :sessions
set :session_secret, 'problems'
end
helpers do
def logged_in?
!!session[:user_id]
end
def current_user
User.find(session[:user_id])
end
end
private
def authenticate_user
if !logged_in?
#You must be logged in to access this page
redirect '/login'
end
end
end
| 16.09375 | 50 | 0.63301 |
61b5ba7e53f0bce145d75ddd748ea8d6a4125743 | 3,245 | class DutyExpressionFormatter
class << self
def prettify(float)
TradeTariffBackend.number_formatter.number_with_precision(
float,
minimum_decimal_points: 2,
precision: 4,
strip_insignificant_zeros: true
)
end
def format(opts = {})
duty_expression_id = opts[:duty_expression_id]
duty_expression_description = opts[:duty_expression_description]
duty_expression_abbreviation = opts[:duty_expression_abbreviation]
duty_amount = opts[:duty_amount]
monetary_unit = opts[:monetary_unit_abbreviation].presence || opts[:monetary_unit]
measurement_unit = opts[:measurement_unit]
measurement_unit_qualifier = opts[:measurement_unit_qualifier]
measurement_unit_abbreviation = measurement_unit.try :abbreviation,
measurement_unit_qualifier: measurement_unit_qualifier
output = []
case duty_expression_id
when "99"
output << if opts[:formatted]
"<abbr title='#{measurement_unit.description}'>#{measurement_unit_abbreviation}</abbr>"
else
measurement_unit_abbreviation.to_s
end
when "12", "14", "37", "40", "41", "42", "43", "44", "21", "25", "27", "29"
if duty_expression_abbreviation.present?
output << duty_expression_abbreviation
elsif duty_expression_description.present?
output << duty_expression_description
end
when "02", "04", "15", "17", "19", "20", "36"
if duty_expression_abbreviation.present?
output << duty_expression_abbreviation
elsif duty_expression_description.present?
output << duty_expression_description
end
if duty_amount.present?
output << prettify(duty_amount).to_s
end
output << if monetary_unit.present?
monetary_unit
else
"%"
end
if measurement_unit_abbreviation.present?
output << if opts[:formatted]
"/ <abbr title='#{measurement_unit.description}'>#{measurement_unit_abbreviation}</abbr>"
else
"/ #{measurement_unit_abbreviation}"
end
end
else
if duty_amount.present?
output << prettify(duty_amount).to_s
end
if duty_expression_abbreviation.present? && !monetary_unit.present?
output << duty_expression_abbreviation
elsif duty_expression_description.present? && !monetary_unit.present?
output << duty_expression_description
elsif duty_expression_description.blank?
output << "%"
end
if monetary_unit.present?
output << monetary_unit
end
if measurement_unit_abbreviation.present?
output << if opts[:formatted]
"/ <abbr title='#{measurement_unit.description}'>#{measurement_unit_abbreviation}</abbr>"
else
"/ #{measurement_unit_abbreviation}"
end
end
end
output.join(" ").html_safe
end
end
end
| 38.630952 | 113 | 0.598767 |
f8b9326afceee7355cf76f4ec5b790f432c95ee7 | 89 | class SessionsController < Devise::SessionsController
def destroy
super
end
end | 12.714286 | 53 | 0.764045 |
2186ce8172fbf8058715b388e657a99d188c71db | 120 | require 'serverspec'
include Serverspec::Helper::Exec
include Serverspec::Helper::DetectOS
RSpec.configure do |c|
end
| 15 | 36 | 0.791667 |
33fdb030dfc538e96c5f089fad724513eb4acd98 | 45,658 | # frozen_string_literal: true
# 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 'base64'
require_relative 'search_context'
require_relative 'screenshot'
module Appium
module Core
class Base
class Driver < ::Selenium::WebDriver::Driver
include ::Selenium::WebDriver::DriverExtensions::UploadsFiles
include ::Selenium::WebDriver::DriverExtensions::HasSessionId
include ::Selenium::WebDriver::DriverExtensions::Rotatable
include ::Selenium::WebDriver::DriverExtensions::HasRemoteStatus
include ::Selenium::WebDriver::DriverExtensions::HasWebStorage
include ::Appium::Core::Base::SearchContext
include ::Appium::Core::Base::TakeScreenshot
# Private API.
# Do not use this for general use. Used by flutter driver to get bridge for creating a new element
attr_reader :bridge
def initialize(opts = {})
listener = opts.delete(:listener)
@bridge = ::Appium::Core::Base::Bridge.handshake(**opts)
if @bridge.dialect == :oss # MJSONWP
extend ::Selenium::WebDriver::DriverExtensions::HasTouchScreen
extend ::Selenium::WebDriver::DriverExtensions::HasLocation
extend ::Selenium::WebDriver::DriverExtensions::HasNetworkConnection
elsif @bridge.dialect == :w3c
# TODO: Only for Appium. Ideally, we'd like to remove the below like selenium-webdriver
extend ::Selenium::WebDriver::DriverExtensions::HasTouchScreen
extend ::Selenium::WebDriver::DriverExtensions::HasLocation
extend ::Selenium::WebDriver::DriverExtensions::HasNetworkConnection
end
super(@bridge, listener: listener)
end
# Get the dialect value
# @return [:oss|:w3c]
def dialect
@bridge.dialect
end
# Update +server_url+ and HTTP clients following this arguments, protocol, host, port and path.
# After this method, [email protected]+ will be a new instance following them instead of +server_url+ which is
# set before creating session.
#
# @example
#
# driver = core.start_driver server_url: 'http://example1.com:8000/wd/hub # @bridge.http is for 'http://example1.com:8000/wd/hub/'
# driver.update_sending_request_to protocol: 'https', host: 'example2.com', port: 9000, path: '/wd/hub'
# driver.manage.timeouts.implicit_wait = 10 # @bridge.http is for 'https://example2.com:9000/wd/hub/'
#
def update_sending_request_to(protocol:, host:, port:, path:)
@bridge.http.update_sending_request_to(scheme: protocol,
host: host,
port: port,
path: path)
end
### Methods for Appium
# Lock the device
# @return [String]
#
# @example
#
# @driver.lock #=> Lock the device
# @driver.lock(5) #=> Lock the device in 5 sec and unlock the device after 5 sec.
# # Block other commands during locking the device.
#
def lock(duration = nil)
@bridge.lock(duration)
end
# Check current device status is weather locked or not
#
# @example
#
# @driver.device_locked?
# @driver.locked?
#
def locked?
@bridge.device_locked?
end
alias device_locked? locked?
# Unlock the device
#
# @example
#
# @driver.unlock
#
def unlock
@bridge.unlock
end
# Hide the onscreen keyboard
# @param [String] close_key The name of the key which closes the keyboard.
# Defaults to 'Done' for iOS(except for XCUITest).
# @param [Symbol] strategy The symbol of the strategy which closes the keyboard.
# XCUITest ignore this argument.
# Default for iOS is +:pressKey+. Default for Android is +:tapOutside+.
#
# @example
#
# @driver.hide_keyboard # Close a keyboard with the 'Done' button
# @driver.hide_keyboard('Finished') # Close a keyboard with the 'Finished' button
# @driver.hide_keyboard(nil, :tapOutside) # Close a keyboard with tapping out side of keyboard
#
def hide_keyboard(close_key = nil, strategy = nil)
@bridge.hide_keyboard close_key, strategy
end
# Get whether keyboard is displayed or not.
# @return [Boolean] Return true if keyboard is shown. Return false if keyboard is hidden.
#
# @example
# @driver.is_keyboard_shown # false
# @driver.keyboard_shown? # true
#
def keyboard_shown?
@bridge.is_keyboard_shown
end
alias is_keyboard_shown keyboard_shown?
# [DEPRECATION]
# Send keys for a current active element
# @param [String] key Input text
#
# @example
#
# @driver.send_keys 'happy testing!'
#
def send_keys(*key)
::Appium::Logger.warn(
'[DEPRECATION] Driver#send_keys is deprecated in W3C spec. Use driver.action.<command>.perform instead'
)
@bridge.send_keys_to_active_element(key)
end
alias type send_keys
class DriverSettings
# @private this class is private
def initialize(bridge)
@bridge = bridge
end
def get
@bridge.get_settings
end
def update(settings)
@bridge.update_settings(settings)
end
end
private_constant :DriverSettings
# Returns an instance of DriverSettings to call get/update.
#
# @example
#
# @driver.settings.get
# @driver.settings.update('allowInvisibleElements': true)
#
def settings
@driver_settings ||= DriverSettings.new(@bridge) # rubocop:disable Naming/MemoizedInstanceVariableName
end
# Get appium Settings for current test session.
# Alias of @driver.settings.get
#
# @example
#
# @driver.get_settings
# @driver.settings.get
#
def get_settings
settings.get
end
# Update Appium Settings for current test session
# Alias of @driver.settings#update
#
# @param [Hash] value Settings to update, keys are settings, values to value to set each setting to
#
# @example
#
# @driver.update_settings('allowInvisibleElements': true)
# @driver.settings.update('allowInvisibleElements': true)
# @driver.settings = { 'allowInvisibleElements': true }
#
def settings=(value)
settings.update(value)
end
alias update_settings settings=
class DeviceIME
# @private this class is private
def initialize(bridge)
@bridge = bridge
end
def activate(ime_name)
@bridge.ime_activate(ime_name)
end
def available_engines
@bridge.ime_available_engines
end
def active_engine
@bridge.ime_active_engine
end
def activated?
@bridge.ime_activated
end
def deactivate
@bridge.ime_deactivate
end
end
private_constant :DeviceIME
# Returns an instance of DeviceIME
#
# @example
#
# @driver.ime.activate engine: 'com.android.inputmethod.latin/.LatinIME'
# @driver.ime.available_engines #=> Get the list of IME installed in the target device
# @driver.ime.active_engine #=> Get the current active IME such as 'com.android.inputmethod.latin/.LatinIME'
# @driver.ime.activated #=> True if IME is activated
# @driver.ime.deactivate #=> Deactivate current IME engine
#
def ime
@device_ime ||= DeviceIME.new(@bridge) # rubocop:disable Naming/MemoizedInstanceVariableName
end
# Android only. Make an engine that is available active.
#
# @param [String] ime_name The IME owning the activity [required]
#
# @example
#
# @driver.ime_activate engine: 'com.android.inputmethod.latin/.LatinIME'
# @driver.ime.activate engine: 'com.android.inputmethod.latin/.LatinIME'
#
def ime_activate(ime_name)
ime.activate(ime_name)
end
# Android only. List all available input engines on the machine.
#
# @example
#
# @driver.ime_available_engines #=> Get the list of IME installed in the target device
# @driver.ime.available_engines #=> Get the list of IME installed in the target device
#
def ime_available_engines
ime.available_engines
end
# Android only. Get the name of the active IME engine.
#
# @example
#
# @driver.ime_active_engine #=> Get the current active IME such as 'com.android.inputmethod.latin/.LatinIME'
# @driver.ime.active_engine #=> Get the current active IME such as 'com.android.inputmethod.latin/.LatinIME'
#
def ime_active_engine
ime.active_engine
end
# @!method ime_activated
# Android only. Indicates whether IME input is active at the moment (not if it is available).
#
# @example
#
# @driver.ime_activated #=> True if IME is activated
# @driver.ime.activated #=> True if IME is activated
#
def ime_activated
ime.activated?
end
# Android only. De-activates the currently-active IME engine.
#
# @example
#
# @driver.ime_deactivate #=> Deactivate current IME engine
# @driver.ime.deactivate #=> Deactivate current IME engine
#
def ime_deactivate
ime.deactivate
end
# Perform a block within the given context, then switch back to the starting context.
# @param [String] context The context to switch to for the duration of the block.
#
# @example
#
# result = @driver.within_context('NATIVE_APP') do
# @driver.find_element :tag, "button"
# end # The result of 'find_element :tag, "button"'
#
def within_context(context)
block_given? ? @bridge.within_context(context, &Proc.new) : @bridge.within_context(context)
end
# Change to the default context. This is equivalent to +set_context nil+.
#
# @example
#
# @driver.switch_to_default_context
#
def switch_to_default_context
@bridge.switch_to_default_context
end
# @return [String] The context currently being used.
#
# @example
#
# @driver.current_context
#
def current_context
@bridge.current_context
end
# @return [Array<String>] All usable contexts, as an array of strings.
#
# @example
#
# @driver.available_contexts
#
def available_contexts
@bridge.available_contexts
end
# Change the context to the given context.
# @param [String] context The context to change to
#
# @example
#
# @driver.set_context "NATIVE_APP"
# @driver.context = "NATIVE_APP"
#
def context=(context = null)
@bridge.set_context(context)
end
alias set_context context=
# Set the value to element directly
#
# @example
#
# @driver.set_immediate_value element, 'hello'
#
def set_immediate_value(element, *value)
::Appium::Logger.warn '[DEPRECATION] driver#set_immediate_value(element, *value) is deprecated. ' \
'Use Element#immediate_value(*value) instead'
@bridge.set_immediate_value(element, *value)
end
# Replace the value to element directly
#
# @example
#
# @driver.replace_value element, 'hello'
#
def replace_value(element, *value)
::Appium::Logger.warn '[DEPRECATION] driver#replace_value(element, *value) is deprecated. ' \
'Use Element#replace_value(*value) instead'
@bridge.replace_value(element, *value)
end
# Place a file in a specific location on the device.
# On iOS, the server should have ifuse libraries installed and configured properly for this feature to work on
# real devices.
# On Android, the application under test should be built with debuggable flag enabled in order to get access to
# its container on the internal file system.
#
# {https://github.com/libimobiledevice/ifuse iFuse GitHub page6}
#
# {https://github.com/osxfuse/osxfuse/wiki/FAQ osxFuse FAQ}
#
# {https://developer.android.com/studio/debug 'Debug Your App' developer article}
#
# @param [String] path Either an absolute path OR, for iOS devices, a path relative to the app, as described.
# If the path starts with application id prefix, then the file will be pushed to the root of
# the corresponding application container.
# @param [String] filedata Raw file data to be sent to the device. Converted to base64 in the method.
#
# @example
#
# @driver.push_file "/file/to/path", "data"
#
# file = File.read "your/path/to/test_image.png"
# @driver.push_file "/sdcard/Pictures", file # Push a file binary to /sdcard/Pictures path in Android
#
def push_file(path, filedata)
@bridge.push_file(path, filedata)
end
# Pull a file from the simulator/device.
# On iOS the server should have ifuse
# libraries installed and configured properly for this feature to work on real devices.
# On Android the application under test should be built with debuggable flag enabled in order to get access
# to its container on the internal file system.
#
# {https://github.com/libimobiledevice/ifuse iFuse GitHub page6}
#
# {https://github.com/osxfuse/osxfuse/wiki/FAQ osxFuse FAQ}
#
# {https://developer.android.com/studio/debug 'Debug Your App' developer article}
#
# @param [String] path Either an absolute path OR, for iOS devices, a path relative to the app, as described.
# If the path starts with application id prefix, then the file will be pulled from the root
# of the corresponding application container.
# Otherwise the root folder is considered as / on Android and on iOS it is a media folder root
# (real devices only).
# Only pulling files from application containers is supported for iOS Simulator.
# Provide the remote path in format
# <code>@bundle.identifier:container_type/relative_path_in_container</code>
# (Make sure this in ifuse doc)
#
# @return [Base64-decoded] Base64 decoded data
#
# @example
#
# decoded_file = @driver.pull_file '/local/data/some/path' #=> Get the file at that path
# decoded_file = @driver.pull_file 'Shenanigans.app/some/file'
# #=> Get 'some/file' from the install location of Shenanigans.app
# decoded_file = @driver.pull_file '@com.appium.example/Documents/file.txt'
# #=> Get 'file.txt' in @com.appium.example/Documents
# File.open('proper_filename', 'wb') { |f| f<< decoded_file }
#
def pull_file(path)
@bridge.pull_file(path)
end
# Pull a folder content from the simulator/device.
# On iOS the server should have ifuse libraries installed and configured properly for this feature to work
# on real devices.
# On Android the application under test should be built with debuggable flag enabled in order to get access to
# its container on the internal file system.
#
# {https://github.com/libimobiledevice/ifuse iFuse GitHub page6}
#
# {https://github.com/osxfuse/osxfuse/wiki/FAQ osxFuse FAQ}
#
# {https://developer.android.com/studio/debug 'Debug Your App' developer article}
#
# @param [String] path Absolute path to the folder.
# If the path starts with <em>@applicationId/</em> prefix, then the folder will be pulled
# from the root of the corresponding application container.
# Otherwise the root folder is considered as / on Android and on iOS it is a media folder root
# (real devices only).
# Only pulling files from application containers is supported for iOS Simulator.
# Provide the remote path in format
# <code>@bundle.identifier:container_type/relative_path_in_container</code>
# (Make sure this in ifuse doc)
#
# @return [Base64-decoded] Base64 decoded data which is zip archived
#
# @example
#
# decoded_file = @driver.pull_folder '/data/local/tmp' #=> Get the folder at that path
# decoded_file = @driver.pull_file '@com.appium.example/Documents' #=> Get 'Documents' in @com.appium.example
# File.open('proper_filename', 'wb') { |f| f<< decoded_file }
#
def pull_folder(path)
@bridge.pull_folder(path)
end
# Send keyevent on the device.(Only for Selendroid)
# http://developer.android.com/reference/android/view/KeyEvent.html
# @param [integer] key The key to press.
# @param [String] metastate The state the metakeys should be in when pressing the key.
#
# @example
#
# @driver.keyevent 82
#
def keyevent(key, metastate = nil)
@bridge.keyevent(key, metastate)
end
# Press keycode on the device.
# http://developer.android.com/reference/android/view/KeyEvent.html
# @param [Integer] key The key to press. The values which have +KEYCODE_+ prefix in http://developer.android.com/reference/android/view/KeyEvent.html
# e.g.: KEYCODE_HOME is +3+ or +0x00000003+
# @param [[Integer]] metastate The state the metakeys should be in when pressing the key. Default is empty Array.
# Metastate have +META_+ prefix in https://developer.android.com/reference/android/view/KeyEvent.html
# e.g.: META_SHIFT_ON is +1+ or +0x00000001+
# @param [[Integer]] flags Native Android flag value. Several flags can be combined into a single key event.
# Default is empty Array. Can set multiple flags as Array.
# Flags have +FLAG_+ prefix in http://developer.android.com/reference/android/view/KeyEvent.html
# e.g.: FLAG_CANCELED is +32+ or +0x00000020+
#
# @example
#
# @driver.press_keycode 66
# @driver.press_keycode 66, flags: [0x02]
# @driver.press_keycode 66, metastate: [1], flags: [32]
#
def press_keycode(key, metastate: [], flags: [])
@bridge.press_keycode(key, metastate: metastate, flags: flags)
end
# Long press keycode on the device.
# http://developer.android.com/reference/android/view/KeyEvent.html
# @param [Integer] key The key to long press. The values which have +KEYCODE_+ prefix in http://developer.android.com/reference/android/view/KeyEvent.html
# e.g.: KEYCODE_HOME is +3+ or +0x00000003+
# @param [[Integer]] metastate The state the metakeys should be in when pressing the key. Default is empty Array.
# Metastate have +META_+ prefix in https://developer.android.com/reference/android/view/KeyEvent.html
# e.g.: META_SHIFT_ON is +1+ or +0x00000001+
# @param [[Integer]] flags Native Android flag value. Several flags can be combined into a single key event.
# Default is empty Array. Can set multiple flags as Array.
# Flags have +FLAG_+ prefix in http://developer.android.com/reference/android/view/KeyEvent.html
# e.g.: FLAG_CANCELED is +32+ or +0x00000020+
#
# @example
#
# @driver.long_press_keycode 66
# @driver.long_press_keycode 66, flags: [0x20, 0x2000]
# @driver.long_press_keycode 66, metastate: [1], flags: [32, 8192]
#
def long_press_keycode(key, metastate: [], flags: [])
@bridge.long_press_keycode(key, metastate: metastate, flags: flags)
end
# Start the simulator and application configured with desired capabilities
#
# @example
#
# @driver.launch_app
#
def launch_app
@bridge.launch_app
end
# Close an app on device
#
# @example
#
# @driver.close_app
#
def close_app
@bridge.close_app
end
# Reset the device, relaunching the application.
#
# @example
#
# @driver.reset
#
def reset
@bridge.reset
end
# Return the hash of all localization strings.
# @return [Hash]
#
# @example
#
# @driver.app_strings #=> "TransitionsTitle"=>"Transitions", "WebTitle"=>"Web"
#
def app_strings(language = nil)
@bridge.app_strings(language)
end
# Backgrounds the app for a set number of seconds.
# This is a blocking application
# @param [Integer] duration How many seconds to background the app for.
# @return [String]
#
# @example
#
# @driver.background_app
# @driver.background_app(5)
# @driver.background_app(-1) #=> the app never come back. https://github.com/appium/appium/issues/7741
#
def background_app(duration = 0)
@bridge.background_app(duration)
end
# Install the given app onto the device
#
# @param [String] path The absolute local path or remote http URL to an .ipa or .apk file,
# or a .zip containing one of these.
# @param [Boolean] replace Only for Android. Whether to reinstall/upgrade the package if it is already present
# on the device under test. +true+ by default
# @param [Integer] timeout Only for Android. How much time to wait for the installation to complete.
# 60000ms by default.
# @param [Boolean] allow_test_packages Only for Android. Whether to allow installation of packages marked as test
# in the manifest. +false+ by default
# @param [Boolean] use_sdcard Only for Android. Whether to use the SD card to install the app. +false+ by default
# @param [Boolean] grant_permissions Only for Android. whether to automatically grant application permissions
# on Android 6+ after the installation completes. +false+ by default
#
# @example
#
# @driver.install_app("/path/to/test.apk")
# @driver.install_app("/path/to/test.apk", replace: true, timeout: 20000, allow_test_packages: true,
# use_sdcard: false, grant_permissions: false)
#
def install_app(path,
replace: nil,
timeout: nil,
allow_test_packages: nil,
use_sdcard: nil,
grant_permissions: nil)
@bridge.install_app(path,
replace: replace,
timeout: timeout,
allow_test_packages: allow_test_packages,
use_sdcard: use_sdcard,
grant_permissions: grant_permissions)
end
# @param [Strong] app_id BundleId for iOS or package name for Android
# @param [Boolean] keep_data Only for Android. Whether to keep application data and caches after it is uninstalled.
# +false+ by default
# @param [Integer] timeout Only for Android. How much time to wait for the uninstall to complete. 20000ms by default.
#
# @example
#
# @driver.remove_app("io.appium.bundle")
# @driver.remove_app("io.appium.bundle", keep_data: false, timeout, 10000)
#
def remove_app(app_id, keep_data: nil, timeout: nil)
@bridge.remove_app(app_id, keep_data: keep_data, timeout: timeout)
end
# Check whether the specified app is installed on the device
# @return [Boolean]
#
# @example
#
# @driver.app_installed?("io.appium.bundle")
#
def app_installed?(app_id)
@bridge.app_installed?(app_id)
end
# Activate(Launch) the specified app.
# @return [Hash]
#
# @example
#
# @driver.activate_app("io.appium.bundle") #=> {}
#
def activate_app(app_id)
@bridge.activate_app(app_id)
end
# Terminate the specified app.
#
# @param [Strong] app_id BundleId for iOS or package name for Android
# @param [Integer] timeout Only for Android. How much time to wait for the application termination to complete.
# 500ms by default.
# @return [Boolean]
#
# @example
#
# @driver.terminate_app("io.appium.bundle") # true
# @driver.terminate_app("io.appium.bundle", timeout: 500)
#
def terminate_app(app_id, timeout: nil)
@bridge.terminate_app(app_id, timeout: timeout)
end
# Get the status of an existing application on the device.
# State:
# :not_installed : The current application state cannot be determined/is unknown
# :not_running : The application is not running
# :running_in_background_suspended : The application is running in the background and is suspended
# :running_in_background : The application is running in the background and is not suspended
# :running_in_foreground : The application is running in the foreground
#
# For more details: https://developer.apple.com/documentation/xctest/xcuiapplicationstate
#
# @param [String] app_id A target app's bundle id
# @return [AppState::STATUS] A number of the state
#
# @example
#
# @driver.app_state("io.appium.bundle") #=> :not_running
# # Compatibility for other clients
# @driver.query_app_state("io.appium.bundle") #=> :not_running
#
def app_state(app_id)
@bridge.app_state(app_id)
end
alias query_app_state app_state
# @param [String] remote_path The path to the remote location, where the resulting video should be uploaded.
# The following protocols are supported: http/https, ftp.
# Null or empty string value (the default setting) means the content of resulting
# file should be encoded as Base64 and passed as the endpoint response value.
# An exception will be thrown if the generated media file is too big to
# fit into the available process memory.
# @param [String] user The name of the user for the remote authentication.
# @param [String] pass The password for the remote authentication.
# @param [String] method The http multipart upload method name. The 'PUT' one is used by default.
#
# @example
#
# @driver.stop_recording_screen
# @driver.stop_recording_screen remote_path: 'https://example.com', user: 'example', pass: 'pass', method: 'POST'
#
def stop_recording_screen(remote_path: nil, user: nil, pass: nil, method: 'PUT')
@bridge.stop_recording_screen(remote_path: remote_path, user: user, pass: pass, method: method)
end
# @param [String] file_path The path to save video decoded from base64 from Appium server.
#
# @example
#
# # iOS
# @driver.start_recording_screen video_type: 'libx264'
# @driver.stop_and_save_recording_screen 'example.mp4' # Video type 'libx264' can be play as '.mp4' video
#
# # Android
# @driver.start_recording_screen
# @driver.stop_and_save_recording_screen 'example.mp4'
#
def stop_and_save_recording_screen(file_path)
@bridge.stop_and_save_recording_screen(file_path)
end
# Cause the device to shake
#
# @example
#
# @driver.shake
#
def shake
@bridge.shake
end
# Get the time on the device
#
# @param [String] format The set of format specifiers. Read https://momentjs.com/docs/ to get
# the full list of supported datetime format specifiers.
# The default format is +YYYY-MM-DDTHH:mm:ssZ+, which complies to ISO-8601
# @return [String] Formatted datetime string or the raw command output if formatting fails
#
# @example
#
# @driver.device_time #=> "2018-06-12T11:13:31+02:00"
# @driver.device_time "YYYY-MM-DD" #=> "2018-06-12"
#
def device_time(format = nil)
@bridge.device_time(format)
end
# touch actions
def touch_actions(actions)
@bridge.touch_actions(actions)
end
def multi_touch(actions)
@bridge.multi_touch(actions)
end
#
# Send multiple W3C action chains to server. Use [email protected]+ for single action chain.
#
# @param [Array] data Array of actions
# @return nil|error
#
# @example: Zoom
#
# f1 = @driver.action.add_pointer_input(:touch, 'finger1')
# f1.create_pointer_move(duration: 1, x: 200, y: 500,
# origin: ::Selenium::WebDriver::Interactions::PointerMove::VIEWPORT)
# f1.create_pointer_down(:left)
# f1.create_pointer_move(duration: 1, x: 200, y: 200,
# origin: ::Selenium::WebDriver::Interactions::PointerMove::VIEWPORT)
# f1.create_pointer_up(:left)
#
# f2 = @driver.action.add_pointer_input(:touch, 'finger2')
# f2.create_pointer_move(duration: 1, x: 200, y: 500,
# origin: ::Selenium::WebDriver::Interactions::PointerMove::VIEWPORT)
# f2.create_pointer_down(:left)
# f2.create_pointer_move(duration: 1, x: 200, y: 800,
# origin: ::Selenium::WebDriver::Interactions::PointerMove::VIEWPORT)
# f2.create_pointer_up(:left)
#
# @driver.perform_actions [f1, f2] #=> 'nil' if the action succeed
#
def perform_actions(data)
raise ArgumentError, "'#{data}' must be Array" unless data.is_a? Array
@bridge.send_actions data.map(&:encode).compact
data.each(&:clear_actions)
nil
end
# Get the device window's size.
# @return [Selenium::WebDriver::Dimension]
#
# @example
# size = @driver.window_size
# size.width #=> Integer
# size.height #=> Integer
#
def window_size
manage.window.size
end
# Get the device window's rect.
# @return [Selenium::WebDriver::Rectangle]
#
# @example
# size = @driver.window_rect
# size.width #=> Integer
# size.height #=> Integer
# size.x #=> 0
# size.y #=> 0
#
def window_rect
manage.window.rect
end
# Get the device window's size.
# @return [String]
#
# @example
# @driver.back # back to the previous view
#
def back
navigate.back
end
# Get the device window's logs.
# @return [String]
#
# @example
#
# @driver.logs.available_types # [:syslog, :crashlog, :performance]
# @driver.logs.get :syslog # []
#
def logs
@logs ||= Logs.new(@bridge)
end
# For W3C.
# Get the timeout related settings on the server side.
#
# @return [Hash]
#
# @example
# @driver.get_timeouts
#
def get_timeouts
@bridge.get_timeouts
end
# Retrieve the capabilities of the specified session.
# It's almost same as [email protected]+ but you can get more details.
#
# @return [Selenium::WebDriver::Remote::Capabilities]
#
# @example
# @driver.session_capabilities
#
# #=> uiautomator2
# # <Selenium::WebDriver::Remote::W3C::Capabilities:0x007fa38dae1360
# # @capabilities=
# # {:proxy=>nil,
# # :browser_name=>nil,
# # :browser_version=>nil,
# # :platform_name=>"android",
# # :page_load_strategy=>nil,
# # :remote_session_id=>nil,
# # :accessibility_checks=>nil,
# # :profile=>nil,
# # :rotatable=>nil,
# # :device=>nil,
# # "platform"=>"LINUX",
# # "webStorageEnabled"=>false,
# # "takesScreenshot"=>true,
# # "javascriptEnabled"=>true,
# # "databaseEnabled"=>false,
# # "networkConnectionEnabled"=>true,
# # "locationContextEnabled"=>false,
# # "warnings"=>{},
# # "desired"=>
# # {"platformName"=>"android",
# # "automationName"=>"uiautomator2",
# # "app"=>"/path/to/app/api.apk.zip",
# # "platformVersion"=>"8.1.0",
# # "deviceName"=>"Android Emulator",
# # "appPackage"=>"io.appium.android.apis",
# # "appActivity"=>"io.appium.android.apis.ApiDemos",
# # "someCapability"=>"some_capability",
# # "unicodeKeyboard"=>true,
# # "resetKeyboard"=>true},
# # "automationName"=>"uiautomator2",
# # "app"=>"/path/to/app/api.apk.zip",
# # "platformVersion"=>"8.1.0",
# # "deviceName"=>"emulator-5554",
# # "appPackage"=>"io.appium.android.apis",
# # "appActivity"=>"io.appium.android.apis.ApiDemos",
# # "someCapability"=>"some_capability",
# # "unicodeKeyboard"=>true,
# # "resetKeyboard"=>true,
# # "deviceUDID"=>"emulator-5554",
# # "deviceScreenSize"=>"1080x1920",
# # "deviceScreenDensity"=>420,
# # "deviceModel"=>"Android SDK built for x86",
# # "deviceManufacturer"=>"Google",
# # "pixelRatio"=>2.625,
# # "statBarHeight"=>63,
# # "viewportRect"=>{"left"=>0, "top"=>63, "width"=>1080, "height"=>1731}}>
# #
# #=> XCUITest
# # <Selenium::WebDriver::Remote::W3C::Capabilities:0x007fb15dc01370
# # @capabilities=
# # {:proxy=>nil,
# # :browser_name=>"UICatalog",
# # :browser_version=>nil,
# # :platform_name=>"ios",
# # :page_load_strategy=>nil,
# # :remote_session_id=>nil,
# # :accessibility_checks=>nil,
# # :profile=>nil,
# # :rotatable=>nil,
# # :device=>"iphone",
# # "udid"=>"DED4DBAD-8E5E-4AD6-BDC4-E75CF9AD84D8",
# # "automationName"=>"XCUITest",
# # "app"=>"/path/to/app/UICatalog.app",
# # "platformVersion"=>"11.4",
# # "deviceName"=>"iPhone Simulator",
# # "useNewWDA"=>true,
# # "useJSONSource"=>true,
# # "someCapability"=>"some_capability",
# # "sdkVersion"=>"11.4",
# # "CFBundleIdentifier"=>"com.example.apple-samplecode.UICatalog",
# # "pixelRatio"=>2,
# # "statBarHeight"=>23.4375,
# # "viewportRect"=>{"left"=>0, "top"=>47, "width"=>750, "height"=>1287}}>
#
def session_capabilities
@bridge.session_capabilities
end
# Returns available sessions on the Appium server
#
# @return [[Hash]]
#
# @example
#
# @driver.sessions #=> [{'id' => 'c363add8-a7ca-4455-b9e3-9ac4d69e95b3', 'capabilities' => { capabilities as Hash }}]
#
def sessions
@bridge.sessions
end
# Image Comparison
def match_images_features(first_image:,
second_image:,
detector_name: 'ORB',
match_func: 'BruteForce',
good_matches_factor: nil,
visualize: false)
@bridge.match_images_features(first_image: first_image,
second_image: second_image,
detector_name: detector_name,
match_func: match_func,
good_matches_factor: good_matches_factor,
visualize: visualize)
end
def find_image_occurrence(full_image:, partial_image:, visualize: false, threshold: nil)
@bridge.find_image_occurrence(full_image: full_image,
partial_image: partial_image,
visualize: visualize,
threshold: threshold)
end
def get_images_similarity(first_image:, second_image:, visualize: false)
@bridge.get_images_similarity(first_image: first_image, second_image: second_image, visualize: visualize)
end
def compare_images(mode: :matchFeatures, first_image:, second_image:, options: nil)
@bridge.compare_images(mode: mode, first_image: first_image, second_image: second_image, options: options)
end
# @since Appium 1.8.2
# Return an element if current view has a partial image. The logic depends on template matching by OpenCV.
# {https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/image-comparison.md image-comparison}
#
# You can handle settings for the comparision following below.
# {https://github.com/appium/appium-base-driver/blob/master/lib/basedriver/device-settings.js#L6 device-settings}
#
# @param [String] img_path A path to a partial image you'd like to find
#
# @return [::Selenium::WebDriver::Element]
#
# @example
#
# @@driver.update_settings({ fixImageFindScreenshotDims: false, fixImageTemplateSize: true,
# autoUpdateImageElementPosition: true })
# e = @@driver.find_element_by_image './test/functional/data/test_element_image.png'
#
def find_element_by_image(img_path)
template = Base64.strict_encode64 File.read img_path
find_element :image, template
end
# @since Appium 1.8.2
# Return elements if current view has a partial image. The logic depends on template matching by OpenCV.
# {https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/image-comparison.md image-comparison}
#
# You can handle settings for the comparision following below.
# {https://github.com/appium/appium-base-driver/blob/master/lib/basedriver/device-settings.js#L6 device-settings}
#
# @param [String] img_path A path to a partial image you'd like to find
#
# @return [::Selenium::WebDriver::Element]
#
# @example
#
# @@driver.update_settings({ fixImageFindScreenshotDims: false, fixImageTemplateSize: true,
# autoUpdateImageElementPosition: true })
# e = @@driver.find_elements_by_image ['./test/functional/data/test_element_image.png']
# e == [] # if the 'e' is empty
#
def find_elements_by_image(img_path)
template = Base64.strict_encode64 File.read img_path
find_elements :image, template
end
# @since Appium 1.14.0
#
# Run a set of script against the current session, allowing execution of many commands in one Appium request.
# Supports {https://webdriver.io/docs/api.html WebdriverIO} API so far.
# Please read {http://appium.io/docs/en/commands/session/execute-driver command API} for more details
# about acceptable scripts and the output.
#
# @param [String] script The string consisting of the script itself
# @param [String] type The name of the script type.
# Defaults to 'webdriverio'. Depends on server implementation which type is supported.
# @param [Integer] timeout_ms The number of +ms+ Appium should wait for the script to finish
# before killing it due to timeout.
#
# @return [Appium::Core::Base::Device::ExecuteDriver::Result] The script result parsed by
# Appium::Core::Base::Device::ExecuteDriver::Result.
#
# @raise [::Selenium::WebDriver::Error::UnknownError] If something error happens in the script.
# It has the original message.
#
# @example
# script = <<~SCRIPT
# const status = await driver.status();
# console.warn('warning message');
# return [status];
# SCRIPT
# r = @@driver.execute_driver(script: script, type: 'webdriverio', timeout: 10_000)
# r #=> An instance of Appium::Core::Base::Device::ExecuteDriver::Result
# r.result #=> The 'result' key part as the result of the script
# r.logs #=> The 'logs' key part as '{'log' => [], 'warn' => [], 'error' => []}'
#
def execute_driver(script: '', type: 'webdriverio', timeout_ms: nil)
@bridge.execute_driver(script: script, type: type, timeout_ms: timeout_ms)
end
# Convert vanilla element response to ::Selenium::WebDriver::Element
#
# @param [Hash] id The id which can get as a response from server
# @return [::Selenium::WebDriver::Element]
#
# @example
# response = {"element-6066-11e4-a52e-4f735466cecf"=>"xxxx", "ELEMENT"=>"xxxx"}
# ele = @driver.convert_to_element(response) #=> ::Selenium::WebDriver::Element
# ele.rect #=> Can get the rect of the element
#
def convert_to_element(id)
@bridge.convert_to_element id
end
end # class Driver
end # class Base
end # module Core
end # module Appium
| 41.319457 | 162 | 0.562596 |
f897fde92f93df9d7d6f5138d584c09fe8ddc785 | 213 | module BurnPlan
module InvestmentStrategy
class InvestmentStrategy
def initialize
end
def create_investments(portfolio, year)
raise NotImplementedError
end
end
end
end
| 16.384615 | 45 | 0.690141 |
39578669135ab0c707f6873348544093850c3b65 | 3,639 | # frozen_string_literal: true
module Faraday
# Base class for all Faraday adapters. Adapters are
# responsible for fulfilling a Faraday request.
class Adapter
extend MiddlewareRegistry
extend DependencyLoader
CONTENT_LENGTH = 'Content-Length'
register_middleware File.expand_path('adapter', __dir__),
test: [:Test, 'test'],
net_http_persistent: [
:NetHttpPersistent,
'net_http_persistent'
],
typhoeus: [:Typhoeus, 'typhoeus'],
patron: [:Patron, 'patron'],
em_synchrony: [:EMSynchrony, 'em_synchrony'],
em_http: [:EMHttp, 'em_http'],
excon: [:Excon, 'excon'],
rack: [:Rack, 'rack'],
httpclient: [:HTTPClient, 'httpclient']
# This module marks an Adapter as supporting parallel requests.
module Parallelism
attr_writer :supports_parallel
def supports_parallel?
@supports_parallel
end
def inherited(subclass)
super
subclass.supports_parallel = supports_parallel?
end
end
extend Parallelism
self.supports_parallel = false
def initialize(_app = nil, opts = {}, &block)
@app = ->(env) { env.response }
@connection_options = opts
@config_block = block
end
# Yields or returns an adapter's configured connection. Depends on
# #build_connection being defined on this adapter.
#
# @param env [Faraday::Env, Hash] The env object for a faraday request.
#
# @return The return value of the given block, or the HTTP connection object
# if no block is given.
def connection(env)
conn = build_connection(env)
return conn unless block_given?
yield conn
end
# Close any persistent connections. The adapter should still be usable
# after calling close.
def close
# Possible implementation:
# @app.close if @app.respond_to?(:close)
end
def call(env)
env.clear_body if env.needs_body?
env.response = Response.new
end
private
def save_response(env, status, body, headers = nil, reason_phrase = nil)
env.status = status
env.body = body
env.reason_phrase = reason_phrase&.to_s&.strip
env.response_headers = Utils::Headers.new.tap do |response_headers|
response_headers.update headers unless headers.nil?
yield(response_headers) if block_given?
end
env.response.finish(env) unless env.parallel?
env.response
end
# Fetches either a read, write, or open timeout setting. Defaults to the
# :timeout value if a more specific one is not given.
#
# @param type [Symbol] Describes which timeout setting to get: :read,
# :write, or :open.
# @param options [Hash] Hash containing Symbol keys like :timeout,
# :read_timeout, :write_timeout, :open_timeout, or
# :timeout
#
# @return [Integer, nil] Timeout duration in seconds, or nil if no timeout
# has been set.
def request_timeout(type, options)
key = TIMEOUT_KEYS.fetch(type) do
msg = "Expected :read, :write, :open. Got #{type.inspect} :("
raise ArgumentError, msg
end
options[key] || options[:timeout]
end
TIMEOUT_KEYS = {
read: :read_timeout,
open: :open_timeout,
write: :write_timeout
}.freeze
end
end
| 31.37069 | 80 | 0.595493 |
bb5e1e17bceb3a9a3af3c29412b3fed60a86c2f2 | 615 | module Capybara
module Features
def self.included(base)
base.instance_eval do
alias :background :before
alias :scenario :it
alias :xscenario :xit
alias :given :let
alias :given! :let!
alias :feature :describe
end
end
end
end
def self.feature(*args, &block)
options = if args.last.is_a?(Hash) then args.pop else {} end
options[:capybara_feature] = true
options[:type] = :feature
options[:caller] ||= caller
args.push(options)
describe(*args, &block)
end
RSpec.configuration.include Capybara::Features, :capybara_feature => true
| 21.964286 | 73 | 0.655285 |
08a6f49ea89e0a0416f3a5860e1f04f5aeee23a2 | 462 | # frozen_string_literal: true
Rails.application.routes.draw do
root to: 'entities#index'
resources :entities, only: %i[show index]
resources :variables, only: %i[show index] do
resources :scenarios, only: %i[index]
end
resources :scenarios, only: %i[show index]
resources :parameters, only: %i[show index]
# get "/:page" => "pages#show"
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
| 33 | 101 | 0.71645 |
8723c33e7d3c22b94c117de31c29794296f96060 | 4,946 | require 'puppet-strings/yard/handlers/helpers'
require 'puppet-strings/yard/handlers/ruby/base'
require 'puppet-strings/yard/code_objects'
require 'puppet-strings/yard/util'
# Implements the handler for Puppet providers written in Ruby.
class PuppetStrings::Yard::Handlers::Ruby::ProviderHandler < PuppetStrings::Yard::Handlers::Ruby::Base
namespace_only
handles method_call(:provide)
process do
return unless statement.count >= 2
# Check that provide is being called on Puppet::Type.type(<name>)
type_call = statement[0]
return unless type_call.is_a?(YARD::Parser::Ruby::MethodCallNode) && type_call.count >= 3
return unless type_call[0].source == 'Puppet::Type'
return unless type_call[2].source == 'type'
# Extract the type name
type_call_parameters = type_call.parameters(false)
return unless type_call_parameters.count >= 1
type_name = node_as_string(type_call_parameters.first)
raise YARD::Parser::UndocumentableError, "Could not determine the resource type name for the provider defined at #{statement.file}:#{statement.line}." unless type_name
# Register the object
object = PuppetStrings::Yard::CodeObjects::Provider.new(type_name, get_name(statement, "'provide'"))
register object
# Extract the docstring
register_provider_docstring object
# Populate the provider data
populate_provider_data object
# Mark the provider as public if it doesn't already have an api tag
object.add_tag YARD::Tags::Tag.new(:api, 'public') unless object.has_tag? :api
# Warn if a summary longer than 140 characters was provided
PuppetStrings::Yard::Handlers::Helpers.validate_summary_tag(object) if object.has_tag? :summary
end
private
def register_provider_docstring(object)
# Walk the tree searching for assignments or calls to desc/doc=
statement.traverse do |child|
if child.type == :assign
ivar = child.jump(:ivar)
next unless ivar != child && ivar.source == '@doc'
docstring = node_as_string(child[1])
log.error "Failed to parse docstring for Puppet provider '#{object.name}' (resource type '#{object.type_name}') near #{child.file}:#{child.line}." and return nil unless docstring
register_docstring(object, PuppetStrings::Yard::Util.scrub_string(docstring), nil)
return nil
elsif child.is_a?(YARD::Parser::Ruby::MethodCallNode)
# Look for a call to a dispatch method with a block
next unless
child.method_name &&
(child.method_name.source == 'desc' || child.method_name.source == 'doc=') &&
child.parameters(false).count == 1
docstring = node_as_string(child.parameters[0])
log.error "Failed to parse docstring for Puppet provider '#{object.name}' (resource type '#{object.type_name}') near #{child.file}:#{child.line}." and return nil unless docstring
register_docstring(object, PuppetStrings::Yard::Util.scrub_string(docstring), nil)
return nil
end
end
log.warn "Missing a description for Puppet provider '#{object.name}' (resource type '#{object.type_name}') at #{statement.file}:#{statement.line}."
end
def populate_provider_data(object)
# Traverse the block looking for confines/defaults/commands
block = statement.block
return unless block && block.count >= 2
block[1].children.each do |node|
next unless node.is_a?(YARD::Parser::Ruby::MethodCallNode) && node.method_name
method_name = node.method_name.source
parameters = node.parameters(false)
if method_name == 'confine'
# Add a confine to the object
next unless parameters.count >= 1
parameters[0].each do |kvp|
next unless kvp.count == 2
object.add_confine(node_as_string(kvp[0]) || kvp[0].source, node_as_string(kvp[1]) || kvp[1].source)
end
elsif method_name == 'has_feature' || method_name == 'has_features'
# Add the features to the object
parameters.each do |parameter|
object.add_feature(node_as_string(parameter) || parameter.source)
end
elsif method_name == 'defaultfor'
# Add a default to the object
next unless parameters.count >= 1
# Some defaultfor statements contain multiple constraints.
parameters.each do |kvps|
next unless kvps.count >= 1
defaultfor = []
kvps.each do |kvp|
defaultfor << [node_as_string(kvp[0]) || kvp[0].source, node_as_string(kvp[1]) || kvp[1].source]
end
object.add_default(defaultfor)
end
elsif method_name == 'commands'
# Add the commands to the object
next unless parameters.count >= 1
parameters[0].each do |kvp|
next unless kvp.count == 2
object.add_command(node_as_string(kvp[0]) || kvp[0].source, node_as_string(kvp[1]) || kvp[1].source)
end
end
end
end
end
| 43.008696 | 186 | 0.681156 |
1aef670d6341a84594874362433c40d0b94c3f04 | 4,325 | # Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
# stub: madowu 0.0.7 ruby lib
Gem::Specification.new do |s|
s.name = "madowu"
s.version = "0.0.7"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["ippei94da"]
s.date = "2016-07-13"
s.description = "Markdown to HTML with table of contents, sidebar to neighboring directories."
s.email = "[email protected]"
s.executables = ["dirmap", "isbninfo", "madowu", "tex2image", "urltitle"]
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".document",
"CHANGES",
"Gemfile",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"bin/dirmap",
"bin/isbninfo",
"bin/madowu",
"bin/tex2image",
"bin/urltitle",
"example/.gitignore",
"example/Rakefile",
"example/dot.aws/associateid",
"example/dot.aws/rootkey.csv",
"example/enum.md",
"example/eq.tex",
"example/heading.md",
"example/index.md",
"example/isbn.md",
"example/list.md",
"example/madowu.css",
"example/subdir/Rakefile",
"example/subdir/index.md",
"example/subdir/madowu.css",
"example/subdir/subdir2/Rakefile",
"example/subdir/subdir2/index.md",
"example/subdir/subdir2/madowu.css",
"example/template/.gitignore",
"example/template/Rakefile",
"example/template/index.md",
"example/template/madowu.css",
"example/tex2image/.gitignore",
"example/tex2image/eq.tex",
"example/urltitle/Rakefile",
"example/urltitle/index.md",
"example/urltitle/madowu.css",
"example/urltitle/url.dat",
"lib/madowu.rb",
"lib/madowu/directorymapper.rb",
"lib/madowu/htmlgenerator.rb",
"lib/madowu/isbn.rb",
"madowu.gemspec",
"test/directorymapper/.gitignore",
"test/directorymapper/dir1/foo.md",
"test/directorymapper/dir2/bar.txt",
"test/directorymapper/dir2/dir/index.md",
"test/directorymapper/dir2/foo.md",
"test/directorymapper/dir2/index.html",
"test/directorymapper/empty.md",
"test/directorymapper/file1.md",
"test/directorymapper/head.md",
"test/directorymapper/japanese/hayasu.md",
"test/directorymapper/japanese/kiito.md",
"test/directorymapper/japanese/nama.md",
"test/directorymapper/japanese/seimei.md",
"test/directorymapper/japanese/shougai.md",
"test/directorymapper/japanese/umareru.md",
"test/directorymapper/title.html",
"test/empty.md",
"test/head.md",
"test/head1.md",
"test/head_pandoc.md",
"test/helper.rb",
"test/subdir/empty.md",
"test/test.css",
"test/test_directorymapper.rb",
"test/test_htmlgenerator.rb",
"test/test_isbn.rb",
"test/test_madowu.rb"
]
s.homepage = "http://github.com/ippei94da/madowu"
s.licenses = ["MIT"]
s.rubygems_version = "2.5.1"
s.summary = "Madowu, MArkDOWn to markUp, to build html"
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_development_dependency(%q<test-unit>, ["~> 3.2"])
s.add_development_dependency(%q<rdoc>, ["~> 4.2"])
s.add_development_dependency(%q<bundler>, ["~> 1.11"])
s.add_development_dependency(%q<jeweler>, ["~> 2.0"])
s.add_development_dependency(%q<simplecov>, ["~> 0.11"])
s.add_development_dependency(%q<amazon-ecs>, ["~> 2.4"])
s.add_development_dependency(%q<tefil>, ["~> 0.1"])
else
s.add_dependency(%q<test-unit>, ["~> 3.2"])
s.add_dependency(%q<rdoc>, ["~> 4.2"])
s.add_dependency(%q<bundler>, ["~> 1.11"])
s.add_dependency(%q<jeweler>, ["~> 2.0"])
s.add_dependency(%q<simplecov>, ["~> 0.11"])
s.add_dependency(%q<amazon-ecs>, ["~> 2.4"])
s.add_dependency(%q<tefil>, ["~> 0.1"])
end
else
s.add_dependency(%q<test-unit>, ["~> 3.2"])
s.add_dependency(%q<rdoc>, ["~> 4.2"])
s.add_dependency(%q<bundler>, ["~> 1.11"])
s.add_dependency(%q<jeweler>, ["~> 2.0"])
s.add_dependency(%q<simplecov>, ["~> 0.11"])
s.add_dependency(%q<amazon-ecs>, ["~> 2.4"])
s.add_dependency(%q<tefil>, ["~> 0.1"])
end
end
| 33.015267 | 105 | 0.635607 |
f80a5e1d9be9ce9d5292d5bb4c042f29b5cf0219 | 7,579 | # knife-block - a plugin to enable the use of multiple knife configuration files
# to allow interaction with multiple knife servers in an easy and consistent manner
#
# Based on a bash script by Kristian Van Der Vliet ([email protected])
#
# Copyright (c) Matthew Macdonald-Wallace / Green and Secure IT Limited 2012
#
# Monkey patch ::Chef::Knife to give us back the config file, cause there's
# no public method to actually use the lookup logic
class Chef
class Knife
def get_config_file
# locate_config_file is only compatible with Chef 11
if GreenAndSecure.current_chef_version >= ::Gem::Version.new('12.0.0')
config[:config_file] ||= ::Chef::Knife.chef_config_dir
elsif GreenAndSecure.current_chef_version >= ::Gem::Version.new('11.8.0')
config[:config_file] ||= ::Chef::Knife.locate_config_file
elsif GreenAndSecure.current_chef_version >= ::Gem::Version.new('11.0.0')
locate_config_file
else
GreenAndSecure.locate_config_file config
end
# if we haven't created our knife.rb yet, set defaults to ~/.chef so we can create the config.
config[:config_file] ? File.dirname(config[:config_file]) : File.join(ENV['HOME'], '.chef')
end
end
end
module GreenAndSecure
@@current_chef_version = ::Gem::Version.new(::Chef::VERSION)
@@knife = ::Chef::Knife.new
def current_chef_version
@@current_chef_version
end
def chef_config_base
@@knife.get_config_file
end
# Copied from chef/knife.rb
#
# Chef 11 defines `locate_config_file` in its chef/knife.rb but Chef 10
# has this snippet of code inlined in chef/knife.rb:configure_chef.
def locate_config_file(config)
candidate_configs = []
# Look for $KNIFE_HOME/knife.rb (allow multiple knives config on same machine)
if ENV['KNIFE_HOME']
candidate_configs << File.join(ENV['KNIFE_HOME'], 'knife.rb')
end
# Look for $PWD/knife.rb
if Dir.pwd
candidate_configs << File.join(Dir.pwd, 'knife.rb')
end
# Look for $UPWARD/.chef/knife.rb
if ::Chef::Knife.chef_config_dir
candidate_configs << File.join(::Chef::Knife.chef_config_dir, 'knife.rb')
end
# Look for $HOME/.chef/knife.rb
if ENV['HOME']
candidate_configs << File.join(ENV['HOME'], '.chef', 'knife.rb')
end
candidate_configs.each do |candidate_config|
candidate_config = File.expand_path(candidate_config)
if File.exist?(candidate_config)
config[:config_file] = candidate_config
break
end
end
end
def check_block_setup
base = GreenAndSecure::chef_config_base
if File.exists?(base+"/knife.rb") then
unless File.symlink?(base+"/knife.rb")
puts "#{base}/knife.rb is NOT a symlink."
puts "Please move the file to #{base}/knife-<servername>.rb and re-run this command."
exit 3
end
end
end
def printable_server(server_config)
File.basename(server_config, ".rb").split('-')[1 .. -1].join('-')
end
# Returns path to berkshelf
def berkshelf_path
@berkshelf_path ||= ENV['BERKSHELF_PATH'] || File.expand_path('~/.berkshelf')
end
extend self
class Block < Chef::Knife
banner "knife block"
def run
GreenAndSecure::check_block_setup
list = GreenAndSecure::BlockList.new
if name_args.size == 1 and list.servers.include?(name_args[0])
use = GreenAndSecure::BlockUse.new
use.name_args = name_args
use.run
else
puts 'Did you mean to run "knife block list" instead?'
puts 'Running "knife block list" for you now'
list.run
end
end
end
class BlockList < Chef::Knife
banner "knife block list"
@current_server = nil
def current_server
GreenAndSecure::check_block_setup
@current_server ||= if File.exists?(GreenAndSecure::chef_config_base+"/knife.rb") then
GreenAndSecure::printable_server(File.readlink(GreenAndSecure::chef_config_base+"/knife.rb"))
else
nil
end
end
@servers = []
def servers
## get the list of available environments by searching ~/.chef for knife.rb files
@servers ||= Dir.glob(GreenAndSecure::chef_config_base+"/knife-*.rb").sort.map do |fn|
GreenAndSecure::printable_server(fn)
end
end
# list the available environments
def run
GreenAndSecure::check_block_setup
puts "The available chef servers are:"
servers.each do |server|
if server == current_server then
puts "\t* #{server} [ Currently Selected ]"
else
puts "\t* #{server}"
end
end
end
end
class BlockUse < Chef::Knife
banner "knife block use SERVERNAME"
def run
unless name_args.size == 1
puts "Please specify a server"
server_list = GreenAndSecure::BlockList.new
server_list.run
exit 1
end
list = GreenAndSecure::BlockList.new
new_server = name_args.first
base = GreenAndSecure::chef_config_base
if File.exists?(base+"/knife-#{new_server}.rb")
if File.exists?(base+"/knife.rb")
File.unlink(base+"/knife.rb")
end
File.symlink(base+"/knife-#{new_server}.rb", base+"/knife.rb")
puts "The knife configuration has been updated to use #{new_server}"
# update berkshelf
berks = GreenAndSecure::berkshelf_path+"/config.json"
berks_new = GreenAndSecure::berkshelf_path+"/config-#{new_server}.json"
if File.exists?(berks_new)
if File.exists?(berks)
File.unlink(berks)
end
File.symlink(berks_new, berks)
puts "The berkshelf configuration has been updated to use #{new_server}"
else
puts "Berkshelf configuration for #{new_server} not found"
end
else
puts "Knife configuration for #{new_server} not found, aborting switch"
end
end
end
class BlockNew < Chef::Knife
banner "knife block new SERVERNAME"
def run
puts "This will create a new knife configuration file for you to use with knife-block"
unless name_args.size == 1
@config_name = ui.ask_question("Please provide a friendly name for the new configuration file: ")
else
@config_name = name_args.first
end
@chef_server = ui.ask_question("Please enter the url to your Chef Server: ")
@client_name = ui.ask_question("Please enter the name of the Chef client: ")
require 'ohai'
require 'chef/knife/configure'
GreenAndSecure::check_block_setup
knife_config = Chef::Knife::Configure.new
knife_config.config[:config_file] = "#{GreenAndSecure::chef_config_base}/knife-#{@config_name}.rb"
knife_config.config[:chef_server_url] = @chef_server
knife_config.config[:node_name] = @client_name
knife_config.config[:client_key] = "#{GreenAndSecure::chef_config_base}/#{@client_name}-#{@config_name}.pem"
knife_config.run
puts "#{GreenAndSecure::chef_config_base}/knife-#{@config_name}.rb has been successfully created"
GreenAndSecure::BlockList.new.run
use = GreenAndSecure::BlockUse.new
use.name_args = [@config_name]
use.run
end
end
# Shows the currently selected knife block
class BlockShow < Chef::Knife
banner "knife block show"
def run
GreenAndSecure::check_block_setup
list = GreenAndSecure::BlockList.new
puts list.current_server
end
end
end
| 30.684211 | 121 | 0.656155 |
e2ee59a0c21b34ee355856a4124438e58545b860 | 11,424 | ##
# The Version class processes string versions into comparable
# values. A version string should normally be a series of numbers
# separated by periods. Each part (digits separated by periods) is
# considered its own number, and these are used for sorting. So for
# instance, 3.10 sorts higher than 3.2 because ten is greater than
# two.
#
# If any part contains letters (currently only a-z are supported) then
# that version is considered prerelease. Versions with a prerelease
# part in the Nth part sort less than versions with N-1
# parts. Prerelease parts are sorted alphabetically using the normal
# Ruby string sorting rules. If a prerelease part contains both
# letters and numbers, it will be broken into multiple parts to
# provide expected sort behavior (1.0.a10 becomes 1.0.a.10, and is
# greater than 1.0.a9).
#
# Prereleases sort between real releases (newest to oldest):
#
# 1. 1.0
# 2. 1.0.b1
# 3. 1.0.a.2
# 4. 0.9
#
# If you want to specify a version restriction that includes both prereleases
# and regular releases of the 1.x series this is the best way:
#
# s.add_dependency 'example', '>= 1.0.0.a', '< 2.0.0'
#
# == How Software Changes
#
# Users expect to be able to specify a version constraint that gives them
# some reasonable expectation that new versions of a library will work with
# their software if the version constraint is true, and not work with their
# software if the version constraint is false. In other words, the perfect
# system will accept all compatible versions of the library and reject all
# incompatible versions.
#
# Libraries change in 3 ways (well, more than 3, but stay focused here!).
#
# 1. The change may be an implementation detail only and have no effect on
# the client software.
# 2. The change may add new features, but do so in a way that client software
# written to an earlier version is still compatible.
# 3. The change may change the public interface of the library in such a way
# that old software is no longer compatible.
#
# Some examples are appropriate at this point. Suppose I have a Stack class
# that supports a <tt>push</tt> and a <tt>pop</tt> method.
#
# === Examples of Category 1 changes:
#
# * Switch from an array based implementation to a linked-list based
# implementation.
# * Provide an automatic (and transparent) backing store for large stacks.
#
# === Examples of Category 2 changes might be:
#
# * Add a <tt>depth</tt> method to return the current depth of the stack.
# * Add a <tt>top</tt> method that returns the current top of stack (without
# changing the stack).
# * Change <tt>push</tt> so that it returns the item pushed (previously it
# had no usable return value).
#
# === Examples of Category 3 changes might be:
#
# * Changes <tt>pop</tt> so that it no longer returns a value (you must use
# <tt>top</tt> to get the top of the stack).
# * Rename the methods to <tt>push_item</tt> and <tt>pop_item</tt>.
#
# == RubyGems Rational Versioning
#
# * Versions shall be represented by three non-negative integers, separated
# by periods (e.g. 3.1.4). The first integers is the "major" version
# number, the second integer is the "minor" version number, and the third
# integer is the "build" number.
#
# * A category 1 change (implementation detail) will increment the build
# number.
#
# * A category 2 change (backwards compatible) will increment the minor
# version number and reset the build number.
#
# * A category 3 change (incompatible) will increment the major build number
# and reset the minor and build numbers.
#
# * Any "public" release of a gem should have a different version. Normally
# that means incrementing the build number. This means a developer can
# generate builds all day long, but as soon as they make a public release,
# the version must be updated.
#
# === Examples
#
# Let's work through a project lifecycle using our Stack example from above.
#
# Version 0.0.1:: The initial Stack class is release.
# Version 0.0.2:: Switched to a linked=list implementation because it is
# cooler.
# Version 0.1.0:: Added a <tt>depth</tt> method.
# Version 1.0.0:: Added <tt>top</tt> and made <tt>pop</tt> return nil
# (<tt>pop</tt> used to return the old top item).
# Version 1.1.0:: <tt>push</tt> now returns the value pushed (it used it
# return nil).
# Version 1.1.1:: Fixed a bug in the linked list implementation.
# Version 1.1.2:: Fixed a bug introduced in the last fix.
#
# Client A needs a stack with basic push/pop capability. They write to the
# original interface (no <tt>top</tt>), so their version constraint looks like:
#
# gem 'stack', '~> 0.0'
#
# Essentially, any version is OK with Client A. An incompatible change to
# the library will cause them grief, but they are willing to take the chance
# (we call Client A optimistic).
#
# Client B is just like Client A except for two things: (1) They use the
# <tt>depth</tt> method and (2) they are worried about future
# incompatibilities, so they write their version constraint like this:
#
# gem 'stack', '~> 0.1'
#
# The <tt>depth</tt> method was introduced in version 0.1.0, so that version
# or anything later is fine, as long as the version stays below version 1.0
# where incompatibilities are introduced. We call Client B pessimistic
# because they are worried about incompatible future changes (it is OK to be
# pessimistic!).
#
# == Preventing Version Catastrophe:
#
# From: http://blog.zenspider.com/2008/10/rubygems-howto-preventing-cata.html
#
# Let's say you're depending on the fnord gem version 2.y.z. If you
# specify your dependency as ">= 2.0.0" then, you're good, right? What
# happens if fnord 3.0 comes out and it isn't backwards compatible
# with 2.y.z? Your stuff will break as a result of using ">=". The
# better route is to specify your dependency with an "approximate" version
# specifier ("~>"). They're a tad confusing, so here is how the dependency
# specifiers work:
#
# Specification From ... To (exclusive)
# ">= 3.0" 3.0 ... ∞
# "~> 3.0" 3.0 ... 4.0
# "~> 3.0.0" 3.0.0 ... 3.1
# "~> 3.5" 3.5 ... 4.0
# "~> 3.5.0" 3.5.0 ... 3.6
# "~> 3" 3.0 ... 4.0
#
# For the last example, single-digit versions are automatically extended with
# a zero to give a sensible result.
class Gem::Version
autoload :Requirement, 'rubygems/requirement'
include Comparable
VERSION_PATTERN = '[0-9]+(?>\.[0-9a-zA-Z]+)*(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?' # :nodoc:
ANCHORED_VERSION_PATTERN = /\A\s*(#{VERSION_PATTERN})?\s*\z/ # :nodoc:
##
# A string representation of this Version.
def version
@version.dup
end
alias to_s version
##
# True if the +version+ string matches RubyGems' requirements.
def self.correct? version
version.to_s =~ ANCHORED_VERSION_PATTERN
end
##
# Factory method to create a Version object. Input may be a Version
# or a String. Intended to simplify client code.
#
# ver1 = Version.create('1.3.17') # -> (Version object)
# ver2 = Version.create(ver1) # -> (ver1)
# ver3 = Version.create(nil) # -> nil
def self.create input
if self === input then # check yourself before you wreck yourself
input
elsif input.nil? then
nil
else
new input
end
end
@@all = {}
def self.new version # :nodoc:
return super unless Gem::Version == self
@@all[version] ||= super
end
##
# Constructs a Version from the +version+ string. A version string is a
# series of digits or ASCII letters separated by dots.
def initialize version
raise ArgumentError, "Malformed version number string #{version}" unless
self.class.correct?(version)
@version = version.to_s.strip.gsub("-",".pre.")
@segments = nil
end
##
# Return a new version object where the next to the last revision
# number is one greater (e.g., 5.3.1 => 5.4).
#
# Pre-release (alpha) parts, e.g, 5.3.1.b.2 => 5.4, are ignored.
def bump
@bump ||= begin
segments = self.segments.dup
segments.pop while segments.any? { |s| String === s }
segments.pop if segments.size > 1
segments[-1] = segments[-1].succ
self.class.new segments.join(".")
end
end
##
# A Version is only eql? to another version if it's specified to the
# same precision. Version "1.0" is not the same as version "1".
def eql? other
self.class === other and @version == other._version
end
def hash # :nodoc:
@version.hash
end
def init_with coder # :nodoc:
yaml_initialize coder.tag, coder.map
end
def inspect # :nodoc:
"#<#{self.class} #{version.inspect}>"
end
##
# Dump only the raw version string, not the complete object. It's a
# string for backwards (RubyGems 1.3.5 and earlier) compatibility.
def marshal_dump
[version]
end
##
# Load custom marshal format. It's a string for backwards (RubyGems
# 1.3.5 and earlier) compatibility.
def marshal_load array
initialize array[0]
end
def yaml_initialize(tag, map) # :nodoc:
@version = map['version']
@segments = nil
@hash = nil
end
def to_yaml_properties # :nodoc:
["@version"]
end
def encode_with coder # :nodoc:
coder.add 'version', @version
end
##
# A version is considered a prerelease if it contains a letter.
def prerelease?
@prerelease ||= !!(@version =~ /[a-zA-Z]/)
end
def pretty_print q # :nodoc:
q.text "Gem::Version.new(#{version.inspect})"
end
##
# The release for this version (e.g. 1.2.0.a -> 1.2.0).
# Non-prerelease versions return themselves.
def release
@release ||= if prerelease?
segments = self.segments.dup
segments.pop while segments.any? { |s| String === s }
self.class.new segments.join('.')
else
self
end
end
def segments # :nodoc:
# segments is lazy so it can pick up version values that come from
# old marshaled versions, which don't go through marshal_load.
@segments ||= @version.scan(/[0-9]+|[a-z]+/i).map do |s|
/^\d+$/ =~ s ? s.to_i : s
end
end
##
# A recommended version for use with a ~> Requirement.
def approximate_recommendation
segments = self.segments.dup
segments.pop while segments.any? { |s| String === s }
segments.pop while segments.size > 2
segments.push 0 while segments.size < 2
"~> #{segments.join(".")}"
end
##
# Compares this version with +other+ returning -1, 0, or 1 if the
# other version is larger, the same, or smaller than this
# one. Attempts to compare to something that's not a
# <tt>Gem::Version</tt> return +nil+.
def <=> other
return unless Gem::Version === other
return 0 if @version == other._version
lhsegments = segments
rhsegments = other.segments
lhsize = lhsegments.size
rhsize = rhsegments.size
limit = (lhsize > rhsize ? lhsize : rhsize) - 1
i = 0
while i <= limit
lhs, rhs = lhsegments[i] || 0, rhsegments[i] || 0
i += 1
next if lhs == rhs
return -1 if String === lhs && Numeric === rhs
return 1 if Numeric === lhs && String === rhs
return lhs <=> rhs
end
return 0
end
protected
def _version
@version
end
end
| 31.128065 | 92 | 0.660627 |
ab96b19f20b012b1e97f268b63902fb4dc485e22 | 6,170 | class Travis < Formula
desc "Command-line client for Travis CI"
homepage "https://github.com/travis-ci/travis.rb/"
url "https://github.com/travis-ci/travis.rb/archive/v1.10.0.tar.gz"
sha256 "b63991faebbd5da0e92bf1547775b69a0dbed01dd57e8b469d23a2a7bd79da43"
license "MIT"
bottle do
cellar :any
sha256 "21ab8e73b2aab1a67e6ad0cf2dfe4e0f2337b1fd743d22b134baf27354c9dd54" => :big_sur
sha256 "c27b3f49ed453047c62be6a72c9c67e495fa1ec88355d212b2919905c377114f" => :arm64_big_sur
sha256 "e6c6d41d24822636377d55de42b627fd901a6864512efbc1dab418dec752911d" => :catalina
sha256 "cdc6ac367f2c79ecce4b33d6ad0c3c5c71457db7ff818eb6de67411a2820ce52" => :mojave
sha256 "24bebab17d6e415efacc5314f4fc9c94b93b0da4c31b21069187acba83fc6be0" => :high_sierra
end
depends_on "pkg-config" => :build
depends_on "ruby"
if MacOS.version < :catalina
depends_on "libffi"
else
uses_from_macos "libffi"
end
resource "activesupport" do
url "https://rubygems.org/gems/activesupport-5.2.4.4.gem"
sha256 "8d3ddc9b86431f4e2df3c641c2f534c4c244621e57a7efa4f98e94a38198f636"
end
resource "concurrent-ruby" do
url "https://rubygems.org/gems/concurrent-ruby-1.1.7.gem"
sha256 "ff4befc88d522ccb2109596da26309f4b0b041683ca62d3cb903b313e1caddee"
end
resource "i18n" do
url "https://rubygems.org/gems/i18n-1.8.5.gem"
sha256 "f3bb7c9e89804cde8264b89f47f4746527f7293e7b5e4c74e66a9b70cfe97a94"
end
resource "minitest" do
url "https://rubygems.org/gems/minitest-5.14.2.gem"
sha256 "9b401338e287c50cd2354353b4b781d3766d863cae413b2a1bf585d237131e9c"
end
resource "tzinfo" do
url "https://rubygems.org/gems/tzinfo-1.2.7.gem"
sha256 "3945d8a57c62a59e691d527ae4daaf562d6e07a3c0d032876c6b066e108072c4"
end
resource "addressable" do
url "https://rubygems.org/gems/addressable-2.7.0.gem"
sha256 "5e9b62fe1239091ea9b2893cd00ffe1bcbdd9371f4e1d35fac595c98c5856cbb"
end
resource "public_suffix" do
url "https://rubygems.org/gems/public_suffix-4.0.6.gem"
sha256 "a99967c7b2d1d2eb00e1142e60de06a1a6471e82af574b330e9af375e87c0cf7"
end
resource "diff-lcs" do
url "https://rubygems.org/gems/diff-lcs-1.4.4.gem"
sha256 "bf3a658875f70c1467fe7a3b302b795f074c84b28db6e4a2bd6b1ad6d12a2255"
end
resource "ruby2_keywords" do
url "https://rubygems.org/gems/ruby2_keywords-0.0.2.gem"
sha256 "145c91edd2ef4c509403328ed05ae4387a8841b7a3ae93679e71c0fd3860ec9e"
end
resource "faraday" do
url "https://rubygems.org/gems/faraday-1.1.0.gem"
sha256 "6578c3ca23d2f63abf436031ca89b47ffe2c7b0d7952928ba079c75b22bfaa99"
end
resource "faraday_middleware" do
url "https://rubygems.org/gems/faraday_middleware-1.0.0.gem"
sha256 "19e808539681bbf2e65df30dfbe27bb402bde916a1dceb4c7496dbe8de14334a"
end
# required by typhoeus
resource "ffi" do
url "https://rubygems.org/gems/ffi-1.12.2.gem"
sha256 "048ad01d5369f67075f943c16f1058f10663af2a66eedb87d921316ba1828e82"
end
resource "gh" do
url "https://rubygems.org/gems/gh-0.18.0.gem"
sha256 "eb93f18a88db3ba92eb888610fc53fae731d9dacfe55922b58cc3f3aca776a47"
end
resource "highline" do
url "https://rubygems.org/gems/highline-2.0.3.gem"
sha256 "2ddd5c127d4692721486f91737307236fe005352d12a4202e26c48614f719479"
end
resource "json" do
url "https://rubygems.org/gems/json-2.3.1.gem"
sha256 "3f9ebb42fcd46ec3ecad16c89c7b174dc539bdd353610c39c15aecca1d570e95"
end
resource "json_pure" do
url "https://rubygems.org/gems/json_pure-2.3.1.gem"
sha256 "9d06adb6c324d54e9fd363a55d5cdd3ce030e26cba189d82dc6872ec268fff02"
end
# launchy v2.5.0 requires ruby > 2.4.0
resource "launchy" do
url "https://rubygems.org/gems/launchy-2.4.3.gem"
sha256 "42f52ce12c6fe079bac8a804c66522a0eefe176b845a62df829defe0e37214a4"
end
resource "multi_json" do
url "https://rubygems.org/gems/multi_json-1.15.0.gem"
sha256 "1fd04138b6e4a90017e8d1b804c039031399866ff3fbabb7822aea367c78615d"
end
resource "multipart-post" do
url "https://rubygems.org/gems/multipart-post-2.1.1.gem"
sha256 "d2dd7aa957650e0d99e0513cd388401b069f09528441b87d884609c8e94ffcfd"
end
resource "net-http-persistent" do
url "https://rubygems.org/gems/net-http-persistent-2.9.4.gem"
sha256 "24274d207ffe66222ef70c78a052c7ea6e66b4ff21e2e8a99e3335d095822ef9"
end
resource "net-http-pipeline" do
url "https://rubygems.org/gems/net-http-pipeline-1.0.1.gem"
sha256 "6923ce2f28bfde589a9f385e999395eead48ccfe4376d4a85d9a77e8c7f0b22f"
end
resource "pusher-client" do
url "https://rubygems.org/gems/pusher-client-0.6.2.gem"
sha256 "c405c931090e126c056d99f6b69a01b1bcb6cbfdde02389c93e7d547c6efd5a3"
end
resource "thread_safe" do
url "https://rubygems.org/gems/thread_safe-0.3.6.gem"
sha256 "9ed7072821b51c57e8d6b7011a8e282e25aeea3a4065eab326e43f66f063b05a"
end
resource "typhoeus" do
url "https://rubygems.org/gems/typhoeus-0.8.0.gem"
sha256 "28b7cf3c7d915a06d412bddab445df94ab725252009aa409f5ea41ab6577a30f"
end
resource "websocket" do
url "https://rubygems.org/gems/websocket-1.2.8.gem"
sha256 "1d8155c1cdaab8e8e72587a60e08423c9dd84ee44e4e827358ce3d4c2ccb2138"
end
def install
ENV["GEM_HOME"] = libexec
# gem issue on Mojave
ENV["SDKROOT"] = MacOS.sdk_path if MacOS.version == :mojave
resources.each do |r|
r.fetch
system "gem", "install", r.cached_download, "--ignore-dependencies",
"--no-document", "--install-dir", libexec
end
system "gem", "build", "travis.gemspec"
system "gem", "install", "--ignore-dependencies", "travis-#{version}.gem"
bin.install libexec/"bin/travis"
bin.env_script_all_files(libexec/"bin", GEM_HOME: ENV["GEM_HOME"])
end
test do
(testpath/".travis.yml").write <<~EOS
language: ruby
matrix:
include:
- os: osx
rvm: system
EOS
output = shell_output("#{bin}/travis lint #{testpath}/.travis.yml")
assert_match "valid", output
output = shell_output("#{bin}/travis init 2>&1", 1)
assert_match "Can't figure out GitHub repo name", output
end
end
| 33.532609 | 95 | 0.753323 |
e29c294b6d1a7cf7325a85eb99aea4525dfc48b1 | 816 | # -*- encoding: utf-8 -*-
# stub: tilt 2.0.1 ruby lib
Gem::Specification.new do |s|
s.name = "tilt"
s.version = "2.0.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Ryan Tomayko"]
s.date = "2014-03-21"
s.description = "Generic interface to multiple Ruby template engines"
s.email = "[email protected]"
s.executables = ["tilt"]
s.files = ["bin/tilt"]
s.homepage = "http://github.com/rtomayko/tilt/"
s.licenses = ["MIT"]
s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Tilt", "--main", "Tilt"]
s.rubygems_version = "2.4.5.1"
s.summary = "Generic interface to multiple Ruby template engines"
s.installed_by_version = "2.4.5.1" if s.respond_to? :installed_by_version
end
| 34 | 105 | 0.661765 |
879f1d9c84949a81a67cb0338c48218aceaf482c | 1,903 | class DropRecalls < ActiveRecord::Migration
def up
drop_table :auto_recalls
drop_table :food_recalls
drop_table :recall_details
drop_table :recalls
end
def down
create_table "recalls", :force => true do |t|
t.string "recall_number", :limit => 10
t.integer "y2k"
t.date "recalled_on"
t.datetime "created_at"
t.datetime "updated_at"
t.string "organization", :limit => 10
end
add_index "recalls", ["recall_number"], :name => "index_recalls_on_recall_number"
create_table "recall_details", :force => true do |t|
t.integer "recall_id"
t.string "detail_type"
t.string "detail_value"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "recall_details", ["recall_id"], :name => "index_recall_details_on_recall_id"
create_table "food_recalls", :force => true do |t|
t.integer "recall_id"
t.string "summary", :null => false
t.text "description", :null => false
t.string "url", :null => false
t.string "food_type", :limit => 10
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "food_recalls", ["recall_id"], :name => "index_food_recalls_on_recall_id"
create_table "auto_recalls", :force => true do |t|
t.integer "recall_id"
t.string "make", :limit => 25
t.string "model"
t.integer "year"
t.string "component_description"
t.date "manufacturing_begin_date"
t.date "manufacturing_end_date"
t.string "manufacturer", :limit => 40
t.string "recalled_component_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "auto_recalls", ["recall_id"], :name => "index_auto_recalls_on_recall_id"
end
end
| 31.716667 | 91 | 0.603258 |
6155e4bf7f96d75be6b6f992e1407df7eb60e041 | 591 | # frozen_string_literal: true
Gem::Specification.new do |spec|
spec.name = "tech-radar"
spec.version = "0.1.0"
spec.authors = ["Loic57"]
spec.email = ["[email protected]"]
spec.summary = "tech-radar !!!"
spec.homepage = "https://agilepartner.github.io/tech-radar/"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").select { |f| f.match(%r!^(assets|_layouts|_includes|_sass|LICENSE|README)!i) }
spec.add_runtime_dependency "jekyll", "~> 3.7"
spec.add_development_dependency "rake", "~> 12.0"
end
| 32.833333 | 132 | 0.610829 |
ab4a45c52c51e2fd10eb337f013e24700b7c5086 | 2,654 | # frozen_string_literal: true
require "dependabot/dependency_file"
module Dependabot
module FileUpdaters
class VendorUpdater
def initialize(repo_contents_path:, vendor_dir:)
@repo_contents_path = repo_contents_path
@vendor_dir = vendor_dir
end
# Returns changed files in the vendor/cache folder
#
# @param base_directory [String] Update config base directory
# @return [Array<Dependabot::DependencyFile>]
def updated_vendor_cache_files(base_directory:)
return [] unless repo_contents_path && vendor_dir
Dir.chdir(repo_contents_path) do
relative_dir = Pathname.new(vendor_dir).relative_path_from(
repo_contents_path
)
status = SharedHelpers.run_shell_command(
"git status --untracked-files all --porcelain v1 #{relative_dir}"
)
changed_paths = status.split("\n").map(&:split)
changed_paths.map do |type, path|
# The following types are possible to be returned:
# M = Modified = Default for DependencyFile
# D = Deleted
# ?? = Untracked = Created
operation = Dependabot::DependencyFile::Operation::UPDATE
operation = Dependabot::DependencyFile::Operation::DELETE if type == "D"
operation = Dependabot::DependencyFile::Operation::CREATE if type == "??"
encoding = ""
encoded_content = File.read(path) unless operation == Dependabot::DependencyFile::Operation::DELETE
if binary_file?(path)
encoding = Dependabot::DependencyFile::ContentEncoding::BASE64
if operation != Dependabot::DependencyFile::Operation::DELETE
encoded_content = Base64.encode64(encoded_content)
end
end
project_root =
Pathname.new(File.expand_path(File.join(Dir.pwd, base_directory)))
file_path =
Pathname.new(path).expand_path.relative_path_from(project_root)
Dependabot::DependencyFile.new(
name: file_path.to_s,
content: encoded_content,
directory: base_directory,
operation: operation,
content_encoding: encoding
)
end
end
end
private
TEXT_ENCODINGS = %w(us-ascii utf-8).freeze
attr_reader :repo_contents_path, :vendor_dir
def binary_file?(path)
return false unless File.exist?(path)
encoding = `file -b --mime-encoding #{path}`.strip
!TEXT_ENCODINGS.include?(encoding)
end
end
end
end
| 34.025641 | 111 | 0.619442 |
7a23c3aec244b2b7c3cd15d8f7462e2cba96c410 | 2,006 | require 'spec_helper'
describe 'cmake.vim#cache' do
before(:each) do
cmake.create_new_project
cmake.configure_project
end
describe '#read' do
it 'reads a known variable from the CMake cache' do
value = validate_response "echo cmake#cache#read('CMAKE_CXX_COMPILER')"
expect(value).to_not match(/:E(\d+)/)
expect(value).to match(/c++/)
end
it 'reads a internal variable from the CMake cache' do
value = validate_response "echo cmake#cache#read('CMAKE_COMMAND')"
expect(value).to_not match(/:E(\d+)/)
expect(value).to eql('/usr/bin/cmake')
end
it 'attempts to reads an non-existent variable from the CMake cache' do
value = vim.command("echo cmake#cache#read('CMAKE_MAGIC_MAKEFILE')")
expect(value).to_not match(/:E(\d+)/)
expect(value).to be_empty
end
it 'reads a custom variable from the CMake cache' do
variable_name = Faker::Internet.user_name.upcase.gsub(/(\.|_)/, '')
variable_value = Faker::Internet.user_name
cmake.configure_project(definitions: {
"#{variable_name}" => variable_value
})
value = vim.command("echo cmake#cache#read('#{variable_name}')")
expect(value).to_not be_empty
expect(value).to_not match(/:E(\d+)/)
expect(value).to eql(variable_value)
end
end
describe '#write' do
it 'writes a known variable to the CMake cache' do
vim.command "echo cmake#cache#write('CMAKE_COLOR_MAKEFILE','ON')"
result = vim.command("echo cmake#cache#read('CMAKE_COLOR_MAKEFILE')")
expect(result).to_not be_empty
expect(result).to_not match(/:E(\d+)/)
expect(result).to eql('ON')
end
it 'writes a custom variable to the CMake cache' do
vim.command "echo cmake#cache#write('CMAKE_COLOR_MAKEMOVE','Purple')"
result = validate_response "echo cmake#cache#read('CMAKE_COLOR_MAKEMOVE')"
expect(result).to eql('Purple')
end
end
end
| 34 | 80 | 0.648554 |
e28055ed4a0407250da20e203f5d334c62014327 | 1,878 | Pod::Spec.new do |s|
s.name = 'GiniVision'
s.version = '4.8.3-gym'
s.summary = 'Computer Vision Library for scanning documents.'
s.description = <<-DESC
Gini provides an information extraction system for analyzing documents (e. g. invoices or
contracts), specifically information such as the document sender or the amount to pay in an invoice.
The Gini Vision Library for iOS provides functionality to capture documents with mobile phones.
DESC
s.homepage = 'https://www.gini.net/en/developer/'
s.license = { :type => 'Private', :file => 'LICENSE' }
s.author = { 'Gini GmbH' => '[email protected]' }
s.frameworks = 'AVFoundation', 'CoreMotion', 'Photos'
s.source = { :git => 'https://github.com/gini/gini-vision-lib-ios.git', :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/gini'
s.swift_version = '4.2'
s.ios.deployment_target = '9.0'
s.default_subspec = 'Core'
s.subspec 'Core' do |core|
core.source_files = 'GiniVision/Classes/Core/**/*'
core.resources = 'GiniVision/Assets/*'
end
s.subspec 'Networking' do |networking|
networking.source_files = 'GiniVision/Classes/Networking/*.swift', 'GiniVision/Classes/Networking/Extensions/*.swift'
networking.dependency "GiniVision/Core"
networking.dependency "Gini-iOS-SDK", "~> 1.3"
networking.dependency "Bolts", "~> 1.9"
end
s.subspec 'Networking+Pinning' do |pinning|
pinning.source_files = 'GiniVision/Classes/Networking/Pinning/*'
pinning.dependency "GiniVision/Networking"
pinning.dependency "Gini-iOS-SDK/Pinning", "~> 1.3"
end
s.test_spec 'Tests' do |test_spec|
test_spec.source_files = 'GiniVision/Tests/*.swift'
test_spec.resources = 'GiniVision/Tests/Assets/*'
test_spec.requires_app_host = true
end
end
| 39.125 | 121 | 0.665602 |
b928e9879b6b85c02b5d2dd75b9c8881fa126cde | 254 | module HealthSeven::V2_7
class Aui < ::HealthSeven::DataType
# Authorization Number
attribute :authorization_number, St, position: "AUI.1"
# Date
attribute :date, Dt, position: "AUI.2"
# Source
attribute :source, St, position: "AUI.3"
end
end | 25.4 | 56 | 0.716535 |
f778769ab39aa1bbfe788b2636915101d1ce7be6 | 2,877 | # Declaração das variáveis de controle
result = ''
confirm_birth = 'n'
confirm_current_date = 'n'
loop do
# Mensagens iniciais ao usuário
puts " "
puts "Selecione uma das seguintes opções:"
puts "1 - Descobrir idade de uma pessoa"
puts "0 - Sair"
print 'Opção: '
# Entrada de dados para opção
option = gets.chomp.to_i
# Se a opção escolhida for 1, faça
if option == 1
# Enquanto a variável de controle do nascimento for diferente de 's' faça
while confirm_birth != 's'
# Pergunta dia do nascimento
print "Digite o dia de nascimento: "
day_of_birth = gets.chomp.to_i
# Pergunta mês do nascimento
print "Digite o mês de nascimento: "
month_of_birth = gets.chomp.to_i
# Pergunta ano do nascimento
print "Digite o ano de nascimento: "
year_of_birth = gets.chomp.to_i
# Verifica se os dados estão corretos
print "Confirmar #{day_of_birth}/#{month_of_birth}/#{year_of_birth} como data de nascimento? (s/n) "
# Atualiza variável de controle do nascimento
confirm_birth = gets.chomp
end
# Enquanto a variavel de controle da data atual for diferente de 's'
while confirm_current_date != 's'
# Pergunta o dia atual
print "Digite o dia atual: "
day = gets.chomp.to_i
# Pergunta o mês atual
print "Digite o mês atual: "
month = gets.chomp.to_i
# Pergunta o ano atual
print "Digite o ano atual: "
year = gets.chomp.to_i
# Verifica se os dados estão certos
print "Confirmar #{day}/#{month}/#{year} como data atual? (s/n) "
# Atualiza variável de controle da data atual
confirm_current_date = gets.chomp
end
# Idade recebe a diferença da data atual pela data de nascimento
age = year - year_of_birth
# Se ainda não tiver passado o aniversário, subtrai 1 na idade
if (month < month_of_birth) or (month == month_of_birth and day < day_of_birth)
age -= 1
end
# Exibe a idade
result = "Você tem #{age} anos"
puts result
# Se for o dia do aniversário, uma mensagem de parabéns é exibida
if (month == month_of_birth && day == day_of_birth)
puts "Parabéns! Hoje é seu aniversário!!"
end
# Se a opção escolhida for 0, o usuário encerra o loop
elsif option == 0
break
# Caso a opção não seja igual nem a 1 nem a 0, exibe 'Operação inválida'
else
result = "Opção inválida"
puts result
end
# Reinicia as variáveis de controle para o padrão
confirm_birth = 'n'
confirm_current_date = 'n'
end | 34.25 | 112 | 0.589155 |
e2357be32bec7a78a0f7b61dad126c19057227fe | 906 | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# This cop checks for space after `!`.
#
# @example
# # bad
# ! something
#
# # good
# !something
class SpaceAfterNot < Cop
include RangeHelp
MSG = 'Do not leave space between `!` and its argument.'.freeze
def on_send(node)
return unless node.keyword_bang? && whitespace_after_operator?(node)
add_offense(node)
end
def whitespace_after_operator?(node)
node.receiver.loc.column - node.loc.column > 1
end
def autocorrect(node)
lambda do |corrector|
corrector.remove(
range_between(node.loc.selector.end_pos,
node.receiver.source_range.begin_pos)
)
end
end
end
end
end
end
| 22.097561 | 78 | 0.545254 |
281f82cbdc832987d4f4b254853bc306807aeec5 | 548 | class HoshinsSweeper < ActionController::Caching::Sweeper
include Hobo::Controller::Cache
observe Hoshin
def after_create(hoshin)
if Rails.configuration.action_controller.perform_caching
##expire_swept_caches_for(hoshin)
end
end
def after_update(hoshin)
if Rails.configuration.action_controller.perform_caching
##expire_swept_caches_for(hoshin)
end
end
def after_destroy(hoshin)
if Rails.configuration.action_controller.perform_caching
##expire_swept_caches_for(hoshin)
end
end
end | 22.833333 | 60 | 0.759124 |
87c96803c3ad37513790d280b68a6253eaa72229 | 4,537 | # frozen_string_literal: true
require 'spec_helper'
describe Gitlab::Auth::RequestAuthenticator do
let(:env) do
{
'rack.input' => '',
'REQUEST_METHOD' => 'GET'
}
end
let(:request) { ActionDispatch::Request.new(env) }
subject { described_class.new(request) }
describe '#user' do
let!(:sessionless_user) { build(:user) }
let!(:session_user) { build(:user) }
it 'returns sessionless user first' do
allow_any_instance_of(described_class).to receive(:find_sessionless_user).and_return(sessionless_user)
allow_any_instance_of(described_class).to receive(:find_user_from_warden).and_return(session_user)
expect(subject.user([:api])).to eq sessionless_user
end
it 'returns session user if no sessionless user found' do
allow_any_instance_of(described_class).to receive(:find_user_from_warden).and_return(session_user)
expect(subject.user([:api])).to eq session_user
end
it 'returns nil if no user found' do
expect(subject.user([:api])).to be_blank
end
it 'bubbles up exceptions' do
allow_any_instance_of(described_class).to receive(:find_user_from_warden).and_raise(Gitlab::Auth::UnauthorizedError)
end
end
describe '#find_sessionless_user' do
let!(:access_token_user) { build(:user) }
let!(:feed_token_user) { build(:user) }
let!(:static_object_token_user) { build(:user) }
let!(:job_token_user) { build(:user) }
it 'returns access_token user first' do
allow_any_instance_of(described_class).to receive(:find_user_from_web_access_token).and_return(access_token_user)
allow_any_instance_of(described_class).to receive(:find_user_from_feed_token).and_return(feed_token_user)
expect(subject.find_sessionless_user([:api])).to eq access_token_user
end
it 'returns feed_token user if no access_token user found' do
allow_any_instance_of(described_class).to receive(:find_user_from_feed_token).and_return(feed_token_user)
expect(subject.find_sessionless_user([:api])).to eq feed_token_user
end
it 'returns static_object_token user if no feed_token user found' do
allow_any_instance_of(described_class)
.to receive(:find_user_from_static_object_token)
.and_return(static_object_token_user)
expect(subject.find_sessionless_user([:api])).to eq static_object_token_user
end
it 'returns job_token user if no static_object_token user found' do
allow_any_instance_of(described_class)
.to receive(:find_user_from_job_token)
.and_return(job_token_user)
expect(subject.find_sessionless_user([:api])).to eq job_token_user
end
it 'returns nil if no user found' do
expect(subject.find_sessionless_user([:api])).to be_blank
end
it 'rescue Gitlab::Auth::AuthenticationError exceptions' do
allow_any_instance_of(described_class).to receive(:find_user_from_web_access_token).and_raise(Gitlab::Auth::UnauthorizedError)
expect(subject.find_sessionless_user([:api])).to be_blank
end
end
describe '#find_user_from_job_token' do
let!(:user) { build(:user) }
let!(:job) { build(:ci_build, user: user) }
before do
env[Gitlab::Auth::AuthFinders::JOB_TOKEN_HEADER] = 'token'
end
context 'with API requests' do
before do
env['SCRIPT_NAME'] = '/api/endpoint'
end
it 'tries to find the user' do
expect(::Ci::Build).to receive(:find_by_token).and_return(job)
expect(subject.find_sessionless_user([:api])).to eq user
end
end
context 'without API requests' do
before do
env['SCRIPT_NAME'] = '/web/endpoint'
end
it 'does not search for job users' do
expect(::Ci::Build).not_to receive(:find_by_token)
expect(subject.find_sessionless_user([:api])).to be_nil
end
end
end
describe '#runner' do
let!(:runner) { build(:ci_runner) }
it 'returns the runner using #find_runner_from_token' do
expect_any_instance_of(described_class)
.to receive(:find_runner_from_token)
.and_return(runner)
expect(subject.runner).to eq runner
end
it 'returns nil if no runner is found' do
expect(subject.runner).to be_blank
end
it 'rescue Gitlab::Auth::AuthenticationError exceptions' do
expect_any_instance_of(described_class)
.to receive(:find_runner_from_token)
.and_raise(Gitlab::Auth::UnauthorizedError)
expect(subject.runner).to be_blank
end
end
end
| 31.289655 | 132 | 0.706855 |
e8e9450150a9a21ad21960092c268444e804311c | 479 | require 'test_helper'
class RelationshipsControllerTest < ActionDispatch::IntegrationTest
test "create should require logedin user" do
assert_no_difference 'Relationship.count' do
post relationships_path
end
assert_redirected_to login_url
end
test "destroy should require logged in user" do
assert_no_difference 'Relationship.count' do
delete relationship_path(relationships(:one))
end
assert_redirected_to login_url
end
end
| 23.95 | 67 | 0.762004 |
2804f7d441c8ab474758fb20c54346e427010722 | 5,607 | # frozen_string_literal: true
module AnyCache::Adapters
# @api private
# @since 0.3.0
class ActiveSupportDalliStore < Basic
class << self
# @param driver [Object]
# @retunr [Boolean]
#
# @api private
# @since 0.3.0
def supported_driver?(driver)
AnyCache::Drivers::ActiveSupportDalliStore.supported_source?(driver)
end
end
# @return [Array]
#
# @api private
# @since 0.3.0
READ_MULTI_EMPTY_KEYS_SET = [].freeze
# @return [Integer]
#
# @api private
# @since 0.3.0
DEFAULT_INCR_DECR_AMOUNT = 1
# @return [Integer]
#
# @api private
# @since 0.3.0
INITIAL_DECREMNETED_VALUE = 0
# @return [NilClass]
#
# @api private
# @since 0.3.0
NO_EXPIRATION_TTL = nil
# @return [Integer]
#
# @api private
# @since 0.3.0
DEAD_TTL = 0
# @since 0.3.0
def_delegators :driver, :delete, :clear, :cleanup
# @param key [String]
# @option raw [Boolean]
# @return [void]
#
# @api private
# @since 0.3.0
def read(key, **options)
raw = options.fetch(:raw, false)
driver.read(key, raw: raw)
end
# @param keys [Array<String>]
# @option raw [Boolean]
# @return [Hash]
#
# @api private
# @since 0.3.0
def read_multi(*keys, **options)
raw = options.fetch(:raw, false)
driver.read_multi(*keys, raw: raw).tap do |entries|
entries.merge!(Hash[(keys - entries.keys).zip(READ_MULTI_EMPTY_KEYS_SET)])
end
end
# @param key [String]
# @param value [Object]
# @option expires_in [NilClass, Integer] Time in seconds
# @option raw [Boolean]
# @return [void]
#
# @api private
# @since 0.3.0
def write(key, value, **options)
expires_in = options.fetch(:expires_in, NO_EXPIRATION_TTL)
raw = options.fetch(:raw, false)
driver.write(key, value, expires_in: expires_in, raw: raw)
end
# @param entries [Hash]
# @option raw [Boolean]
# @return [void]
#
# @api private
# @since 0.3.0
def write_multi(entries, **options)
raw = options.fetch(:raw, false)
# NOTE: ActiveSupport::Cache::DalliStore does not support #write_multi :\
entries.each_pair do |key, value|
write(key, value, expires_in: NO_EXPIRATION_TTL, raw: raw)
end
end
# @param key [String]
# @option expires_in [Integer]
# @option force [Boolean, Proc]
# @option raw [Boolean]
# @return [Object]
#
# @api private
# @since 0.3.0
def fetch(key, **options, &fallback)
force_rewrite = options.fetch(:force, false)
force_rewrite = force_rewrite.call(key) if force_rewrite.respond_to?(:call)
expires_in = options.fetch(:expires_in, NO_EXPIRATION_TTL)
raw = options.fetch(:raw, false)
driver.fetch(key, force: force_rewrite, expires_in: expires_in, raw: raw, &fallback)
end
# @param keys [Array<String>]
# @param options [Hash]
# @param fallback [Proc]
# @return [Hash]
#
# @api private
# @since 0.3.0
def fetch_multi(*keys, **options, &fallback)
keys.each_with_object({}) do |key, dataset|
dataset[key] = fetch(key, **options, &fallback)
end
end
# @param key [String]
# @param amount [Integer]
# @options expires_in [Integer]
# @return [Integer, Float]
#
# @api private
# @since 0.3.0
def increment(key, amount = DEFAULT_INCR_DECR_AMOUNT, **options)
expires_in = options.fetch(:expires_in, NO_EXPIRATION_TTL)
unless exist?(key)
write(key, amount, expires_in: expires_in, raw: true) && amount
else
driver.increment(key, amount).tap do
expire(key, expires_in: expires_in) if expires_in
end
end
end
# @param key [String]
# @param amount [Integer]
# @option expires_in [Integer]
# @return [Integer, Float]
#
# @api private
# @since 0.3.0
def decrement(key, amount = DEFAULT_INCR_DECR_AMOUNT, **options)
expires_in = options.fetch(:expires_in, NO_EXPIRATION_TTL)
unless exist?(key)
# NOTE: Dalli::Client (under the hood of this) can't decrement:
# - non-raw values;
# - values lower than zero;
# - empty entries;
write(key, INITIAL_DECREMNETED_VALUE, expires_in: expires_in, raw: true)
INITIAL_DECREMNETED_VALUE
else
driver.decrement(key, amount).tap do
expire(key, expires_in: expires_in) if expires_in
end
end
end
# @param pattern [String, Regexp]
# @param options [Hash]
# @return [void]
#
# @api private
# @since 0.3.0
def delete_matched(pattern, **options)
# TODO: make it real >:]
end
# @param key [String]
# @option expires_in [Integer]
# @return [void]
#
# @api private
# @since 0.3.0
def expire(key, expires_in: DEAD_TTL)
read(key, raw: true).tap do |value|
is_alive = expires_in ? expires_in.positive? : false
is_alive ? write(key, value, expires_in: expires_in, raw: true) : delete(key)
end
end
# @param key [String]
# @param options [Hash]
# @return [void]
#
# @api private
# @since 0.3.0
def persist(key, **options)
read(key).tap { |value| write(key, value) }
end
# @param key [String]
# @param options [Hash]
# @return [BOolean]
#
# @api private
# @since 0.3.0
def exist?(key, **options)
driver.exist?(key, options)
end
end
end
| 25.03125 | 90 | 0.590155 |
015b55c0bab5fca8ad8f10038d05b47baf4e5312 | 904 | module FastlyCTL
class CLI < Thor
desc "skeleton NAME", "Create a skeleton VCL file with the current boilerplate."
method_option :service, :aliases => ["--s"]
def skeleton(name="main")
id = FastlyCTL::Utils.parse_directory unless options[:service]
id ||= options[:service]
abort "Could not parse service id from directory. Use --s <service> to specify, vcl download, then try again." unless id
filename = "#{name}.vcl"
version = FastlyCTL::Fetcher.get_active_version(id)
boilerplate = FastlyCTL::Fetcher.api_request(:get, "/service/#{id}/version/#{version}/boilerplate")
if (File.exist?(filename))
say("#{filename} exists, please delete it if you want this command to overwrite it.")
abort
end
File.open(filename , 'w+') {|f| f.write(boilerplate) }
say("Boilerplate written to #{filename}.")
end
end
end
| 36.16 | 126 | 0.65708 |
ffcddf97364ff9d4410cbd9f07f5a98f11b6e8b2 | 1,370 | module Frontapp
class Client
module Tags
def tags(params = {})
list("tags", params)
end
# Parameters
# Name Type Description
# ---------------------------
# tag_id string Id of the requested tag
# ---------------------------
def get_tag(tag_id)
get("tags/#{tag_id}")
end
# Allowed attributes:
# Name Type Description
# -------------------------
# name string Name of the tag to create
# -------------------------
def create_tag!(params = {})
cleaned = params.front_permit(:name)
create("tags", cleaned)
end
# Parameters
# Name Type Description
# ---------------------------
# tag_id string Id of the requested tag
# ---------------------------
#
# Allowed params:
# Name Type Description
# ----------------------------------------------
# q object (optional) Search query.
# q.statuses array (optional) List of the statuses of the conversations you want to list
# ----------------------------------------------
def get_tag_conversations(tag_id, params = {})
cleaned = params.front_permit({ q: [:statuses] })
list("tags/#{tag_id}/conversations", cleaned)
end
end
end
end | 29.782609 | 97 | 0.434307 |
18381f2868bc42bd9e173a0dfecb8077ada61924 | 59 | Faker::UniqueGenerator.clear
Fabricate.times(100, :review)
| 19.666667 | 29 | 0.813559 |
91332085e1e4c7c0dd1f58e4929aec899c8e8a5b | 2,564 | module Pickle
module Email
# return the deliveries array, optionally selected by the passed fields
def emails(fields = nil)
@emails = ActionMailer::Base.deliveries.select {|m| email_has_fields?(m, fields)}
end
def email(ref, fields = nil)
(match = ref.match(/^#{capture_index_in_email}$/)) or raise ArgumentError, "argument should match #{match_email}"
@emails or raise RuntimeError, "Call #emails before calling #email"
index = parse_index(match[1])
email_has_fields?(@emails[index], fields) ? @emails[index] : nil
end
def email_has_fields?(email, fields)
parse_fields(fields).each do |key, val|
return false unless (Array(email.send(key)) & Array(val)).any?
end
true
end
def visit_in_email(email, link_text)
visit(parse_email_for_link(email, link_text))
end
def click_first_link_in_email(email)
link = links_in_email(email).first
visit link
end
protected
def open_in_browser(path) # :nodoc
require "launchy"
Launchy::Browser.run(path)
rescue LoadError
warn "Sorry, you need to install launchy to open emails: `gem install launchy`"
end
# Saves the emails out to RAILS_ROOT/tmp/ and opens it in the default
# web browser if on OS X. (depends on webrat)
def save_and_open_emails
emails_to_open = @emails || emails
filename = "pickle-email-#{Time.now.to_i}.html"
File.open(filename, "w") do |f|
emails_to_open.each_with_index do |e, i|
f.write "<h1>Email #{i+1}</h1><pre>#{e}</pre><hr />"
end
end
open_in_browser(filename)
end
def parse_email_for_link(email, text_or_regex)
url = parse_email_for_explicit_link(email, text_or_regex)
url ||= parse_email_for_anchor_text_link(email, text_or_regex)
raise "No link found matching #{text_or_regex.inspect} in #{email}" unless url
url
end
# e.g. confirm in http://confirm
def parse_email_for_explicit_link(email, regex)
regex = /#{Regexp.escape(regex)}/ unless regex.is_a?(Regexp)
links_in_email(email).detect { |link| link =~ regex }
end
# e.g. Click here in <a href="http://confirm">Click here</a>
def parse_email_for_anchor_text_link(email, link_text)
if match_data = email.body.match(%r{<a[^>]*href=['"]?([^'"]*)['"]?[^>]*?>[^<]*?#{link_text}[^<]*?</a>})
match_data[1]
end
end
def links_in_email(email, protos=['http', 'https'])
URI.extract(email.body.to_s, protos)
end
end
end
| 32.871795 | 119 | 0.649766 |
e2f1d52c276fa0ae80245dcc1d4d660af48e7f1e | 165 | require 'rails_helper'
describe 'authors/new.html.erb', type: :view do
before { assign(:author, build(:author_factory)) }
it_behaves_like 'renderable view'
end
| 23.571429 | 52 | 0.745455 |
03e4fdbc198a4b1a27c6e06e23aa49a69d58aab0 | 1,754 | class Id3ed < Formula
desc "ID3 tag editor for MP3 files"
homepage "http://code.fluffytapeworm.com/projects/id3ed"
url "http://code.fluffytapeworm.com/projects/id3ed/id3ed-1.10.4.tar.gz"
sha256 "56f26dfde7b6357c5ad22644c2a379f25fce82a200264b5d4ce62f2468d8431b"
license "GPL-2.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "0adb83739ee928667c488d4213369f5854900380f159219d0f04dc929ff731cc"
sha256 cellar: :any_skip_relocation, big_sur: "a560e42fb11482b14d22079ffa0ffb2dd2307f5e740b22acd2636b4fa6e4a307"
sha256 cellar: :any_skip_relocation, catalina: "9520d236327bce01cc292421934e19476163d8d72b4848740d3067cbc71b2572"
sha256 cellar: :any_skip_relocation, mojave: "2079b26fd26395f4eb016c61afafa007045d7b87b5030b05650705959c3bd87a"
sha256 cellar: :any_skip_relocation, high_sierra: "c31762b13640d1e9713ea26df41d5e9cb675a8d3565cd84b70efc526663ddfb8"
sha256 cellar: :any_skip_relocation, sierra: "e930552e37599e7926efebaf0d893f888576a26bddef6a91e356cf1b5de15b9e"
sha256 cellar: :any_skip_relocation, el_capitan: "6448c8e19c8e0874ed5141193c7db06c443ac6c33ab2f6bbe8811098b063c0d1"
sha256 cellar: :any_skip_relocation, yosemite: "8ca64da5c8c0cbbc7ec64af436fcf3a7ae457c8d8a8073887fc63ec4e89c98b9"
end
def install
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}",
"--bindir=#{bin}/",
"--mandir=#{man1}"
bin.mkpath
man1.mkpath
system "make", "install"
end
test do
system "#{bin}/id3ed", "-r", "-q", test_fixtures("test.mp3")
end
end
| 50.114286 | 122 | 0.721209 |
1af723adac7b8d81d46028ec2ad3a9acf8fef151 | 676 | # encoding: UTF-8
require 'minitest/autorun'
require 'minitest/reporters'
MiniTest::Reporters.use! MiniTest::Reporters::RubyMineReporter.new
require '../src/expert_system'
require '../src/fact_table'
require '../src/fuzzy_fact_table'
require '../src/rule'
require '../src/fuzzy_rule'
require '../src/result_value'
require '../src/explanator'
require '../src/fuzzy_explanator'
require '../src/translation_patch'
Object.translation_map = {}
$delta = 0.000001
class Mock
def initialize(method_name, block = nil )
block||=Proc.new do |*args|
args=args.first if args.length==1
yield(args)
end
self.class.send :define_method, method_name, block
end
end
| 26 | 66 | 0.724852 |
b9e9173ad94ee8667b56d9e700784baad11bd6a0 | 1,152 | def standard_dependencies
gem 'yard'
gem 'ffi'
group :development, :testing do
gem 'jruby-openssl', platforms: :jruby
gem 'json', platforms: :jruby
# Explicitly specify each rspec dependency so that we can use
# rspec-mocks-diag instead of rspec-mocks
#gem 'rspec', '~> 3.0'
gem 'rspec-core', '~> 3.0'
gem 'activesupport'
gem 'rake'
gem 'byebug', platforms: :mri
gem 'ruby-debug', platforms: :jruby
gem 'aws-sdk-core', '~> 3'
gem 'aws-sdk-cloudwatchlogs'
gem 'aws-sdk-ec2'
gem 'aws-sdk-ecs'
gem 'aws-sdk-iam'
gem 'paint'
# for benchmark tests
gem 'yajl-ruby', platforms: :mri, require: false
gem 'celluloid', platforms: :mri, require: false
end
group :testing do
gem 'timecop'
gem 'ice_nine'
gem 'rubydns', platforms: :mri
gem 'rspec-retry'
gem 'rspec-expectations', '~> 3.0'
gem 'rspec-mocks-diag', '~> 3.0'
gem 'rfc', '~> 0.1.1'
gem 'fuubar'
gem 'timeout-interrupt', platforms: :mri
gem 'concurrent-ruby', platforms: :jruby
gem 'dotenv'
end
group :development do
gem 'ruby-prof', platforms: :mri
end
end
| 24 | 65 | 0.617188 |
213c4a208ca7a17e9b7a63c3bdd499b42abe2467 | 185 | class CreateFlights < ActiveRecord::Migration[6.0]
def change
create_table :flights do |t|
t.integer :beer_id
t.integer :order_id
t.timestamps
end
end
end | 18.5 | 50 | 0.664865 |
f715607d04c45ae3be18f791a0a3f1c63d3ba7da | 1,141 | require 'spec_helper'
require 'timecop'
RSpec.describe Que::Scheduler::SchedulerJobArgs do
it 'should prepare default args' do
Timecop.freeze do
mock_db_time_now
args = described_class.build(nil)
expect(args.last_run_time).to eq(Time.zone.now)
expect(args.as_time).to eq(Time.zone.now)
expect(args.job_dictionary).to eq([])
end
end
describe 'should parse current args' do
let(:last_time) { Time.zone.now - 45.minutes }
let(:dictionary) { %w[HalfHourlyTestJob OldRemovedJob] }
def attempt_parse(options)
Timecop.freeze do
mock_db_time_now
args = described_class.build(options)
expect(args.last_run_time.iso8601).to eq(last_time.iso8601)
expect(args.as_time).to eq(Time.zone.now)
expect(args.job_dictionary).to eq(dictionary)
end
end
it 'as symbols' do
attempt_parse(
last_run_time: last_time.iso8601,
job_dictionary: dictionary
)
end
it 'as strings' do
attempt_parse(
'last_run_time' => last_time.iso8601,
'job_dictionary' => dictionary
)
end
end
end
| 25.931818 | 67 | 0.660824 |
26b516466878528ec584e8b6210c6088779ab850 | 90 | FactoryGirl.define do
factory :column do
name "MyString"
document nil
end
end
| 12.857143 | 21 | 0.7 |
38570c1513b04bf825ef760cbf7a568f8598d4d5 | 78 | class Story < ApplicationRecord
has_many :sections, dependent: :destroy
end
| 19.5 | 41 | 0.794872 |
619157e511e7ecf48fb5257db92c84f4e9461c05 | 1,415 | require 'shrine'
Shrine.plugin :activerecord
Shrine.plugin :cached_attachment_data # for forms
Shrine.plugin :upload_endpoint
Shrine.plugin :presign_endpoint
Shrine.plugin :restore_cached_data
Shrine.plugin :determine_mime_type
# On precompile, the ENV vars for AWS are not set
return if ARGV.join.include?('assets:precompile')
if Rails.env.test?
require "shrine/storage/memory"
Shrine.storages = {
cache: Shrine::Storage::Memory.new,
store: Shrine::Storage::Memory.new
}
else
require 'shrine/storage/s3'
# Allow self signed certificate (needed for Minio server)
Aws.config[:ssl_verify_peer] = ENV.fetch('AWS_SSL_VERIFY_PEER', true) != 'false'
s3_options = {
access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),
secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY'),
region: ENV.fetch('AWS_REGION'),
bucket: ENV.fetch('AWS_BUCKET'),
endpoint: ENV.fetch('AWS_ENDPOINT', 'https://s3.amazonaws.com'),
force_path_style: ENV.fetch('AWS_FORCE_PATH_STYLE', false)
}
Shrine.storages = {
cache: Shrine::Storage::S3.new(s3_options.merge(prefix: "#{Rails.env}/cache")),
store: Shrine::Storage::S3.new(s3_options.merge(prefix: "#{Rails.env}/store"))
}
end
Shrine.plugin :backgrounding
Shrine::Attacher.promote { |data| UploadPromoteJob.perform_later(data) }
Shrine::Attacher.delete { |data| UploadDeleteJob.perform_later(data) }
| 32.159091 | 83 | 0.720848 |
e98eca75dae7b7cdeaa85b13bad9f5fe34c4aeaa | 103 | module TestEngine
class TestController < ApplicationController
def index
end
end
end | 14.714286 | 46 | 0.708738 |
bf0d4cae74919134a755b56ccbb7025571f92857 | 1,803 | class Nest < Formula
desc "Neural Simulation Tool (NEST) with Python3 bindings (PyNEST)"
homepage "https://www.nest-simulator.org/"
url "https://github.com/nest/nest-simulator/archive/v3.3.tar.gz"
sha256 "179462b966cc61f5785d2fee770bc36f86745598ace9cd97dd620622b62043ed"
license "GPL-2.0-or-later"
revision 1
bottle do
root_url "https://github.com/gromgit/homebrew-core-mojave/releases/download/nest"
sha256 mojave: "aedb705bed56f9fc40f01124430ff48668d77e2659465bf6c7f749284f8118e7"
end
depends_on "cmake" => :build
depends_on "cython" => :build
depends_on "gsl"
depends_on "libtool"
depends_on "numpy"
depends_on "[email protected]"
depends_on "readline"
uses_from_macos "ncurses"
on_macos do
depends_on "libomp"
end
def install
# Help FindReadline find macOS system ncurses library
sdk = MacOS.sdk_path_if_needed
args = sdk ? ["-DNCURSES_LIBRARY=#{sdk}/usr/lib/libncurses.tbd"] : []
system "cmake", "-S", ".", "-B", "build", *std_cmake_args, *args
system "cmake", "--build", "build"
system "cmake", "--install", "build"
# Replace internally accessible gcc with externally accessible version
# in nest-config if required
inreplace bin/"nest-config", Superenv.shims_path/ENV.cxx, ENV.cxx
end
def caveats
<<~EOS
The PyNEST bindings and its dependencies are installed with the [email protected] formula.
If you want to use PyNEST, use the Python interpreter from this path:
#{Formula["[email protected]"].bin}
You may want to add this to your PATH.
EOS
end
test do
# check whether NEST was compiled & linked
system bin/"nest", "--version"
# check whether NEST is importable form python
system Formula["[email protected]"].bin/"python3.10", "-c", "'import nest'"
end
end
| 29.557377 | 89 | 0.698281 |
115401cf3d9fbad92fdcdadaa2e654e9cb964f89 | 157 | my_array = [3, 4, 8, 7, 1, 6, 5, 9, 2]
# Call the sort! method on my_array below.
# my_array should then equal [1, 2, 3, 4, 5, 6, 7, 8, 9].
my_array.sort!
| 22.428571 | 57 | 0.592357 |
1d1a3a4b5f8ca7ad0f026d291db01ab53d1e429e | 2,661 | require 'rails_helper'
RSpec.describe Admin::ArchiveController, type: :controller, admin: true do
let(:petition) do
FactoryBot.create(:completed_petition)
end
describe "not logged in" do
describe "PATCH /admin/petitions/:petition_id/archive" do
it "redirects to the login page" do
patch :update, params: { petition_id: petition.id }
expect(response).to redirect_to("https://moderate.petitions.senedd.wales/admin/login")
end
end
end
context "logged in as moderator user but need to reset password" do
let(:user) { FactoryBot.create(:moderator_user, force_password_reset: true) }
before { login_as(user) }
describe "PATCH /admin/petitions/:petition_id/archive" do
it "redirects to edit profile page" do
patch :update, params: { petition_id: petition.id }
expect(response).to redirect_to("https://moderate.petitions.senedd.wales/admin/profile/#{user.id}/edit")
end
end
end
describe "logged in as moderator user" do
let(:user) { FactoryBot.create(:moderator_user) }
before { login_as(user) }
describe "PATCH /admin/petitions/:petition_id/archive" do
it "marks the petition as archived" do
expect {
patch :update, params: { petition_id: petition.id }
}.to change {
petition.reload.archived_at
}.from(nil).to(be_within(5.seconds).of(Time.current))
end
it "redirects to the petition page" do
patch :update, params: { petition_id: petition.id }
expect(response).to redirect_to("https://moderate.petitions.senedd.wales/admin/petitions/#{petition.id}")
end
it "displays a notice" do
patch :update, params: { petition_id: petition.id }
expect(flash[:notice]).to eq("Petition has been successfully updated")
end
context "when the petition is not completed" do
let(:petition) { FactoryBot.create(:referred_petition) }
it "doesn't mark the petition as archived" do
expect {
patch :update, params: { petition_id: petition.id }
}.not_to change {
petition.reload.archived_at
}.from(nil)
end
it "redirects to the petition page" do
patch :update, params: { petition_id: petition.id }
expect(response).to redirect_to("https://moderate.petitions.senedd.wales/admin/petitions/#{petition.id}")
end
it "displays an alert" do
patch :update, params: { petition_id: petition.id }
expect(flash[:alert]).to eq("Petition could not be updated - please contact support")
end
end
end
end
end
| 35.013158 | 115 | 0.651635 |
4add9c90cccf51c29bea8226a20182ef41ef4f07 | 1,890 | # The MIT License (MIT)
# Copyright (c) 2018 Mike DeAngelo Looker Data Sciences, Inc.
# 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 'gzr/commands/look/cat'
RSpec.describe Gzr::Commands::Look::Cat do
it "executes `look cat` command successfully" do
require 'sawyer'
mock_response = double(Sawyer::Resource, { :id=>1, :title=>"foo" })
allow(mock_response).to receive(:to_attrs).and_return({ :id=>1, :title=>"foo" })
mock_sdk = Object.new
mock_sdk.define_singleton_method(:logout) { }
mock_sdk.define_singleton_method(:look) do |look_id|
return mock_response
end
output = StringIO.new
options = {}
command = Gzr::Commands::Look::Cat.new(1,options)
command.instance_variable_set(:@sdk, mock_sdk)
command.execute(output: output)
expect(output.string).to eq <<-OUT
{
"id": 1,
"title": "foo"
}
OUT
end
end
| 37.058824 | 84 | 0.734392 |
ab8d3540342293ea3b8e7daf4f27c473b6de4fa6 | 3,899 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with this
# work for additional information regarding copyright ownership. The ASF
# licenses this file to you 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 File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helpers'))
describe Buildr::Compiler::Ecj do
before(:all) do
#Make ecj appear as a compiler that applies:
class Buildr::Compiler::Ecj
class << self
def applies_to?(project, task)
paths = task.sources + [sources].flatten.map { |src| Array(project.path_to(:source, task.usage, src.to_sym)) }
paths.flatten!
ext_glob = Array(source_ext).join(',')
paths.each { |path|
Find.find(path) {|found|
if (!File.directory?(found)) && found.match(/.*\.#{Array(source_ext).join('|')}/)
return true
end
} if File.exist? path
}
false
end
end
end
end
it "should be the default Java compiler once loaded" do
write 'src/main/java/Foo.java', 'public class Foo {}'
foo = define('foo')
foo.compile.compiler.should == :ecj
end
describe "should compile a Java project just in the same way javac does" do
javac_spec = File.read(File.join(File.dirname(__FILE__), "compiler_spec.rb"))
javac_spec = javac_spec.match(Regexp.escape("require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helpers'))\n")).post_match
javac_spec.gsub!("javac", "ecj")
javac_spec.gsub!("nowarn", "warn:none")
eval(javac_spec)
end
# Redirect the java error ouput, yielding so you can do something while it is
# and returning the content of the error buffer.
#
def redirect_java_err
pending "RJB doesn't support well instantiating a class that has several constructors" unless RUBY_PLATFORM =~ /java/
err = Java.java.io.ByteArrayOutputStream.new
original_err = Java.java.lang.System.err
begin
printStream = Java.java.io.PrintStream
print = printStream.new(err)
Java.java.lang.System.setErr(print)
yield
ensure
Java.java.lang.System.setErr(original_err)
end
err.toString
end
it "should not issue warnings for type casting when warnings are set to warn:none, by default" do
write "src/main/java/Main.java", "import java.util.List; public class Main {public List get() {return null;}}"
foo = define("foo") {
compile.options.source = "1.5"
compile.options.target = "1.5"
}
redirect_java_err { foo.compile.invoke }.should_not match(/WARNING/)
end
it "should issue warnings for type casting when warnings are set" do
write "src/main/java/Main.java", "import java.util.List; public class Main {public List get() {return null;}}"
foo = define("foo") {
compile.options.source = "1.5"
compile.options.target = "1.5"
compile.options.warnings = true
}
redirect_java_err { foo.compile.invoke }.should match(/WARNING/)
end
after(:all) do
#Make ecj appear as a compiler that doesn't apply:
module Buildr
module Compiler
class Ecj
class << self
def applies_to?(project, task)
false
end
end
end
end
end
end
end
| 33.612069 | 146 | 0.660939 |
2182c12632c5b391b4cd6655da80a486d0526756 | 4,184 | #! /usr/bin/env ruby
# frozen_string_literal: true
#
# check-azurerm-route-tables-usage
#
# DESCRIPTION:
# This plugin checks the number of Route Tables allocated and available in a Region in Azure.
# Warning and Critical Percentage thresholds may be set as needed.
#
# OUTPUT:
# plain-text
#
# PLATFORMS:
# Linux
#
# DEPENDENCIES:
# gem: azure_mgmt_network
# gem: sensu-plugin
#
# USAGE:
# ./check-azurerm-route-tables-usage.rb -l "westeurope" -w 80 -c 90
#
# ./check-azurerm-route-tables-usage.rb -t "00000000-0000-0000-0000-000000000000"
# -c "00000000-0000-0000-0000-000000000000"
# -S "00000000-0000-0000-0000-000000000000"
# -s "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234"
# -l "eastus2" -w 80 -c 90
#
# ./check-azurerm-route-tables-usage.rb -tenant "00000000-0000-0000-0000-000000000000"
# -client_id "00000000-0000-0000-0000-000000000000"
# -client_secret "00000000-0000-0000-0000-000000000000"
# -subscription "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234"
# -location "westeurope"
# -warning_percentage 80
# -critical_percentage 90
#
# NOTES:
#
# LICENSE:
# Tom Harvey
# Released under the same terms as Sensu (the MIT license); see LICENSE
# for details.
#
require 'azure_mgmt_network'
require 'sensu-plugin/check/cli'
require 'sensu-plugins-azurerm'
class CheckAzureRMRouteTablesUsage < Sensu::Plugin::Check::CLI
include SensuPluginsAzureRM
option :tenant_id,
description: 'ARM Tenant ID. Either set ENV[\'ARM_TENANT_ID\'] or provide it as an option',
short: '-t ID',
long: '--tenant ID',
default: ENV['ARM_TENANT_ID'] # TODO: can we pull these out from the Check too?
option :client_id,
description: 'ARM Client ID. Either set ENV[\'ARM_CLIENT_ID\'] or provide it as an option',
short: '-c ID',
long: '--client ID',
default: ENV['ARM_CLIENT_ID']
option :client_secret,
description: 'ARM Client Secret. Either set ENV[\'ARM_CLIENT_SECRET\'] or provide it as an option',
short: '-s SECRET',
long: '--clientSecret SECRET',
default: ENV['ARM_CLIENT_SECRET']
option :subscription_id,
description: 'ARM Subscription ID',
short: '-S ID',
long: '--subscription ID',
default: ENV['ARM_SUBSCRIPTION_ID']
option :location,
description: 'Azure Location (e.g. westeurope/eastus2)',
short: '-l LOCATION',
long: '--location LOCATION'
option :warning_percentage,
description: 'Warning Percentage threshold for filter',
short: '-w PERCENTAGE',
long: '--warning PERCENTAGE'
option :critical_percentage,
description: 'Critical Percentage threshold for filter',
short: '-c PERCENTAGE',
long: '--critical PERCENTAGE'
def run
tenant_id = config[:tenant_id]
client_id = config[:client_id]
client_secret = config[:client_secret]
subscription_id = config[:subscription_id]
location = config[:location]
usage_client = NetworkUsage.new.build_usage_client(tenant_id, client_id, client_secret, subscription_id)
result = Common.new.retrieve_usage_stats(usage_client, location, 'RouteTables')
current_usage = result.current_value
allowance = result.limit
critical_percentage = config[:critical_percentage].to_f
warning_percentage = config[:warning_percentage].to_f
message = "Current usage: #{current_usage} of #{allowance} Route Tables"
percentage_used = (current_usage.to_f / allowance) * 100
if percentage_used >= critical_percentage
critical message
elsif percentage_used >= warning_percentage
warning message
else
ok message
end
rescue StandardError => e
puts "Error: exception: #{e}"
critical
end
end
| 34.01626 | 108 | 0.625478 |
eda1cafd65e46ab12223d4f3945dd4c73b4495a8 | 989 | require 'spec_helper'
describe ProjectPolicy, models: true do
let(:project) { create(:empty_project, :public) }
let(:guest) { create(:user) }
let(:reporter) { create(:user) }
let(:dev) { create(:user) }
let(:master) { create(:user) }
let(:owner) { create(:user) }
let(:admin) { create(:admin) }
let(:users_ordered_by_permissions) do
[nil, guest, reporter, dev, master, owner, admin]
end
let(:users_permissions) do
users_ordered_by_permissions.map { |u| Ability.allowed(u, project).size }
end
before do
project.team << [guest, :guest]
project.team << [master, :master]
project.team << [dev, :developer]
project.team << [reporter, :reporter]
group = create(:group)
project.project_group_links.create(
group: group,
group_access: Gitlab::Access::MASTER)
group.add_owner(owner)
end
it 'returns increasing permissions for each level' do
expect(users_permissions).to eq(users_permissions.sort.uniq)
end
end
| 26.72973 | 77 | 0.672396 |
1a8fb53b273e068fa40c98c1b9f18ad23b71eda5 | 1,641 | # 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::Storage::Mgmt::V2019_04_01
module Models
#
# Result of the request to list Storage operations. It contains a list of
# operations and a URL link to get the next set of results.
#
class OperationListResult
include MsRestAzure
# @return [Array<Operation>] List of Storage operations supported by the
# Storage resource provider.
attr_accessor :value
#
# Mapper for OperationListResult class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'OperationListResult',
type: {
name: 'Composite',
class_name: 'OperationListResult',
model_properties: {
value: {
client_side_validation: true,
required: false,
serialized_name: 'value',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'OperationElementType',
type: {
name: 'Composite',
class_name: 'Operation'
}
}
}
}
}
}
}
end
end
end
end
| 28.293103 | 78 | 0.522852 |
eda2aadd04a3746346867811b9d207ad7aa6bc9e | 208 | class CreateStaticPermissions < ActiveRecord::Migration
def change
create_table :static_permissions do |t|
t.integer :permission_type
t.integer :target
t.timestamps
end
end
end
| 18.909091 | 55 | 0.711538 |
1a11dbca9b81d33bf0cad471263cc97deb1adcd9 | 33 | module ProgressReportsHelper
end
| 11 | 28 | 0.909091 |
e8933d300d777326ec492b7338078af65b7d7d58 | 597 | # frozen_string_literal: true
class Rpush320AddApnsP8 < ActiveRecord::VERSION::MAJOR >= 5 ? ActiveRecord::Migration[5.0] : ActiveRecord::Migration
def self.up
add_column :rpush_apps, :apn_key, :string, null: true
add_column :rpush_apps, :apn_key_id, :string, null: true
add_column :rpush_apps, :team_id, :string, null: true
add_column :rpush_apps, :bundle_id, :string, null: true
end
def self.down
remove_column :rpush_apps, :apn_key
remove_column :rpush_apps, :apn_key_id
remove_column :rpush_apps, :team_id
remove_column :rpush_apps, :bundle_id
end
end
| 33.166667 | 116 | 0.735343 |
ab31830baa3e08ea455a48f800d565a869ae327a | 1,671 | namespace :report do
desc 'Output titles and work ids of possible duplicates'
task :report_duplicate_titles_and_work_ids_by_collection_id, [:collectionid, :output_file] => :environment do |t,args|
if args.count < 1
puts 'Usage: bundle exec rake report:report_duplicate_titles_and_work_ids_by_collection_id[<collectionid>[,output-file]]'
puts ' Output is written to tmp directory. If no filename is provided as the 2nd argument output is written to tmp/duplicate-titles.txt'
puts ' Format of output is workid:title. E.g.:'
puts ' abc123def:The title of my thesis.'
puts ' xyz987uvw:The title of my thesis.'
exit
end
collection_id = args[:collectionid]
begin
co = Collection.find(collection_id)
rescue ActiveFedora::ObjectNotFoundError => e
puts "Can't find collection with id: #{collection_id}"
puts "Available collections: "
puts "Id (Title)"
puts "----------"
Collection.all.each do |coll| puts "#{coll.id} (" + coll.title.first + ")" end
exit
end
if !args[:output_file].nil?
fn = 'tmp/'+args[:output_file]
else
fn = 'tmp/duplicate-titles.txt'
end
duplicate_titles = ReportDuplicateTitlesWithWorkIdsService.new(collection_id).duplicate_titles
o=File.open("#{fn}",'w')
if !duplicate_titles.nil?
duplicate_titles.each do |wid,ti|
o.puts "#{wid}: #{ti}"
end
else
puts "No duplicates found"
end
o.close if !fn.nil?
puts "wrote #{duplicate_titles.count} possible duplicate titles to #{fn}" if !duplicate_titles.nil?
end
end
| 34.8125 | 149 | 0.646918 |
91dab11fab86e066433e6fe4f7ca11565eaba0c2 | 2,075 | #! /usr/bin/env ruby
#
# metrics-curl
#
# DESCRIPTION:
# Simple wrapper around curl for getting timing stats from the various phases
# of connecting to an HTTP/HTTPS server.
#
# OUTPUT:
# metric data
#
# PLATFORMS:
# Linux
#
# DEPENDENCIES:
# gem: sensu-plugin
# gem: socket
#
# USAGE:
# #YELLOW
#
# NOTES:
# Based on: http://dev.nuclearrooster.com/2009/12/07/quick-download-benchmarks-with-curl/
# by Nick Stielau.
#
# LICENSE:
# Copyright 2012 Joe Miller
# Released under the same terms as Sensu (the MIT license); see LICENSE
# for details.
#
require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'socket'
require 'sensu-plugin/metric/cli'
class CurlMetrics < Sensu::Plugin::Metric::CLI::Graphite
option :url,
short: '-u URL',
long: '--url URL',
description: 'valid cUrl url to connect',
default: 'http://127.0.0.1:80/'
option :curl_args,
short: '-a "CURL ARGS"',
long: '--curl_args "CURL ARGS"',
description: 'Additional arguments to pass to curl',
default: ''
option :scheme,
description: 'Metric naming scheme, text to prepend to metric',
short: '-s SCHEME',
long: '--scheme SCHEME',
required: true,
default: "#{Socket.gethostname}.curl_timings"
def run
cmd = "curl --silent --output /dev/null #{config[:curl_args]} "
cmd += '-w "%{time_total},%{time_namelookup},%{time_connect},%{time_pretransfer},%{time_redirect},%{time_starttransfer}" '
cmd += config[:url]
output = `#{cmd}`
(time_total, time_namelookup, time_connect, time_pretransfer, time_redirect, time_starttransfer) = output.split(',')
output "#{config[:scheme]}.time_total", time_total
output "#{config[:scheme]}.time_namelookup", time_namelookup
output "#{config[:scheme]}.time_connect", time_connect
output "#{config[:scheme]}.time_pretransfer", time_pretransfer
output "#{config[:scheme]}.time_redirect", time_redirect
output "#{config[:scheme]}.time_starttransfer", time_starttransfer
ok
end
end
| 28.040541 | 126 | 0.653012 |
d511abb3566d1f6c82719fcfba3856d5b9d5d503 | 645 | Pod::Spec.new do |s|
s.name = "AMSlideOutController"
s.version = "1.1.1"
s.summary = "SlideOut Navigation Controller for iOS. Fully customizable."
s.homepage = "https://github.com/andreamazz/SlideOutNavigation"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "Andrea Mazzini" => "[email protected]" }
s.source = { :git => "https://github.com/andreamazz/SlideOutNavigation.git", :tag => 'v1.1.1' }
s.platform = :ios, '5.0'
s.source_files = 'AMSlideOut', '*.{h,m}'
s.resources = "AMSlideOut/*.png"
s.framework = 'QuartzCore'
s.requires_arc = true
end
| 43 | 103 | 0.604651 |
e9036c23427633dcc4e62785b8f36bb0f2564d08 | 10,080 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::Geo, :geo, :request_store do
using RSpec::Parameterized::TableSyntax
include ::EE::GeoHelpers
let_it_be(:primary_node) { create(:geo_node, :primary) }
let_it_be(:secondary_node) { create(:geo_node) }
shared_examples 'a Geo cached value' do |method, key|
it 'includes GitLab version and Rails.version in the cache key' do
expanded_key = "geo:#{key}:#{Gitlab::VERSION}:#{Rails.version}"
expect(Gitlab::ProcessMemoryCache.cache_backend).to receive(:write)
.with(expanded_key, an_instance_of(String), expires_in: 1.minute).and_call_original
expect(Rails.cache).to receive(:write)
.with(expanded_key, an_instance_of(String), expires_in: 2.minutes)
described_class.public_send(method)
end
end
describe '.current_node' do
it 'returns a GeoNode instance' do
expect(GeoNode).to receive(:current_node).and_return(primary_node)
expect(described_class.current_node).to eq(primary_node)
end
it_behaves_like 'a Geo cached value', :current_node, :current_node
end
describe '.primary_node' do
it 'returns a GeoNode primary instance' do
expect(described_class.primary_node).to eq(primary_node)
end
it_behaves_like 'a Geo cached value', :primary_node, :primary_node
end
describe '.secondary_nodes' do
it 'returns a list of Geo secondary nodes' do
expect(described_class.secondary_nodes).to match_array(secondary_node)
end
it_behaves_like 'a Geo cached value', :secondary_nodes, :secondary_nodes
end
describe '.primary?' do
context 'when current node is a primary node' do
before do
stub_current_geo_node(primary_node)
end
it 'returns true' do
expect(described_class.primary?).to be_truthy
end
it 'returns false when GeoNode is disabled' do
allow(described_class).to receive(:enabled?) { false }
expect(described_class.primary?).to be_falsey
end
end
end
describe '.primary_node_configured?' do
context 'when current node is a primary node' do
it 'returns true' do
expect(described_class.primary_node_configured?).to be_truthy
end
it 'returns false when primary does not exist' do
primary_node.destroy
expect(described_class.primary_node_configured?).to be_falsey
end
end
end
describe '.current_node_misconfigured?' do
it 'returns true when current node is not set' do
expect(described_class.current_node_misconfigured?).to be_truthy
end
it 'returns false when primary' do
stub_current_geo_node(primary_node)
expect(described_class.current_node_misconfigured?).to be_falsey
end
it 'returns false when secondary' do
stub_current_geo_node(secondary_node)
expect(described_class.current_node_misconfigured?).to be_falsey
end
it 'returns false when Geo is disabled' do
GeoNode.delete_all
expect(described_class.current_node_misconfigured?).to be_falsey
end
end
describe '.secondary?' do
context 'when current node is a secondary node' do
before do
stub_current_geo_node(secondary_node)
end
it 'returns true' do
expect(described_class.secondary?).to be_truthy
end
it 'returns false when GeoNode is disabled' do
allow(described_class).to receive(:enabled?) { false }
expect(described_class.secondary?).to be_falsey
end
end
end
describe '.enabled?' do
it_behaves_like 'a Geo cached value', :enabled?, :node_enabled
context 'when any GeoNode exists' do
it 'returns true' do
expect(described_class.enabled?).to be_truthy
end
end
context 'when no GeoNode exists' do
before do
GeoNode.delete_all
end
it 'returns false' do
expect(described_class.enabled?).to be_falsey
end
end
end
describe '.oauth_authentication' do
before do
stub_secondary_node
stub_current_geo_node(secondary_node)
end
it_behaves_like 'a Geo cached value', :oauth_authentication, :oauth_application
end
describe '.connected?' do
context 'when there is a database issue' do
it 'returns false when database connection is down' do
allow(GeoNode).to receive(:connected?) { false }
expect(described_class.connected?).to be_falsey
end
it 'returns false when the table does not exist' do
allow(GeoNode).to receive(:table_exists?) { false }
expect(described_class.connected?).to be_falsey
end
end
end
describe '.secondary?' do
context 'when current node is secondary' do
it 'returns true' do
stub_current_geo_node(secondary_node)
expect(described_class.secondary?).to be_truthy
end
end
context 'current node is primary' do
it 'returns false' do
expect(described_class.secondary?).to be_falsey
end
end
end
describe '.expire_cache!' do
it 'clears the Geo cache keys', :request_store do
described_class::CACHE_KEYS.each do |key|
content = "#{key}-content"
described_class.cache_value(key) { content }
expect(described_class.cache_value(key)).to eq(content)
end
described_class.expire_cache!
described_class::CACHE_KEYS.each do |key|
expect(described_class.cache_value(key) { nil }).to be_nil
end
end
end
describe '.expire_cache_keys!' do
it 'clears specified keys', :request_store do
cache_data = { one: 1, two: 2 }
cache_data.each do |key, value|
described_class.cache_value(key) { value }
expect(described_class.cache_value(key)).to eq(value)
end
described_class.expire_cache_keys!(cache_data.keys)
cache_data.keys.each do |key|
expect(described_class.cache_value(key) { nil }).to be_nil
end
end
end
describe '.license_allows?' do
it 'returns true if license has Geo addon' do
stub_licensed_features(geo: true)
expect(described_class.license_allows?).to be_truthy
end
it 'returns false if license doesnt have Geo addon' do
stub_licensed_features(geo: false)
expect(described_class.license_allows?).to be_falsey
end
it 'returns false if no license is present' do
allow(License).to receive(:current) { nil }
expect(described_class.license_allows?).to be_falsey
end
end
describe '.generate_access_keys' do
it 'returns a public and secret access key' do
keys = described_class.generate_access_keys
expect(keys[:access_key].length).to eq(20)
expect(keys[:secret_access_key].length).to eq(40)
end
end
describe '.configure_cron_jobs!' do
let(:manager) { double('cron_manager').as_null_object }
before do
allow(Gitlab::Geo::CronManager).to receive(:new) { manager }
end
it 'creates a cron watcher' do
expect(manager).to receive(:create_watcher!)
described_class.configure_cron_jobs!
end
it 'runs the cron manager' do
expect(manager).to receive(:execute)
described_class.configure_cron_jobs!
end
end
describe '.repository_verification_enabled?' do
context "when the feature flag hasn't been set" do
it 'returns true' do
expect(described_class.repository_verification_enabled?).to eq true
end
end
context 'when the feature flag has been set' do
context 'when the feature flag is set to enabled' do
it 'returns true' do
stub_feature_flags(geo_repository_verification: true)
expect(described_class.repository_verification_enabled?).to eq true
end
end
context 'when the feature flag is set to disabled' do
it 'returns false' do
stub_feature_flags(geo_repository_verification: false)
expect(described_class.repository_verification_enabled?).to eq false
end
end
end
end
describe '.allowed_ip?' do
where(:allowed_ips, :ip, :allowed) do
"192.1.1.1" | "192.1.1.1" | true
"192.1.1.1, 192.1.2.1" | "192.1.2.1" | true
"192.1.1.0/24" | "192.1.1.223" | true
"192.1.0.0/16" | "192.1.223.223" | true
"192.1.0.0/16, 192.1.2.0/24" | "192.1.2.223" | true
"192.1.0.0/16" | "192.2.1.1" | false
"192.1.0.1" | "192.2.1.1" | false
end
with_them do
specify do
stub_application_setting(geo_node_allowed_ips: allowed_ips)
expect(described_class.allowed_ip?(ip)).to eq(allowed)
end
end
end
describe '.proxying_to_primary_message' do
it 'returns a message as a string' do
url = 'ssh://[email protected]/namespace/repo.git'
message = <<~STR
This request to a Geo secondary node will be forwarded to the
Geo primary node:
#{url}
STR
expect(described_class.interacting_with_primary_message(url)).to eq(message)
end
end
describe '.redirecting_to_primary_message' do
it 'returns a message as a string' do
url = 'http://primary.com/namespace/repo.git'
message = <<~STR
This request to a Geo secondary node will be forwarded to the
Geo primary node:
#{url}
STR
expect(described_class.interacting_with_primary_message(url)).to eq(message)
end
end
describe '.enabled_replicator_classes' do
it 'returns an Array of replicator classes' do
result = described_class.enabled_replicator_classes
expect(result).to be_an(Array)
expect(result).to include(Geo::PackageFileReplicator)
end
context 'when replication is disabled' do
before do
stub_feature_flags(geo_package_file_replication: false)
end
it 'does not return the replicator class' do
expect(described_class.enabled_replicator_classes).not_to include(Geo::PackageFileReplicator)
end
end
end
end
| 28.156425 | 101 | 0.673313 |
abd8314be7131e02f2631679294c975ad3809521 | 132 | FactoryGirl.define do
factory :part_line_item, class: 'Spree::PartLineItem' do
line_item
variant
quantity 1
end
end
| 16.5 | 58 | 0.719697 |
e86a37f934033b0779d9ce886d301edace06b300 | 3,382 | FactoryBot.define do
factory :lesson do
lesson_name 'テスト講義'
to_create do |instance|
instance.save validate: false
end
trait :with_result do
after(:create) do |lesson|
lesson.results = []
lesson.results << FactoryBot.create(:result, lesson_id: lesson.id)
end
end
end
factory :zenkari_lesson, class: Lesson do
lesson_name '全カリ講義'
faculty_id 11
department_id 33
to_create do |instance|
instance.save validate: false
end
trait :with_result do
after(:create) do |lesson|
lesson.results = []
lesson.results << FactoryBot.create(:result, lesson_id: lesson.id)
end
end
end
factory :full_data_lesson, class: Lesson do
lesson_name 'フルデータ授業'
faculty_id 11
department_id 33
lesson_number 'CMP2500'
lesson_code '多彩5/主総A5'
professor_name '森本 正和'
term 2
period 'a_1'
classroom 'D201'
note '特になし'
campus 1
url 'https://sy.rikkyo.ac.jp/timetable/slbssbdr.do?value(risyunen)=2018&value(semekikn)=1&value(kougicd)=FE114&value(crclumcd)='
year 2018
topic_id 34
tag 259
same_lessons '12373,13083'
trait :with_lesson_detail do
after(:create) do |lesson|
lesson.lesson_detail = FactoryBot.create(:lesson_detail, lesson_id: lesson.id)
end
end
trait :with_lesson_schedules do
after(:create) do |lesson|
lesson.lesson_schedules = []
count = 1
while count < 15
lesson.lesson_schedules << FactoryBot.create(:lesson_schedule, {
number: count,
lesson_id: lesson.id
})
count += 1
end
end
end
trait :with_evaluations do
after(:create) do |lesson|
lesson.evaluations = []
percent = 20
while percent < 100
lesson.evaluations << FactoryBot.create(:evaluation, {
percent: percent,
lesson_id: lesson.id
})
percent += 80
end
end
end
trait :with_textbooks do
after(:create) do |lesson|
lesson.text_book_lessons = []
document = TextBook.first
textbook = TextBook.last
# Document
lesson.text_book_lessons << FactoryBot.create(:text_book_lesson, {
lesson_id: lesson.id,
text_book_id: document.id,
book_type: 0
})
# Textbook
lesson.text_book_lessons << FactoryBot.create(:text_book_lesson, {
lesson_id: lesson.id,
text_book_id: textbook.id,
book_type: 1
})
end
end
end
# lesson#showに必要な最低限のデータが揃っている
# same_lessonsがnilでなければ最低限のデータとなる
factory :minimum_data_lesson, class: Lesson do
same_lessons ''
after(:create) do |lesson|
lesson.lesson_detail = FactoryBot.create(:nil_lesson_detail, lesson_id: lesson.id)
lesson.evaluations = []
lesson.evaluations << FactoryBot.create(:nil_evaluation, lesson_id: lesson.id)
lesson.lesson_schedules = []
lesson.lesson_schedules << FactoryBot.create(:nil_lesson_schedule, lesson_id: lesson.id)
document = TextBook.create!
lesson.text_book_lessons = []
lesson.text_book_lessons << FactoryBot.create(:text_book_lesson, {
lesson_id: lesson.id,
text_book_id: document.id,
book_type: 0
})
end
end
end
| 26.217054 | 132 | 0.623596 |
287247e27a0c0b7a3e8ce8aeff9cc487734f4b44 | 417 | class YARD::Handlers::C::MixinHandler < YARD::Handlers::C::Base
MATCH = /rb_include_module\s*\(\s*(\w+?),\s*(\w+?)\s*\)/
handles MATCH
statement_class BodyStatement
process do
statement.source.scan(MATCH) do |klass_var, mixin_var|
namespace = namespace_for_variable(klass_var)
ensure_loaded!(namespace)
namespace.mixins(:instance) << namespace_for_variable(mixin_var)
end
end
end
| 29.785714 | 70 | 0.702638 |
08769752e3ca4a7f06345e1582d190c8dbad78e6 | 5,850 | require "rubygems"
require "thread"
require "bugsnag/version"
require "bugsnag/configuration"
require "bugsnag/meta_data"
require "bugsnag/report"
require "bugsnag/cleaner"
require "bugsnag/helpers"
require "bugsnag/session_tracker"
require "bugsnag/delivery"
require "bugsnag/delivery/synchronous"
require "bugsnag/delivery/thread_queue"
require "bugsnag/integrations/rack"
require "bugsnag/middleware/rack_request"
require "bugsnag/middleware/warden_user"
require "bugsnag/middleware/clearance_user"
require "bugsnag/middleware/callbacks"
require "bugsnag/middleware/rails3_request"
require "bugsnag/middleware/sidekiq"
require "bugsnag/middleware/mailman"
require "bugsnag/middleware/rake"
require "bugsnag/middleware/callbacks"
require "bugsnag/middleware/classify_error"
module Bugsnag
LOCK = Mutex.new
class << self
##
# Configure the Bugsnag notifier application-wide settings.
#
# Yields a configuration object to use to set application settings.
def configure
yield(configuration) if block_given?
@key_warning = false unless defined?(@key_warning)
if !configuration.valid_api_key? && !@key_warning
configuration.warn("No valid API key has been set, notifications will not be sent")
@key_warning = true
end
end
##
# Explicitly notify of an exception.
#
# Optionally accepts a block to append metadata to the yielded report.
def notify(exception, auto_notify=false, &block)
unless auto_notify.is_a? TrueClass or auto_notify.is_a? FalseClass
configuration.warn("Adding metadata/severity using a hash is no longer supported, please use block syntax instead")
auto_notify = false
end
if !configuration.auto_notify && auto_notify
configuration.debug("Not notifying because auto_notify is disabled")
return
end
if !configuration.valid_api_key?
configuration.debug("Not notifying due to an invalid api_key")
return
end
if !configuration.should_notify_release_stage?
configuration.debug("Not notifying due to notify_release_stages :#{configuration.notify_release_stages.inspect}")
return
end
if exception.respond_to?(:skip_bugsnag) && exception.skip_bugsnag
configuration.debug("Not notifying due to skip_bugsnag flag")
return
end
report = Report.new(exception, configuration, auto_notify)
# If this is an auto_notify we yield the block before the any middleware is run
yield(report) if block_given? && auto_notify
if report.ignore?
configuration.debug("Not notifying #{report.exceptions.last[:errorClass]} due to ignore being signified in auto_notify block")
return
end
# Run internal middleware
configuration.internal_middleware.run(report)
if report.ignore?
configuration.debug("Not notifying #{report.exceptions.last[:errorClass]} due to ignore being signified in internal middlewares")
return
end
# Store before_middleware severity reason for future reference
initial_severity = report.severity
initial_reason = report.severity_reason
# Run users middleware
configuration.middleware.run(report) do
if report.ignore?
configuration.debug("Not notifying #{report.exceptions.last[:errorClass]} due to ignore being signified in user provided middleware")
return
end
# If this is not an auto_notify then the block was provided by the user. This should be the last
# block that is run as it is the users "most specific" block.
yield(report) if block_given? && !auto_notify
if report.ignore?
configuration.debug("Not notifying #{report.exceptions.last[:errorClass]} due to ignore being signified in user provided block")
return
end
# Test whether severity has been changed and ensure severity_reason is consistant in auto_notify case
if report.severity != initial_severity
report.severity_reason = {
:type => Report::USER_CALLBACK_SET_SEVERITY
}
else
report.severity_reason = initial_reason
end
# Deliver
configuration.info("Notifying #{configuration.endpoint} of #{report.exceptions.last[:errorClass]}")
options = {:headers => report.headers}
payload = ::JSON.dump(Bugsnag::Helpers.trim_if_needed(report.as_json))
Bugsnag::Delivery[configuration.delivery_method].deliver(configuration.endpoint, payload, configuration, options)
end
end
##
# Returns the client's Configuration object, or creates one if not yet created.
def configuration
@configuration = nil unless defined?(@configuration)
@configuration || LOCK.synchronize { @configuration ||= Bugsnag::Configuration.new }
end
##
# Returns the client's SessionTracker object, or creates one if not yet created.
def session_tracker
@session_tracker = nil unless defined?(@session_tracker)
@session_tracker || LOCK.synchronize { @session_tracker ||= Bugsnag::SessionTracker.new}
end
##
# Starts a session.
#
# Allows Bugsnag to track error rates across releases.
def start_session
session_tracker.start_session
end
##
# Allow access to "before notify" callbacks as an array.
#
# These callbacks will be called whenever an error notification is being made.
def before_notify_callbacks
Bugsnag.configuration.request_data[:before_callbacks] ||= []
end
end
end
require "bugsnag/integrations/railtie" if defined?(Rails::Railtie)
[:resque, :sidekiq, :mailman, :delayed_job, :shoryuken, :que].each do |integration|
begin
require "bugsnag/integrations/#{integration}"
rescue LoadError
end
end
| 34.821429 | 143 | 0.708718 |
6a9b9cd95fab610b870bad976fa2eb86e04d302d | 1,081 | # frozen_string_literal: true
require_relative "test_helper"
require "httpx/plugins/proxy"
class ProxyTest < Minitest::Test
include HTTPX
def test_parameters
params = parameters(username: "user", password: "pass")
assert params == parameters(username: "user", password: "pass")
assert params != parameters(username: "user2", password: "pass")
assert params != parameters
assert params == URI.parse("http://user:pass@proxy")
assert params == "http://user:pass@proxy"
assert params != "bamalam"
assert params != 1
end
def test_parameters_authenticated
assert parameters(username: "user", password: "pass").authenticated?
assert !parameters.authenticated?
end
def test_parameters_token_authentication
params = parameters(username: "user", password: "pass")
assert params.token_authentication == Base64.strict_encode64("user:pass"),
"it should have base64-rencoded the credentials"
end
private
def parameters(uri: "http://proxy", **args)
Plugins::Proxy::Parameters.new(uri: uri, **args)
end
end
| 29.216216 | 78 | 0.707678 |
bfbbf3b485c9deb8fdc91ab4a105c8054dd17012 | 1,244 | class I2p < Formula
desc "Anonymous overlay network - a network within a network"
homepage "https://geti2p.net"
url "https://download.i2p2.de/releases/0.9.50/i2pinstall_0.9.50.jar"
mirror "https://launchpad.net/i2p/trunk/0.9.50/+download/i2pinstall_0.9.50.jar"
sha256 "34902d2a7e678fda9261d489ab315661bd2915b9d0d81165acdee008d9031430"
livecheck do
url "https://geti2p.net/en/download"
regex(/href=.*?i2pinstall[._-]v?(\d+(?:\.\d+)+)\.jar/i)
end
bottle :unneeded
depends_on "openjdk@11"
def install
(buildpath/"path.conf").write "INSTALL_PATH=#{libexec}"
system "#{Formula["openjdk@11"].opt_bin}/java", "-jar", "i2pinstall_#{version}.jar",
"-options", "path.conf", "-language", "eng"
wrapper_name = "i2psvc-macosx-universal-64"
libexec.install_symlink libexec/wrapper_name => "i2psvc"
(bin/"eepget").write_env_script libexec/"eepget", JAVA_HOME: Formula["openjdk@11"].opt_prefix
(bin/"i2prouter").write_env_script libexec/"i2prouter", JAVA_HOME: Formula["openjdk@11"].opt_prefix
man1.install Dir["#{libexec}/man/*"]
end
test do
assert_match "I2P Service is not running.", shell_output("#{bin}/i2prouter status", 1)
end
end
| 36.588235 | 103 | 0.676849 |
39de5d0e2c2c92975d37193b82108c2590c24a76 | 535 | Pod::Spec.new do |s|
s.name = 'DAKeyboardControl'
s.version = '0.0.1'
s.platform = :ios
s.license = 'MIT'
s.summary = 'Easily add keyboard awareness and scrolling dismissal.'
s.homepage = 'https://github.com/danielamitay/DAKeyboardControl'
s.author = { 'Daniel Amitay' => '[email protected]' }
s.source = { :git => 'https://github.com/danielamitay/DAKeyboardControl.git', :commit => '31b3687a3aa1c36b3754e54ea7687d36b9e89084' }
s.source_files = 'DAKeyboardControl/*.{h,m}'
s.requires_arc = true
end
| 41.153846 | 137 | 0.68972 |
f7ab6f14e2c9ec4ceeacfd1011c2d83a13b05d8c | 278 | class RecipeSerializer
include JSONAPI::Serializer
attributes :name, :ingredients, :instructions, :image_url, :user_id, :created_at, :updated_at, :comments
belongs_to :user, serializer: UserSerializer
# has_many :comments
# has_many :users, through: :comments
end
| 30.888889 | 106 | 0.758993 |
18a1a3552825a63be03e04a751ab39492191e948 | 732 | Pod::Spec.new do |s|
s.name = "HPLChatViewController"
s.version = "0.0.2"
s.summary = "HPLChatViewController is for making sms like views on iOS. It is a fork of https://github.com/AlexBarinov/UIBubbleTableView."
s.homepage = "https://github.com/huffpostlabs/HPLChatViewController"
s.license = { :type => 'Creative Commons Attribution-ShareAlike 3.0 Unported', :file => 'LICENSE' }
s.author = { "Matthew Conlen" => "[email protected]" }
s.source = { :git => "https://github.com/huffpostlabs/HPLChatViewController.git", :tag => "0.0.2" }
s.platform = :ios, '4.0'
s.source_files = 'Classes', 'Classes/**/*.{h,m}'
s.resources = "Images", "Images/**/*.png"
end
| 36.6 | 145 | 0.625683 |
f8ac5d8e443b279e21acd0a998ae2f34e1101ee3 | 211 | require "application_system_test_case"
class ObjectivesTest < ApplicationSystemTestCase
# test "visiting the index" do
# visit objectives_url
#
# assert_selector "h1", text: "Objective"
# end
end
| 21.1 | 48 | 0.739336 |
288c4657088eaf257d8c21beafb340c2bfb4c754 | 657 | class SaltController < ApplicationController
# http_basic_authenticate_with name: "preview", password: "", only: :render_html
before_action :authenticate_full_site_password, only: [:render_html]
def render_html
if Rails.env.development? && request.fullpath =~ /.html$/
render plain: "Template not found: #{request.fullpath}", status: :not_found
return
end
if request.path =~ /^\/teams\/([^\/]+)$/
@team = Team.find_by(slug: $1, accepts_public_payins: true)
@support_offering = @team.support_offering || @team.build_support_offering if @team
end
render "layouts/salt.html.erb", layout: false
end
end
| 29.863636 | 89 | 0.694064 |
ac5a3142ab438d654dc5ce1a618254aa47f87faa | 810 | cask 'origin' do
version '10.5.30.15625'
sha256 'd679a1635957edcc677b4f00f9a6d3fb236b1af8d401306999085b3e1c8cfeab'
# origin-a.akamaihd.net was verified as official when first introduced to the cask
url 'https://origin-a.akamaihd.net/Origin-Client-Download/origin/mac/live/Origin.dmg'
appcast 'https://api1.origin.com/autopatch/2/upgradeFrom/10.5.24.5022/en_US/PROD?platform=MAC&osVersion=10.13.0'
name 'Origin'
homepage 'https://www.origin.com/'
app 'Origin.app'
zap trash: [
'~/Library/Application Support/Origin',
'~/Library/Saved Application State/com.ea.Origin.savedState',
'~/Library/LaunchAgents/com.ea.origin.WebHelper.plist',
'~/Library/Caches/com.ea.Origin',
'~/Library/Caches/Origin',
]
end
| 38.571429 | 114 | 0.676543 |
915f51461c8eb77e475fc95132f7745f2bcb20cc | 139 | require 'test_helper'
class WhatContactsControllerTest < ActionController::TestCase
# test "the truth" do
# assert true
# end
end
| 17.375 | 61 | 0.741007 |
b9bf9ae1caffafa96d7f159529c61c9d2279e3d7 | 638 | module Rao
module Api
module ResourcesController::DestroyAllActionConcern
extend ActiveSupport::Concern
included do
if respond_to?(:before_action)
before_action :load_and_destroy_collection, only: [:destroy_all]
else
before_filter :load_and_destroy_collection, only: [:destroy_all]
end
end
def destroy_all
respond_to do |format|
format.json { render json: serialize_collection(@collection) }
end
end
private
def load_and_destroy_collection
@collection = resource_class.destroy_all
end
end
end
end | 23.62963 | 74 | 0.65674 |
e9226d2e1891ffa42f7667eba6256074b0a0ef22 | 682 | # frozen_string_literal: true
module Userable
extend ActiveSupport::Concern
included do
def remove_users(id: nil, jwt: nil)
result = Maremma.get user_url
Array.wrap(result.body["data"]).each do |user|
url = ENV["VOLPINO_URL"] + "/users/" + user.fetch("id")
data = {
"data" => { "attributes" => { id => nil }, "type" => "users" },
}
result =
Maremma.patch(
url,
content_type: "application/vnd.api+json",
accept: "application/vnd.api+json",
bearer: jwt,
data: data.to_json,
)
logger.info result.inspect
end
end
end
end
| 24.357143 | 73 | 0.532258 |
797f8589365b74c4f1a9cbb15c2da03721ac0ccc | 1,110 | require_relative 'alerty/version'
require_relative 'alerty/error'
require_relative 'alerty/config'
require_relative 'alerty/command'
require_relative 'alerty/logger'
require_relative 'alerty/cli'
require_relative 'alerty/string_util'
require_relative 'alerty/plugin_factory'
class Alerty
def self.logger
@logger ||= Logger.new(Config.log_path, Config.log_shift_age, Config.log_shift_size).tap do |logger|
logger.level = Config.log_level
end
end
# @param [Hash] record
# @option record [String] :hostname
# @option record [String] :command
# @option record [Integer] :exitstatus
# @option record [String] :output
# @option record [Float] :started_at unix timestamp
# @option record [Float] :duration
# @option record [Integer] :retries number of being retried
def self.send(record)
PluginFactory.plugins.each do |plugin|
begin
plugin.alert(record)
rescue => e
puts "#{e.class} #{e.message} #{e.backtrace.join("\n")}" if Config.debug?
Alerty.logger.warn "#{e.class} #{e.message} #{e.backtrace.join("\n")}"
end
end
end
end
| 30.833333 | 104 | 0.703604 |
bb98eca3d96f0ac7bdf90d161e87906a7346337e | 780 | # This has to be a separate type to enable collecting
Puppet::Type.newtype(:database_user) do
@doc = "Manage a database user. This includes management of users password as well as priveleges"
ensurable
newparam(:name, :namevar=>true) do
desc "The name of the user. This uses the 'username@hostname' or username@hostname."
validate do |value|
raise(ArgumentError, "Invalid database user #{value}") unless value =~ /\w+@[\w%]+/
username = value.split('@')[0]
if username.size > 16
raise ArgumentError, "MySQL usernames are limited to a maximum of 16 characters"
end
end
end
newproperty(:password_hash) do
desc "The password hash of the user. Use mysql_password() for creating such a hash."
newvalue(/\w+/)
end
end
| 32.5 | 99 | 0.687179 |
33ee49eba6048b12f443d9afc1e8ca33ba4ba7bb | 395 | class YearsController < ApplicationController
get '/years' do
if Year.all.empty?
Scraper.year_scraper
end
erb :'years/index'
end
get '/years/:year' do
@year = Year.find_by(:value => params[:year])
#SHOULD REFACTOR BELOW
if @year.shows.empty?
@year.scrape_shows
end
erb :'years/show'
end
end | 18.809524 | 49 | 0.55443 |
39d35df2def558a6bc171c859056d6734f14e566 | 1,419 | module Support
class InteractionsController < ApplicationController
before_action :safe_interaction, only: :new
def index; end
def show
@interaction = InteractionPresenter.new(current_case.interactions.find(params[:id]))
end
def new
@interaction = InteractionPresenter.new(current_case.interactions.build)
@back_url = support_case_path(current_case)
render :new, locals: { option: safe_interaction }
end
def create
@interaction = InteractionPresenter.new(Interaction.new(interaction_params))
if @interaction.save
record_action(case_id: @interaction.case.id, action: "add_interaction", data: { event_type: @interaction.event_type })
redirect_to support_case_path(@interaction.case),
notice: I18n.t("support.interaction.message.created_flash", type: @interaction.event_type).humanize
else
render :new, locals: { option: safe_interaction }
end
end
private
def interaction_params
params.require(:interaction).permit(:event_type, :body).merge(agent_id: current_agent.id, case: current_case)
end
def safe_interaction
@option = Support::Interaction::SAFE_INTERACTIONS.find { |opt| opt == params[:option].to_s } ||
redirect_to(support_case_path(current_case))
end
def current_case
@current_case || Case.find(params[:case_id])
end
end
end
| 31.533333 | 126 | 0.701903 |
4a0cc73e654988449faa1be59a3993062971a353 | 581 | include SnipeIT::API
class Status
def initialize(url, token, status_label)
@status_label = status_label
endpoint = Endpoint.new(url, token, 'statuslabels', search: status_label)
@status = Get.new(endpoint)
end
class DoesNotExistError < StandardError
end
def current_value
if @status.response['rows'].empty?
raise Status::DoesNotExistError, "#{@status_label} status does not exist in the database!"
else
@status.response['rows'].first
end
end
def name
current_value['name']
end
def id
current_value['id']
end
end
| 20.034483 | 96 | 0.690189 |
1109181bb5d5df471c5d460d104b6d364b95ef7a | 730 | class SorceryActivityLogging < ActiveRecord::Migration
def self.up
add_column :accounts, :last_login_at, :datetime, :default => nil
add_column :accounts, :last_logout_at, :datetime, :default => nil
add_column :accounts, :last_activity_at, :datetime, :default => nil
add_column :accounts, :last_login_from_ip_address, :string, :default => nil
add_index :accounts, [:last_logout_at, :last_activity_at]
end
def self.down
remove_index :accounts, [:last_logout_at, :last_activity_at]
remove_column :accounts, :last_login_from_ip_address
remove_column :accounts, :last_activity_at
remove_column :accounts, :last_logout_at
remove_column :accounts, :last_login_at
end
end | 38.421053 | 79 | 0.736986 |
4a6aa9dd5cc56494b83e06d14795256eeb625641 | 207 | class User < ActiveRecord::Base
has_secure_password
has_many :villagers
validates :name, presence: true
validates :password_digest, presence: true
validates :email, uniqueness: true
end | 25.875 | 46 | 0.73913 |
26496ec9764f26a938e915e5bf4c2c16194e7556 | 806 | # encoding: UTF-8
require_relative 'spec_helper'
describe 'openstack-compute::api-os-compute' do
describe 'redhat' do
let(:runner) { ChefSpec::Runner.new(REDHAT_OPTS) }
let(:node) { runner.node }
let(:chef_run) { runner.converge(described_recipe) }
include_context 'compute_stubs'
include_examples 'expect_runs_nova_common_recipe'
include_examples 'expect_creates_nova_state_dir'
include_examples 'expect_creates_nova_lock_dir'
it 'upgrades openstack api packages' do
expect(chef_run).to upgrade_package 'openstack-nova-api'
end
it 'starts openstack api on boot' do
expect(chef_run).to enable_service 'openstack-nova-api'
end
it 'starts openstack api now' do
expect(chef_run).to start_service 'openstack-nova-api'
end
end
end
| 27.793103 | 62 | 0.730769 |
38d58d69e7db2b4164a8f1d343ae245a011025f2 | 974 | # DRUNKWATER TEMPLATE(add description and prototypes)
# Question Title and Description on leetcode.com
# Function Declaration and Function Prototypes on leetcode.com
#108. Convert Sorted Array to Binary Search Tree
#Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
#For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
#Example:
#Given the sorted array: [-10,-3,0,5,9],
#One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
# 0
# / \
# -3 9
# / /
# -10 5
## Definition for a binary tree node.
## class TreeNode
## attr_accessor :val, :left, :right
## def initialize(val)
## @val = val
## @left, @right = nil, nil
## end
## end
## @param {Integer[]} nums
## @return {TreeNode}
#def sorted_array_to_bst(nums)
#end
# Time Is Money | 32.466667 | 158 | 0.688912 |
39eb81a72729b75436e325c504ed20985180cc48 | 205 | class AddFieldsToUser < ActiveRecord::Migration
def change
add_column :users, :name, :string
add_column :users, :perm_admin, :boolean
add_column :users, :perm_create_talk, :boolean
end
end
| 25.625 | 50 | 0.736585 |
f87d811ec8971acd13f20a0e0027910e3d5fc511 | 1,619 | # app/models/registration.rb
# Model for events registrations
class Registration < ActiveRecord::Base
# extends ...................................................................
# includes ..................................................................
# security (i.e. attr_accessible) ...........................................
# relationships .............................................................
belongs_to :event
belongs_to :user, foreign_key: "user_id"
before_validation :code_certified
validates_uniqueness_of :certified_code
# validations ...............................................................
# callbacks .................................................................
# scopes ....................................................................
# additional config .........................................................
# class methods .............................................................
def self.is_registrated?(user_id)
return true if self.where(user_id: user_id).count >= 1
false
end
def self.to_register(user_id)
self.create(user_id: user_id)
end
def code_certified
while true do
code = SecureRandom.hex[0..7]
register = Registration.where(' certified_code = ? ', code).first
break if register.nil?
end
self.certified_code = code
end
# public instance methods ...................................................
# protected instance methods ................................................
# private instance methods ..................................................
end
| 36.795455 | 79 | 0.399629 |
e97a28effb2dc70032565f578c83d1980aeec5fa | 1,812 | require 'spec_helper'
require 'rack/test'
require 'bosh/director/api/controllers/errands_controller'
module Bosh::Director
describe Api::Controllers::ErrandsController do
include Rack::Test::Methods
subject(:app) { described_class } # "app" is a Rack::Test hook
before { Api::ResourceManager.stub(:new) }
describe 'POST', '/deployments/:deployment_name/errands/:name/runs' do
before { Config.base_dir = 'base_dir' }
def perform
post(
'/deployments/fake-dep-name/errands/fake-errand-name/runs',
JSON.dump({}),
{ 'CONTENT_TYPE' => 'application/json' },
)
end
context 'authenticated access' do
before { authorize 'admin', 'admin' }
it 'enqueues a RunErrand task' do
job_queue = instance_double('Bosh::Director::JobQueue')
allow(JobQueue).to receive(:new).and_return(job_queue)
task = instance_double('Bosh::Director::Models::Task', id: 1)
expect(job_queue).to receive(:enqueue).with(
'admin',
Jobs::RunErrand,
'run errand fake-errand-name from deployment fake-dep-name',
['fake-dep-name', 'fake-errand-name'],
).and_return(task)
perform
end
it 'returns a task' do
perform
expect_redirect_to_queued_task(last_response)
end
end
context 'accessing with invalid credentials' do
before { authorize 'invalid-user', 'invalid-password' }
it 'returns 401' do
perform
expect(last_response.status).to eq(401)
end
end
context 'unauthenticated access' do
it 'returns 401' do
perform
expect(last_response.status).to eq(401)
end
end
end
end
end
| 27.454545 | 74 | 0.602649 |
bfe283872bf7db081b921bc1b041a2bbb778df96 | 1,681 | # encoding: utf-8
require 'spec_helper'
module Rubocop
module Cop
module Style
describe RedundantBegin do
let(:cop) { RedundantBegin.new }
it 'reports an offence for def with redundant begin block' do
src = ['def func',
' begin',
' ala',
' rescue => e',
' bala',
' end',
'end']
inspect_source(cop, src)
expect(cop.offences).to have(1).item
end
it 'reports an offence for defs with redundant begin block' do
src = ['def Test.func',
' begin',
' ala',
' rescue => e',
' bala',
' end',
'end']
inspect_source(cop, src)
expect(cop.offences).to have(1).item
end
it 'accepts a def with required begin block' do
src = ['def func',
' begin',
' ala',
' rescue => e',
' bala',
' end',
' something',
'end']
inspect_source(cop, src)
expect(cop.offences).to be_empty
end
it 'accepts a defs with required begin block' do
src = ['def Test.func',
' begin',
' ala',
' rescue => e',
' bala',
' end',
' something',
'end']
inspect_source(cop, src)
expect(cop.offences).to be_empty
end
end
end
end
end
| 26.265625 | 70 | 0.395003 |
38b29ea992b1c36a2ab5f19e09ebef25326fa15e | 3,130 | module Selenium
module WebDriver
module Firefox
class Binary
def initialize
ENV['MOZ_NO_REMOTE'] = '1' # able to launch multiple instances
check_binary_exists
end
def create_base_profile(name)
execute("-CreateProfile", name)
status = nil
Timeout.timeout(15, Error::TimeOutError) do
_, status = wait
end
if status && status.to_i != 0
raise Error::WebDriverError, "could not create base profile: (exit status: #{status})"
end
end
def start_with(profile, *args)
ENV['XRE_PROFILE_PATH'] = profile.absolute_path
execute(*args)
cope_with_mac_strangeness(args) if Platform.mac?
end
def execute(*extra_args)
args = [path, "-no-remote", "--verbose"] + extra_args
@process = ChildProcess.new(*args).start
end
def cope_with_mac_strangeness(args)
sleep 0.3
if @process.ugly_death?
# process crashed, trying a restart. sleeping 5 seconds shorter than the java driver
sleep 5
execute(*args)
end
# ensure we're ok
sleep 0.3
if @process.ugly_death?
raise Error::WebDriverError, "unable to start Firefox cleanly, args: #{args.inspect}"
end
end
def kill
@process.kill if @process
end
def wait
@process.wait if @process
end
def pid
@process.pid if @process
end
private
def path
@path ||= case Platform.os
when :macosx
"/Applications/Firefox.app/Contents/MacOS/firefox-bin"
when :windows
windows_path
when :linux, :unix
"/usr/bin/firefox"
else
raise "Unknown platform: #{Platform.os}"
end
end
def check_binary_exists
unless File.file?(path)
raise Error::WebDriverError, "Could not find Firefox binary. Make sure Firefox is installed (OS: #{Platform.os})"
end
end
def windows_path
windows_registry_path || (ENV['PROGRAMFILES'] || "\\Program Files") + "\\Mozilla Firefox\\firefox.exe"
end
def windows_registry_path
return if Platform.jruby? || Platform.ironruby?
require "win32/registry"
lm = Win32::Registry::HKEY_LOCAL_MACHINE
lm.open("SOFTWARE\\Mozilla\\Mozilla Firefox") do |reg|
main = lm.open("SOFTWARE\\Mozilla\\Mozilla Firefox\\#{reg.keys[0]}\\Main")
if entry = main.find {|key, type, data| key =~ /pathtoexe/i}
return entry.last
end
end
rescue Win32::Registry::Error
raise Error::WebDriverError, "Firefox not found in Windows registry, please make sure you have it installed."
end
end # Binary
end # Firefox
end # WebDriver
end # Selenium
| 28.981481 | 125 | 0.544089 |
b9ce261d92ebf496dca1daccdcf24c269da0da73 | 736 | class Api::V1::CollectionsController < ApplicationController
def index
collections = Collection.all
render json: CollectionSerializer.new(collections)
end
def create
collection = Collection.new(collection_params)
if collection.save
render json: CollectionSerializer.new(collection), status: :accepted
else
render json: {errors: collection.errors.full_messages}, status: :unprocessible_entity
end
end
def destroy
collect = Collection.find(params[:id])
collect.destroy
end
private
def collection_params
params.require(:collection).permit(:name, :image_url, :description, :source_url, :category_id)
end
end
| 22.30303 | 102 | 0.675272 |
6a4cb12977a926576c5165c425e613fdb423206b | 8,878 | # typed: false
require 'spec_helper'
require 'datadog/statsd'
require 'ddtrace'
require 'benchmark/ips'
unless PlatformHelpers.jruby?
require 'benchmark/memory'
require 'memory_profiler'
end
require 'fileutils'
require 'json'
RSpec.shared_context 'benchmark' do
# When applicable, runs the test subject for different input sizes.
# Similar to how N in Big O notation works.
#
# This value is provided to the `subject(i)` method in order for the test
# to appropriately execute its run based on input size.
let(:steps) { defined?(super) ? super() : [1, 10, 100] }
# How many times we run our program when testing for memory allocation.
# In theory, we should only need to run it once, as memory tests are not
# dependent on competing system resources.
# But occasionally we do see a few blimps of inconsistency, making the benchmarks skewed.
# By running the benchmarked snippet many times, we drown out any one-off anomalies, allowing
# the real memory culprits to surface.
let(:memory_iterations) { defined?(super) ? super() : 100 }
# How long the program will run when calculating IPS performance, in seconds.
let(:timing_runtime) { defined?(super) ? super() : 5 }
# Outputs human readable information to STDERR.
# Most of the benchmarks have nicely formatted reports
# that are by default printed to terminal.
before do |e|
@test = e.metadata[:example_group][:full_description]
@type = e.description
warn "Test:#{e.metadata[:example_group][:full_description]} #{e.description}"
end
def warm_up
steps.each do |s|
subject(s)
end
end
# Report JSON result objects to ./tmp/benchmark/ folder
# Theses results can be historically tracked (e.g. plotting) if needed.
def write_result(result, subtype = nil)
file_name = if subtype
"#{@type}-#{subtype}"
else
@type
end
warn(@test, file_name, result)
directory = result_directory!(subtype)
path = File.join(directory, file_name)
File.write(path, JSON.pretty_generate(result))
warn("Result written to #{path}")
end
# Create result directory for current benchmark
def result_directory!(subtype = nil)
path = File.join('tmp', 'benchmark', @test)
path = File.join(path, subtype.to_s) if subtype
FileUtils.mkdir_p(path)
path
end
# Measure execution time
it 'timing' do
report = Benchmark.ips do |x|
x.config(time: timing_runtime, warmup: timing_runtime / 10.0)
steps.each do |s|
x.report(s) do
subject(s)
end
end
x.compare!
end
result = report.entries.each_with_object({}) do |entry, hash|
hash[entry.label] = { ips: entry.stats.central_tendency, error: entry.stats.error_percentage / 100 }
end.to_h
write_result(result)
end
# Measure memory usage (object creation and memory size)
it 'memory' do
warm_up
skip("'benchmark/memory' not supported") if PlatformHelpers.jruby?
report = Benchmark.memory do |x|
steps.each do |s|
x.report(s) do
memory_iterations.times { subject(s) }
end
end
x.compare!
end
result = report.entries.map do |entry|
row = entry.measurement.map do |metric|
{ type: metric.type, allocated: metric.allocated, retained: metric.retained }
end
[entry.label, row]
end.to_h
write_result(result)
end
# Measure GC cycles triggered during run
it 'gc' do
skip if PlatformHelpers.jruby?
warm_up
io = StringIO.new
GC::Profiler.enable
memory_iterations.times { subject(steps[0]) }
GC.disable # Prevent data collection from influencing results
data = GC::Profiler.raw_data
GC::Profiler.report(io)
GC::Profiler.disable
GC.enable
puts io.string
result = { count: data.size, time: data.sum { |d| d[:GC_TIME] } }
write_result(result)
end
# Reports that generate non-aggregated data.
# Useful for debugging.
context 'detailed' do
before { skip('Detailed report are too verbose for CI') if ENV.key?('CI') }
let(:ignore_files) { defined?(super) ? super() : nil }
# Memory report with reference to each allocation site
it 'memory report' do
skip("'benchmark/memory' not supported") if PlatformHelpers.jruby?
warm_up
steps.each do |step|
report = MemoryProfiler.report(ignore_files: ignore_files) do
memory_iterations.times { subject(step) }
end
report_results(report, step)
end
end
def report_results(report, step)
puts "Report for step: #{step}"
report.pretty_print
per_gem_report = lambda do |results|
Hash[results.map { |x| [x[:data], x[:count]] }.sort_by(&:first)]
end
result = {
total_allocated: report.total_allocated,
total_allocated_memsize: report.total_allocated_memsize,
total_retained: report.total_retained,
total_retained_memsize: report.total_retained_memsize,
allocated_memory_by_gem: per_gem_report[report.allocated_memory_by_gem],
allocated_objects_by_gem: per_gem_report[report.allocated_objects_by_gem],
retained_memory_by_gem: per_gem_report[report.retained_memory_by_gem],
retained_objects_by_gem: per_gem_report[report.retained_objects_by_gem]
}
write_result(result, step)
end
# CPU profiling report
context 'RubyProf report' do
before do
if PlatformHelpers.jruby? || Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.4.0')
skip("'ruby-prof' not supported")
end
end
before do
require 'ruby-prof'
RubyProf.measure_mode = RubyProf::PROCESS_TIME
end
it do
warm_up
steps.each do |step|
result = RubyProf.profile do
(memory_iterations * 5).times { subject(step) }
end
report_results(result, step)
end
end
def report_results(result, step)
puts "Report for step: #{step}"
directory = result_directory!(step)
printer = RubyProf::CallTreePrinter.new(result)
printer.print(path: directory)
warn("Results written in Callgrind format to #{directory}")
warn('You can use KCachegrind or QCachegrind to read these results.')
warn('On MacOS:')
warn('$ brew install qcachegrind')
warn("$ qcachegrind '#{Dir["#{directory}/*"].min}'")
end
end
end
end
require 'socket'
# An "agent" that always responds with a proper OK response, while
# keeping minimum overhead.
#
# The goal is to reduce external performance noise from running a real
# agent process in the system.
#
# It finds a locally available port to listen on, and updates the value of
# {Datadog::Ext::Transport::HTTP::ENV_DEFAULT_PORT} accordingly.
RSpec.shared_context 'minimal agent' do
let(:agent_server) { TCPServer.new '127.0.0.1', agent_port }
let(:agent_port) { ENV[Datadog::Tracing::Configuration::Ext::Transport::ENV_DEFAULT_PORT].to_i }
# Sample agent response, collected from a real agent exchange.
AGENT_HTTP_RESPONSE = "HTTP/1.1 200\r\n" \
"Content-Length: 40\r\n" \
"Content-Type: application/json\r\n" \
"Date: Thu, 03 Sep 2020 20:05:54 GMT\r\n" \
"\r\n" \
"{\"rate_by_service\":{\"service:,env:\":1}}\n".freeze
def server_runner
previous_conn = nil
loop do
conn = agent_server.accept
conn.print AGENT_HTTP_RESPONSE
conn.flush
# Read HTTP request to allow other side to have enough
# buffer write room. If we don't, the client won't be
# able to send the full request until the buffer is cleared.
conn.read(1 << 31 - 1)
# Closing the connection immediately can sometimes
# be too fast, cause to other side to not be able
# to read the response in time.
# We instead delay closing the connection until the next
# connection request comes in.
previous_conn.close if previous_conn
previous_conn = conn
end
end
before do
# Initializes server in a fork, to allow for true concurrency.
# In JRuby, threads are not supported, but true thread concurrency is.
@agent_runner = if Process.respond_to?(:fork)
fork { server_runner }
else
Thread.new { server_runner }
end
end
after do
if Process.respond_to?(:fork)
Process.kill('TERM', @agent_runner) rescue nil
Process.wait(@agent_runner)
else
@agent_runner.kill
end
end
around do |example|
# Set the agent port used by the default HTTP transport
ClimateControl.modify(Datadog::Tracing::Configuration::Ext::Transport::ENV_DEFAULT_PORT => available_port.to_s) do
example.run
end
end
end
| 28.731392 | 118 | 0.660059 |
1de12c9c56df6d61b56aa651c1a03e6a90debc4b | 2,222 | # frozen_string_literal: true
require 'spec_helper'
describe 'is_integer' do
it { is_expected.not_to eq(nil) }
it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) }
it { is_expected.to run.with_params(1, 2).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) }
it { is_expected.to run.with_params(3).and_return(true) }
it { is_expected.to run.with_params('3').and_return(true) }
it { is_expected.to run.with_params(-3).and_return(true) }
it { is_expected.to run.with_params('-3').and_return(true) }
it { is_expected.to run.with_params("123\nfoo").and_return(true) }
it { is_expected.to run.with_params("foo\n123").and_return(true) }
it { is_expected.to run.with_params(3.7).and_return(false) }
it { is_expected.to run.with_params('3.7').and_return(false) }
it { is_expected.to run.with_params(-3.7).and_return(false) }
it { is_expected.to run.with_params('-3.7').and_return(false) }
it { is_expected.to run.with_params('one').and_return(false) }
it { is_expected.to run.with_params([]).and_return(false) }
it { is_expected.to run.with_params([1]).and_return(false) }
it { is_expected.to run.with_params({}).and_return(false) }
it { is_expected.to run.with_params(true).and_return(false) }
it { is_expected.to run.with_params(false).and_return(false) }
it { is_expected.to run.with_params('0001234').and_return(false) }
it { is_expected.to run.with_params("foo\nbar").and_return(false) }
context 'with deprecation warning' do
after(:each) do
ENV.delete('STDLIB_LOG_DEPRECATIONS')
end
# Checking for deprecation warning, which should only be provoked when the env variable for it is set.
it 'displays a single deprecation' do
ENV['STDLIB_LOG_DEPRECATIONS'] = 'true'
expect(scope).to receive(:warning).with(include('This method is deprecated'))
is_expected.to run.with_params(50).and_return(true)
end
it 'displays no warning for deprecation' do
ENV['STDLIB_LOG_DEPRECATIONS'] = 'false'
expect(scope).to receive(:warning).with(include('This method is deprecated')).never
is_expected.to run.with_params(50).and_return(true)
end
end
end
| 45.346939 | 113 | 0.721872 |
08a914a59163024ea77f935418ee94b78f7ba03c | 447 | class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :audiences
validates :first_name, :presence => true
validates :last_name, :presence => true
def fullName
return "#{self.first_name} #{self.last_name}"
end
end | 31.928571 | 62 | 0.733781 |
613f5d90f53d5a61672dce1f5a5a2bb354cf5aa4 | 8,847 | require 'hanami/utils'
module Hanami
# Registered components
#
# @since 0.9.0
# @api private
#
# @see Hanami::Components
module Components # rubocop:disable Metrics/ModuleLength
# Require the entire project
#
# @since 0.9.0
# @api private
register 'all' do
requires 'model', 'apps', 'finalizers'
resolve { true }
end
# Check if code reloading is enabled
#
# @since 0.9.0
# @api private
register 'code_reloading' do
prepare do
begin
require 'shotgun'
rescue LoadError # rubocop:disable Lint/HandleExceptions
end
end
resolve do
defined?(Shotgun) &&
Components['environment'].code_reloading? &&
true
end
end
# Tries to load hanami-model, if available for the project
#
# @since 0.9.0
# @api private
#
# @example With hanami-model
# Hanami::Components.resolve('model')
# Hanami::Components['model'] # => true
#
# @example Without hanami-model
# Hanami::Components.resolve('model')
# Hanami::Components['model'] # => nil
register 'model' do
requires 'model.configuration', 'model.sql'
resolve do
if Components['model.configuration']
Hanami::Model.load!
true
end
end
end
# Tries to evaluate hanami-model configuration, if available for the project
#
# @since 0.9.0
# @api private
#
# @example With hanami-model
# Hanami::Components.resolve('model.configuration')
# Hanami::Components['model.configuration'].class # => Hanami::Model::Configuration
#
# @example Without hanami-model
# Hanami::Components.resolve('model.configuration')
# Hanami::Components['model.configuration'].class # => NilClass
register 'model.configuration' do
requires 'model.bundled'
resolve do |configuration|
if Components['model.bundled']
Hanami::Model.configure(&configuration.model)
Hanami::Model.configuration
end
end
end
# Tries to load SQL support for hanami, if available for the project
#
# @since 0.9.0
# @api private
#
# @example With hanami-model
# Hanami::Components.resolve('model.sql')
# Hanami::Components['model.sql'] # => true
#
# @example Without hanami-model
# Hanami::Components.resolve('model.sql')
# Hanami::Components['model.sql'] # => nil
register 'model.sql' do
requires 'model.configuration'
prepare do
begin
require 'hanami/model/sql'
rescue LoadError # rubocop:disable Lint/HandleExceptions
end
end
resolve do
true if defined?(Hanami::Model::Sql)
end
end
# Check if hanami-model is bundled
#
# @since 0.9.0
# @api private
#
# @example With hanami-model
# Hanami::Components.resolve('model.bundled')
# Hanami::Components['model.bundled'] # => true
#
# @example Without hanami-model
# Hanami::Components.resolve('model.bundled')
# Hanami::Components['model.bundled'] # => nil
register 'model.bundled' do
prepare do
begin
require 'hanami/model'
rescue LoadError # rubocop:disable Lint/HandleExceptions
end
end
resolve do
true if defined?(Hanami::Model)
end
end
# Loads the routes for all the mounted Hanami/Rack applications
#
# This is used only by `hanami routes` command.
#
# @since 0.9.0
# @api private
register 'routes.inspector' do
requires 'apps.configurations'
prepare do
require 'hanami/components/routes_inspector'
end
resolve do |configuration|
RoutesInspector.new(configuration)
end
end
# Loads all the Hanami applications in the project
#
# @since 0.9.0
# @api private
register 'apps' do
resolve do |configuration|
configuration.apps do |app|
component('app').call(app)
end
true
end
end
# Evaluates all the Hanami applications' configurations in the project
#
# @since 0.9.0
# @api private
register 'apps.configurations' do
resolve do |configuration|
configuration.apps do |app|
component('app.configuration').call(app)
end
true
end
end
# Evaluates all the Hanami assets configurations for each application in the project
#
# This is used only by `hanami assets precompile` command.
#
# @since 0.9.0
# @api private
register 'apps.assets.configurations' do
requires 'apps.configurations'
prepare do
require 'hanami/components/app/assets'
end
resolve do |configuration|
[].tap do |result|
configuration.apps do |app|
result << Components::App::Assets.resolve(app)
end
end
end
end
# Finalizers for the project
#
# @since 0.9.0
# @api private
register 'finalizers' do
requires 'finalizers.initializers'
resolve { true }
end
# Load project initializers
#
# @since 0.9.0
# @api private
register 'finalizers.initializers' do
run do
Hanami::Utils.require!(
Hanami.root.join('config', 'initializers')
)
end
end
# Configure, load and finalize a Hanami application in the project
#
# @since 0.9.0
# @api private
register 'app' do
run do |app|
['app.configuration', 'app.frameworks', 'app.code', 'app.routes', 'app.finalizer'].each do |c|
component(c).call(app)
end
resolved(app.app_name, true)
end
end
# Evaluate the configuration of a single Hanami application in the project
#
# @since 0.9.0
# @api private
register 'app.configuration' do
run do |app|
resolved("#{app.app_name}.configuration") do
ApplicationConfiguration.new(app.namespace, app.configurations, app.path_prefix).tap do |config|
app.configuration = config
end
end
end
end
# Evaluate Hanami frameworks configurations of a single Hanami application in the project
#
# @since 0.9.0
# @api private
register 'app.frameworks' do
run do |app|
['app.controller', 'app.view', 'app.assets', 'app.logger'].each do |c|
component(c).call(app)
end
end
end
# Evaluate hanami-controller configuration of a single Hanami application in the project
#
# @since 0.9.0
# @api private
register 'app.controller' do
prepare do
require 'hanami/components/app/controller'
end
run do |app|
Components::App::Controller.resolve(app)
end
end
# Evaluate hanami-view configuration of a single Hanami application in the project
#
# @since 0.9.0
# @api private
register 'app.view' do
prepare do
require 'hanami/components/app/view'
end
run do |app|
Components::App::View.resolve(app)
end
end
# Evaluate hanami-assets configuration of a single Hanami application in the project
#
# @since 0.9.0
# @api private
register 'app.assets' do
prepare do
require 'hanami/components/app/assets'
end
run do |app|
Components::App::Assets.resolve(app)
end
end
# Evaluate hanami/logger configuration of a single Hanami application in the project
#
# @since 0.9.0
# @api private
register 'app.logger' do
prepare do
require 'hanami/components/app/logger'
end
run do |app|
Components::App::Logger.resolve(app)
end
end
# Load the code for a single Hanami application in the project
#
# @since 0.9.0
# @api private
register 'app.code' do
run do |app|
config = app.configuration
config.load_paths.load!
end
end
# Load the routes for a single Hanami application in the project
#
# @since 0.9.0
# @api private
register 'app.routes' do
prepare do
require 'hanami/components/app/routes'
end
run do |app|
Components::App::Routes.resolve(app)
end
end
# Finalize a single Hanami application in the project
#
# @since 0.9.0
# @api private
register 'app.finalizer' do
run do |app|
config = app.configuration
namespace = app.namespace
config.middleware.load!
namespace.module_eval %(#{namespace}::Controller.load!)
namespace.module_eval %(#{namespace}::View.load!)
namespace.module_eval %(#{namespace}::Assets.load!)
end
end
end
end
| 24.106267 | 106 | 0.59896 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.