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
1c6bf53dea2837a62387bb3cf7f8f9d6dbb0716b
1,928
# # Cookbook:: ruby_rbenv # Recipe:: user_install # # Copyright:: 2011-2017, Fletcher Nichol # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # include_recipe 'ruby_rbenv' install_rbenv_pkg_prereqs template '/etc/profile.d/rbenv.sh' do source 'rbenv.sh.erb' owner 'root' mode '0755' only_if { node['rbenv']['create_profiled'] } end Array(node['rbenv']['user_installs']).each do |rb_user| if rb_user['home'].nil? next unless ::File.exist?(File.join(node['rbenv']['user_home_root'], rb_user['user'])) else next unless ::File.exist?(rb_user['home']) end upgrade_strategy = build_upgrade_strategy(rb_user['upgrade']) git_url = rb_user['git_url'] || node['rbenv']['git_url'] git_ref = rb_user['git_ref'] || node['rbenv']['git_ref'] home_dir = rb_user['home'] || ::File.join( node['rbenv']['user_home_root'], rb_user['user']) rbenv_prefix = rb_user['root_path'] || ::File.join(home_dir, '.rbenv') rbenv_plugins = rb_user['plugins'] || [] install_or_upgrade_rbenv rbenv_prefix: rbenv_prefix, home_dir: home_dir, git_url: git_url, git_ref: git_ref, upgrade_strategy: upgrade_strategy, user: rb_user['user'], group: rb_user['group'], rbenv_plugins: rbenv_plugins end
35.703704
90
0.637448
4a01da4a56e7d54582fd6ba8a2102c50dd8dd483
33
module MonthlyExpencesHelper end
11
28
0.909091
62262eb1ced153e985a5cebe7dbf03d5197c886b
1,599
class CloudNuke < Formula desc "CLI tool to nuke (delete) cloud resources" homepage "https://gruntwork.io/" url "https://github.com/gruntwork-io/cloud-nuke/archive/v0.1.30.tar.gz" sha256 "5f79e00b32bfba7e669127e50adccb6d21c0f8351d66733bbfa7bddd5d8653a3" license "MIT" head "https://github.com/gruntwork-io/cloud-nuke.git" bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "af12dea60e894df260e12fb281befdca83ceeb29d95235b6ca7f82e74efeecbf" sha256 cellar: :any_skip_relocation, big_sur: "6ec739fadc9ae6423b94f400cac632a524d5484f4cf3ec8d198b3622fc6b74fd" sha256 cellar: :any_skip_relocation, catalina: "20a887ea78779cf126585fd7c0020b36c3d3545c3f57b8d0137d5da5d57aceb2" sha256 cellar: :any_skip_relocation, mojave: "af204a87970fceee89f2cebe941b4784a78c38a80b84e8c8d5340b5a7b2be26b" sha256 cellar: :any_skip_relocation, x86_64_linux: "ebd54e23b85e9f93a25d64f625e109fa82422f115d4a060e9d4075e2cebcd649" end depends_on "go" => :build def install system "go", "build", "-ldflags", "-s -w -X main.VERSION=v#{version}", *std_go_args end def caveats <<~EOS Before you can use these tools, you must export some variables to your $SHELL. export AWS_ACCESS_KEY="<Your AWS Access ID>" export AWS_SECRET_KEY="<Your AWS Secret Key>" export AWS_REGION="<Your AWS Region>" EOS end test do assert_match "A CLI tool to nuke (delete) cloud resources", shell_output("#{bin}/cloud-nuke --help 2>1&") assert_match "ec2", shell_output("#{bin}/cloud-nuke aws --list-resource-types") end end
43.216216
122
0.750469
6afe53bdab4cc749cd48f11f9f8058b7a813a41d
1,195
require_relative 'lib/swq/version' Gem::Specification.new do |spec| spec.name = "swq" spec.version = Swq::VERSION spec.authors = ["norioc"] spec.email = ["[email protected]"] spec.summary = %q{helps you find sw quotes} spec.description = %q{helps you find sw quotes.} spec.homepage = "https://swapi.co/api/people/" spec.license = "MIT" spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0") spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'" spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = "https://swapi.co/api/people/" spec.metadata["changelog_uri"] = "https://swapi.co/api/people/" # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] end
39.833333
87
0.643515
623a6b66e0852449a467ab23afac8d86285ae2dd
750
require 'test_helper' class PackageMapperTest < ActiveSupport::TestCase test "truth" do assert_kind_of Class, GRPC::Rails::PackageMapper end test "#service" do package_mapper = GRPC::Rails::PackageMapper .new("helloworld", TestRegistry.new([])) instance = package_mapper.service("greeter") { self } assert_instance_of GRPC::Rails::ServiceMapper, instance assert Object.constants.include?(:GreeterServiceImpl) Object.send(:remove_const, :GreeterServiceImpl) end test "#register" do route_mapper = TestRegistry.new([]) package_mapper = GRPC::Rails::PackageMapper.new("mypackage", route_mapper) package_mapper.register("my-service") assert_equal ["my-service"], route_mapper.objects end end
30
78
0.730667
ff930b16b32027e23188d4f7d15b833eb6b88ead
42
module Coolifyk VERSION = "1.0.1.9" end
10.5
21
0.666667
1af8b5eb2fa157d4fb4128872cfe85e8e35f553f
1,674
# -*- encoding: utf-8 -*- # stub: aws-sdk-pinpointemail 1.6.0 ruby lib Gem::Specification.new do |s| s.name = "aws-sdk-pinpointemail".freeze s.version = "1.6.0" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.metadata = { "changelog_uri" => "https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-pinpointemail/CHANGELOG.md", "source_code_uri" => "https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-pinpointemail" } if s.respond_to? :metadata= s.require_paths = ["lib".freeze] s.authors = ["Amazon Web Services".freeze] s.date = "2019-03-28" s.description = "Official AWS Ruby gem for Amazon Pinpoint Email Service (Pinpoint Email). This gem is part of the AWS SDK for Ruby.".freeze s.email = ["[email protected]".freeze] s.homepage = "http://github.com/aws/aws-sdk-ruby".freeze s.licenses = ["Apache-2.0".freeze] s.rubygems_version = "3.0.6".freeze s.summary = "AWS SDK for Ruby - Pinpoint Email".freeze s.installed_by_version = "3.0.6" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<aws-sdk-core>.freeze, ["~> 3", ">= 3.48.2"]) s.add_runtime_dependency(%q<aws-sigv4>.freeze, ["~> 1.1"]) else s.add_dependency(%q<aws-sdk-core>.freeze, ["~> 3", ">= 3.48.2"]) s.add_dependency(%q<aws-sigv4>.freeze, ["~> 1.1"]) end else s.add_dependency(%q<aws-sdk-core>.freeze, ["~> 3", ">= 3.48.2"]) s.add_dependency(%q<aws-sigv4>.freeze, ["~> 1.1"]) end end
45.243243
254
0.670848
d5fb79509f1b795255fc8e1e77519e9a098d9804
1,219
=begin #Molecule API Documentation #The Hydrogen Molecule API OpenAPI spec version: 1.3.0 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.14 =end require 'spec_helper' require 'json' require 'date' # Unit tests for MoleculeApi::CurrencyUpdateParams # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'CurrencyUpdateParams' do before do # run before each test @instance = MoleculeApi::CurrencyUpdateParams.new end after do # run after each test end describe 'test an instance of CurrencyUpdateParams' do it 'should create an instance of CurrencyUpdateParams' do expect(@instance).to be_instance_of(MoleculeApi::CurrencyUpdateParams) end end describe 'test attribute "logo"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "is_allowed"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
25.395833
102
0.747334
f8951feca56cd68b0fd6b1e06acd44c5268349f8
1,938
module Datagrid module Drivers class Array < AbstractDriver #:nodoc: def self.match?(scope) !Datagrid::Drivers::ActiveRecord.match?(scope) && (scope.is_a?(::Array) || scope.is_a?(Enumerator)) end def to_scope(scope) scope end def where(scope, attribute, value) scope.select do |object| object.send(attribute) == value end end def asc(scope, order) return scope unless order return scope if order.empty? scope.sort_by do |object| object.send(order) end end def desc(scope, order) asc(scope, order).reverse end def default_order(scope, column_name) column_name end def reverse_order(scope) scope.reverse end def greater_equal(scope, field, value) scope.select do |object| compare_value = object.send(field) compare_value.respond_to?(:>=) && compare_value >= value end end def less_equal(scope, field, value) scope.select do |object| compare_value = object.send(field) compare_value.respond_to?(:<=) && compare_value <= value end end def has_column?(scope, column_name) scope.any? && scope.first.respond_to?(column_name) end def is_timestamp?(scope, column_name) has_column?(scope, column_name) && timestamp_class?(scope.first.send(column_name).class) end def contains(scope, field, value) scope.select do |object| object.send(field).to_s.include?(value) end end def column_names(scope) [] end def batch_each(scope, batch_size, &block) scope.each(&block) end def default_cache_key(asset) asset end def can_preload?(scope, association) false end end end end
22.534884
107
0.582043
0192379d0d2631f464a8638dfe04d4902e21dd10
360
cask 'jump' do version '8.4.3' sha256 'c879dc05f2415f64d26b23b6f753e88d0a10382c87112cbd6e32ee7659e419f3' url "https://mirror.jumpdesktop.com/downloads/JumpDesktopMac-#{version}.zip" appcast 'https://jumpdesktop.com/downloads/viewer/jdmac-web-appcast.xml' name 'Jump Desktop' homepage 'https://jumpdesktop.com/#jdmac' app 'Jump Desktop.app' end
30
78
0.769444
330ace9da1b762faf26334cd71f381418d1d8fdf
2,959
module Odania class Consul attr_reader :service, :config, :event, :health def initialize(consul_url) consul_url = ENV['CONSUL_ADDR'] if consul_url.nil? consul_url = 'http://consul:8500' if consul_url.nil? $logger.info "Consul URL: #{consul_url}" if $debug Diplomat.configure do |config| # Set up a custom Consul URL config.url = consul_url end @service = Service.new @config = Config.new @event = Event.new @health = Health.new end class Config def get(path) begin JSON.parse Diplomat::Kv.get path rescue Diplomat::KeyNotFound nil end end def get_all(path) retrieve_value path end def set(key, value) Diplomat::Kv.put(key, JSON.dump(value)) end def delete(key) Diplomat::Kv.delete(key) end protected def retrieve_value(plugin_path) begin result = {} Diplomat::Kv.get(plugin_path, :recurse => true).each do |data| result[data[:key]] = JSON.parse data[:value] end result rescue Diplomat::KeyNotFound {} end end end class Service def get_all services = {} Diplomat::Service.get_all.each_pair do |key, _value| services[key.to_s] = get_all_for(key) end $logger.info "SERVICES: #{JSON.pretty_generate services}" if $debug services end def get_all_for(plugin_name) begin instances = get(plugin_name, :all) rescue instances = [] end instances.is_a?(Array) ? instances : [instances] end # TODO Is there an easier way to get the first service tagges with "core-backend"? def get_core_service core_backends = [] begin Diplomat::Service.get_all.each_pair do |key, tags| core_backends << key if tags.include? 'core-backend' end rescue $logger.warn 'No services in consul!' end get(core_backends.shuffle.first) end def get(key, scope=:first) Diplomat::Service.get(key, scope) end def register(consul_config) if Diplomat::Service.register consul_config $logger.info 'Service registered' if $debug else $logger.error 'Error registering service' end end def deregister(name) Diplomat::Service.deregister name end def build_config(plugin_name, plugin_instance_name, ip, tags=[], port=80) { 'id' => plugin_instance_name, 'name' => plugin_name, 'tags' => tags, 'address' => ip, 'port' => port, 'token' => plugin_instance_name, 'checks' => [ { 'id' => plugin_name, 'name' => "HTTP on port #{port}", 'http' => "http://#{ip}:#{port}/health", 'interval' => '10s', 'timeout' => '1s' } ] } end end class Event def fire(key, value) Diplomat::Event.fire key, value end end class Health def state(state=:any) Diplomat::Health.state(state) end def service(name) Diplomat::Health.service(name) end end end end
20.692308
85
0.625549
e8fc0d48476746b9951f2bab461d741a8bc17f42
82
module CapeJS module Rails class Engine < ::Rails::Engine end end end
11.714286
34
0.658537
b98709b8b8f918e59f4e74b1ca0fac796d3c4ee7
9,049
=begin #IronWorker CE API #The ultimate, language agnostic, container based task processing framework. OpenAPI spec version: 0.5.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =end require 'date' module IronWorker class NewTask # Name of Docker image to use. This is optional and can be used to override the image defined at the group level. attr_accessor :image # Payload for the task. This is what you pass into each task to make it do something. attr_accessor :payload # Number of seconds to wait before queueing the task for consumption for the first time. Must be a positive integer. Tasks with a delay start in state \"delayed\" and transition to \"running\" after delay seconds. attr_accessor :delay # Maximum runtime in seconds. If a consumer retrieves the task, but does not change it's status within timeout seconds, the task is considered failed, with reason timeout (Titan may allow a small grace period). The consumer should also kill the task after timeout seconds. If a consumer tries to change status after Titan has already timed out the task, the consumer will be ignored. attr_accessor :timeout # Priority of the task. Higher has more priority. 3 levels from 0-2. Tasks at same priority are processed in FIFO order. attr_accessor :priority # \"Number of automatic retries this task is allowed. A retry will be attempted if a task fails. Max 25. Automatic retries are performed by titan when a task reaches a failed state and has `max_retries` > 0. A retry is performed by queueing a new task with the same image id and payload. The new task's max_retries is one less than the original. The new task's `retry_of` field is set to the original Task ID. The old task's `retry_at` field is set to the new Task's ID. Titan will delay the new task for retries_delay seconds before queueing it. Cancelled or successful tasks are never automatically retried.\" attr_accessor :max_retries # Time in seconds to wait before retrying the task. Must be a non-negative integer. attr_accessor :retries_delay # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'image' => :'image', :'payload' => :'payload', :'delay' => :'delay', :'timeout' => :'timeout', :'priority' => :'priority', :'max_retries' => :'max_retries', :'retries_delay' => :'retries_delay' } end # Attribute type mapping. def self.swagger_types { :'image' => :'String', :'payload' => :'String', :'delay' => :'Integer', :'timeout' => :'Integer', :'priority' => :'Integer', :'max_retries' => :'Integer', :'retries_delay' => :'Integer' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} if attributes.has_key?(:'image') self.image = attributes[:'image'] end if attributes.has_key?(:'payload') self.payload = attributes[:'payload'] end if attributes.has_key?(:'delay') self.delay = attributes[:'delay'] else self.delay = 0 end if attributes.has_key?(:'timeout') self.timeout = attributes[:'timeout'] else self.timeout = 60 end if attributes.has_key?(:'priority') self.priority = attributes[:'priority'] end if attributes.has_key?(:'max_retries') self.max_retries = attributes[:'max_retries'] else self.max_retries = 0 end if attributes.has_key?(:'retries_delay') self.retries_delay = attributes[:'retries_delay'] else self.retries_delay = 60 end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new return invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? return false if @image.nil? return false if @priority.nil? return true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && image == o.image && payload == o.payload && delay == o.delay && timeout == o.timeout && priority == o.priority && max_retries == o.max_retries && retries_delay == o.retries_delay end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [image, payload, delay, timeout, priority, max_retries, retries_delay].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /^(true|t|yes|y|1)$/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = IronWorker.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map{ |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
33.391144
618
0.642281
08ac592434619e3cf134b7c258b96d5530e11416
377
RSpec.describe Magick::Image, '#trim' do it 'works' do # Can't use the default image because it's a solid color hat = described_class.read(IMAGES_DIR + '/Flower_Hat.jpg').first expect(hat.trim).to be_instance_of(described_class) expect(hat.trim(10)).to be_instance_of(described_class) expect { hat.trim(10, 10) }.to raise_error(ArgumentError) end end
31.416667
68
0.718833
bf37ced41c0f0681b96d1eab3b3efc2065cbaaad
726
# encoding: UTF-8 # # Copyright (c) 2010-2015 GoodData Corporation. All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. require_relative 'object' require_relative '../mixins/obj_id' require_relative '../mixins/rest_resource' module GutData module Rest # Base class for REST resources implementing (at least 'somehow') full CRUD # # IS responsible for wrapping full CRUD interface class Resource < Object include Mixin::RestResource include Mixin::ObjId # Default constructor passing all arguments to parent def initialize(opts = {}) super(opts) end end end end
25.928571
79
0.714876
bb7f0aeae45badc306e5930f75778635725f1aea
5,063
module RSpec::Matchers::BuiltIn RSpec.describe BeBetween do class SizeMatters include Comparable attr :str def <=>(other) str.size <=> other.str.size end def initialize(str) @str = str end def inspect @str end end shared_examples "be_between" do |mode| it "passes if target is between min and max" do expect(5).to matcher(1, 10) end it "fails if target is not between min and max" do expect { # It does not go to 11 expect(11).to matcher(1, 10) }.to fail_with("expected 11 to be between 1 and 10 (#{mode})") end it "works with strings" do expect("baz").to matcher("bar", "foo") expect { expect("foo").to matcher("bar", "baz") }.to fail_with("expected \"foo\" to be between \"bar\" and \"baz\" (#{mode})") end it "works with other Comparable objects" do expect(SizeMatters.new("--")).to matcher(SizeMatters.new("-"), SizeMatters.new("---")) expect { expect(SizeMatters.new("---")).to matcher(SizeMatters.new("-"), SizeMatters.new("--")) }.to fail_with("expected --- to be between - and -- (#{mode})") end end shared_examples "not_to be_between" do |mode| it "passes if target is not between min and max" do expect(11).not_to matcher(1, 10) end it "fails if target is between min and max" do expect { expect(5).not_to matcher(1, 10) }.to fail_with("expected 5 not to be between 1 and 10 (#{mode})") end end shared_examples "composing with other matchers" do |mode| it "passes when the matchers both match" do expect([nil, 3]).to include(matcher(2, 4), a_nil_value) end it "works with mixed types" do expect(["baz", Math::PI]).to include(matcher(3.1, 3.2), matcher("bar", "foo")) expect { expect(["baz", 2.14]).to include(matcher(3.1, 3.2), matcher("bar", "foo") ) }.to fail_with("expected [\"baz\", 2.14] to include (a value between 3.1 and 3.2 (#{mode})) and (a value between \"bar\" and \"foo\" (#{mode}))") end it "provides a description" do description = include(matcher(2, 4), an_instance_of(Float)).description expect(description).to eq("include (a value between 2 and 4 (#{mode})) and (an instance of Float)") end it "fails with a clear error message when the matchers do not match" do expect { expect([nil, 1]).to include(matcher(2, 4), a_nil_value) }.to fail_with("expected [nil, 1] to include (a value between 2 and 4 (#{mode})) and (a nil value)") end end it_behaves_like "an RSpec matcher", :valid_value => (10), :invalid_value => (11) do let(:matcher) { be_between(1, 10) } end describe "expect(...).to be_between(min, max) (inclusive)" do it_behaves_like "be_between", :inclusive do def matcher(min, max) be_between(min, max) end end it "is inclusive" do expect(1).to be_between(1, 10) expect(10).to be_between(1, 10) end it "indicates it was not comparable if it does not respond to `<=` and `>=`" do expect { expect(nil).to be_between(0, 10) }.to fail_with("expected nil to be between 0 and 10 (inclusive), but it does not respond to `<=` and `>=`") end end describe "expect(...).to be_between(min, max) (exclusive)" do it_behaves_like "be_between", :exclusive do def matcher(min, max) be_between(min, max).exclusive end end it "indicates it was not comparable if it does not respond to `<` and `>`" do expect { expect(nil).to be_between(0, 10).exclusive }.to fail_with("expected nil to be between 0 and 10 (exclusive), but it does not respond to `<` and `>`") end it "is exclusive" do expect { expect(1).to be_between(1, 10).exclusive }.to fail expect { expect(10).to be_between(1, 10).exclusive }.to fail end end describe "expect(...).not_to be_between(min, max) (inclusive)" do it_behaves_like "not_to be_between", :inclusive do def matcher(min, max) be_between(min, max) end end end describe "expect(...).not_to be_between(min, max) (exclusive)" do it_behaves_like "not_to be_between", :exclusive do def matcher(min, max) be_between(min, max).exclusive end end end describe "composing with other matchers (inclusive)" do it_behaves_like "composing with other matchers", :inclusive do def matcher(min, max) a_value_between(min, max) end end end describe "composing with other matchers (exclusive)" do it_behaves_like "composing with other matchers", :exclusive do def matcher(min, max) a_value_between(min, max).exclusive end end end end end
32.044304
153
0.587794
01f9eb041a17a383cc3422b037cc2e7f15870a1a
2,715
require 'uri' require 'net/http' require 'rack' # Copied shamelessly from Capybara # Used to run a mock service in a new thread when started by the AppManager or the ControlServer module Pact class Server class Middleware attr_accessor :error def initialize(app) @app = app end def call(env) if env["PATH_INFO"] == "/__identify__" [200, {}, [@app.object_id.to_s]] else begin @app.call(env) rescue StandardError => e @error = e unless @error raise e end end end end class << self def ports @ports ||= {} end end attr_reader :app, :host, :port, :options def initialize(app, host, port, options = {}) @app = app @middleware = Middleware.new(@app) @server_thread = nil @host = host @port = port @options = options end def reset_error! @middleware.error = nil end def error @middleware.error end def responsive? return false if @server_thread && @server_thread.join(0) res = get_identity if res.is_a?(Net::HTTPSuccess) or res.is_a?(Net::HTTPRedirection) return res.body == @app.object_id.to_s end rescue SystemCallError return false rescue EOFError return false end def run_default_server(app, port) require 'rack/handler/webrick' Rack::Handler::WEBrick.run(app, **webrick_opts) do |server| @port = server[:Port] end end def get_identity return false unless @port http = Net::HTTP.new host, @port if options[:ssl] http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end http.get('/__identify__') end def webrick_opts opts = { Port: port.nil? ? 0 : port, AccessLog: [], Logger: WEBrick::Log::new(nil, 0) } opts.merge!({ :SSLCertificate => OpenSSL::X509::Certificate.new(File.open(options[:sslcert]).read) }) if options[:sslcert] opts.merge!({ :SSLPrivateKey => OpenSSL::PKey::RSA.new(File.open(options[:sslkey]).read) }) if options[:sslkey] opts.merge!(ssl_opts) if options[:ssl] opts end def ssl_opts { SSLEnable: true, SSLCertName: [ ["CN", host] ] } end def boot unless responsive? @server_thread = Thread.new { run_default_server(@middleware, @port) } Timeout.timeout(60) { @server_thread.join(0.1) until responsive? } end rescue Timeout::Error raise "Rack application timed out during boot" else Pact::Server.ports[@app.object_id] = @port self end end end
24.241071
116
0.591529
38f7dcad43ca4104b1259c9f8f6ddc26cf90d2b3
33,006
# == Schema Information # # Table name: features # # id :bigint not null, primary key # ancestor_ids :string # fid :integer not null # is_blank :boolean default(FALSE), not null # is_name_position_overriden :boolean default(FALSE), not null # is_public :integer # old_pid :string # position :integer default(0) # created_at :datetime # updated_at :datetime # # Indexes # # features_ancestor_ids_idx (ancestor_ids) # features_fid (fid) UNIQUE # features_is_public_idx (is_public) # class Feature < ActiveRecord::Base attr_accessor :skip_update include FeatureExtensionForNamePositioning extend IsDateable validates_presence_of :fid validates_uniqueness_of :fid validates_numericality_of :position, allow_nil: true @@associated_models = [FeatureName, FeatureGeoCode, XmlDocument] # acts_as_solr fields: [:pid] acts_as_family_tree :node, -> { where(feature_relation_type_id: FeatureRelationType.hierarchy_ids) }, tree_class: 'FeatureRelation' acts_as_indexable { |f| ShantiIntegration::Indexer.trigger("uid:#{f.uid}") } # These are distinct from acts_as_family_tree's parent/child_relations, which only include hierarchical parent/child relations. has_many :affiliations, dependent: :destroy has_many :all_child_relations, class_name: 'FeatureRelation', foreign_key: 'parent_node_id', dependent: :destroy has_many :all_parent_relations, class_name: 'FeatureRelation', foreign_key: 'child_node_id', dependent: :destroy has_many :association_notes, as: :notable, dependent: :destroy has_many :cached_feature_names, dependent: :destroy has_many :captions, dependent: :destroy has_many :collections, through: :affiliations has_many :citations, as: :citable, dependent: :destroy has_many :descriptions, dependent: :destroy has_many :essays, dependent: :destroy has_many :geo_codes, class_name: 'FeatureGeoCode', dependent: :destroy # naming inconsistency here (see feature_object_types association) ? has_many :geo_code_types, through: :geo_codes has_many :illustrations, dependent: :destroy has_one :illustration, -> { where(is_primary: true) } has_many :imports, as: 'item', dependent: :destroy has_many :summaries, dependent: :destroy has_one :xml_document, class_name: 'XmlDocument', dependent: :destroy # This fetches root *FeatureNames* (names that don't have parents), # within the scope of the current feature has_many :names, class_name: 'FeatureName', dependent: :destroy do # # # def roots # proxy_target, proxy_owner, proxy_reflection - See Rails "Association Extensions" pa = proxy_association pa.reflection.class_name.constantize.roots.where('feature_names.feature_id' => pa.owner.id) #.sort !!! See the FeatureName.<=> method end def recursive_roots_with_path res = [] self.roots.order('position').collect{ |r| res += r.recursive_roots_with_path } res end end def parent_by_perspective(perspective) parent_relation = FeatureRelation.where(child_node_id: self.id, perspective_id: perspective.id, feature_relation_type_id: FeatureRelationType.hierarchy_ids).select(:parent_node_id).order(:created_at).first parent_relation.nil? ? nil : parent_relation.parent_node end def parents_by_perspective(perspective) parent_relations = FeatureRelation.where(child_node_id: self.id, perspective_id: perspective.id, feature_relation_type_id: FeatureRelationType.hierarchy_ids).select(:parent_node_id).order(:created_at) feature_ids = parent_relations.empty? ? [] : parent_relations.collect{ |pr| pr.parent_node_id }.uniq feature_ids.empty? ? [] : feature_ids.collect { |id| Feature.find(id) } end def closest_parent_by_perspective(perspective) feature_id = Rails.cache.fetch("features/#{self.fid}/closest_parent_by_perspective/#{perspective.id}", expires_in: 1.day) do parent_relation = FeatureRelation.where(child_node_id: self.id, perspective_id: perspective.id, feature_relation_type_id: FeatureRelationType.hierarchy_ids).select(:parent_node_id).order(:created_at).first break parent_relation.parent_node.id if !parent_relation.nil? parent_relation = FeatureRelation.where(child_node_id: self.id, perspective_id: perspective.id).select(:parent_node_id).order(:created_at).first break parent_relation.parent_node.id if !parent_relation.nil? parent_relation = FeatureRelation.where(child_node_id: self.id).select(:parent_node_id).order(:created_at).first break parent_relation.parent_node.id if !parent_relation.nil? nil end feature_id.nil? ? nil : Feature.find(feature_id) end def closest_parents_by_perspective(perspective) feature_ids = Rails.cache.fetch("features/#{self.fid}/closest_parents_by_perspective/#{perspective.id}", expires_in: 1.day) do parent_relations = FeatureRelation.where(child_node_id: self.id, perspective_id: perspective.id, feature_relation_type_id: FeatureRelationType.hierarchy_ids).select(:parent_node_id).order(:created_at) break parent_relations.collect{ |pr| pr.parent_node_id } if !parent_relations.empty? parent_relations = FeatureRelation.where(child_node_id: self.id, perspective_id: perspective.id).select(:parent_node_id).order(:created_at) break parent_relations.collect{ |pr| pr.parent_node_id } if !parent_relations.empty? parent_relations = FeatureRelation.where(child_node_id: self.id).select(:parent_node_id).order(:created_at) break parent_relations.collect{ |pr| pr.parent_node_id } if !parent_relations.empty? [] end feature_ids.nil? ? [] : feature_ids.uniq.collect { |id| Feature.find(id) } end def closest_hierarchical_feature_id_by_perspective(perspective) Rails.cache.fetch("features/#{self.fid}/closest_hierarchical_feature_by_perspective/#{perspective.id}", expires_in: 1.day) do ancestor_ids = self.closest_ancestors_by_perspective(perspective).collect(&:id) root_ids = Feature.current_roots_by_perspective(perspective).collect(&:id) parent_id = (root_ids & ancestor_ids).first break root_ids.first if parent_id.nil? ancestor_ids.delete(parent_id) relation = FeatureRelation.find_by(perspective_id: perspective.id, parent_node_id: parent_id, child_node_id: ancestor_ids, feature_relation_type_id: FeatureRelationType.hierarchy_ids) while !relation.nil? ancestor_ids.delete(parent_id) parent_id = relation.child_node_id relation = FeatureRelation.find_by(perspective_id: perspective.id, parent_node_id: parent_id, child_node_id: ancestor_ids, feature_relation_type_id: FeatureRelationType.hierarchy_ids) end parent_id end end def ancestors_by_perspective(perspective) feature_ids = Rails.cache.fetch("features/#{self.fid}/ancestors_by_perspective/#{perspective.id}", expires_in: 1.day) do root_ids = Feature.current_roots_by_perspective(perspective).collect(&:id) pending = [[self, [self.id]]] goaled = nil while !pending.empty? current_with_path = pending.shift # Use shift for Breadth First Search. For Depth First Search use pop. current = current_with_path.first path = current_with_path.last if root_ids.include?(current.id) goaled = path break # Currenty getting shortest path. Comment second condition and turn goaled into an array to keep iterating in order to get all paths end parents = current.parents_by_perspective(perspective).reject{ |p| path.include?(p.id) } pending += parents.collect{ |p| [p, path + [p.id]] } end goaled.nil? ? [] : goaled.reverse end feature_ids.collect{|id| Feature.find(id)} end def closest_ancestors_by_perspective(perspective) feature_ids = Rails.cache.fetch("features/#{self.fid}/closest_ancestors_by_perspective/#{perspective.id}", expires_in: 1.day) do root_ids = Feature.current_roots_by_perspective(perspective).collect(&:id) pending = [[self, [self.id]]] goaled = nil while !pending.empty? && goaled.nil? # Currenty getting shortest path. Comment second condition and turn goaled into an array to keep iterating in order to get all paths current_with_path = pending.shift # Use shift for Breadth First Search. For Depth First Search use pop. current = current_with_path.first path = current_with_path.last if root_ids.include?(current.id) goaled = path break end parents = current.closest_parents_by_perspective(perspective).reject{ |p| path.include?(p.id) } pending += parents.collect{ |p| [p, path + [p.id]] } end goaled.nil? ? [] : goaled.reverse end feature_ids.collect{|fid| Feature.find(fid)} end # # # def current_children(current_perspective, current_view) return children.includes([{cached_feature_names: :feature_name}, :parent_relations]).references([{cached_feature_names: :feature_name}, :parent_relations]).where('cached_feature_names.view_id' => current_view.id).order('feature_names.name').select do |c| # children(include: [:names, :parent_relations]) c.parent_relations.any? {|cr| cr.perspective==current_perspective} end end def descendants_by_perspective_with_parent(perspective) Feature.descendants_by_perspective_with_parent([self.fid], perspective) end def descendants_with_parent pending = [self] des = pending.collect{|f| [f, nil]} des_ids = pending.collect(&:id) while !pending.empty? e = pending.pop FeatureRelation.where(parent_node_id: e.id).each do |r| c = r.child_node if !des_ids.include? c.id des_ids << c.id des << [c, e, r] pending.push(c) end end end des end def recursive_descendants_with_depth(level = 0) res = [[self, level]] FeatureRelation.where(parent_node_id: self.id).joins(:child_node).order('features.position').each do |r| c = r.child_node res += c.recursive_descendants_with_depth(level+1) end res end def recursive_descendants_by_perspective_with_depth(perspective, level = 0) res = [[self, level]] FeatureRelation.where(parent_node_id: self.id, perspective_id: perspective.id).joins(:child_node).order('features.position').each do |r| c = r.child_node res += c.recursive_descendants_by_perspective_with_depth(perspective, level+1) end res end def all_descendants pending = [self] des = [] des_ids = [] while !pending.empty? e = pending.pop FeatureRelation.select('child_node_id').where(parent_node_id: e.id).each do |r| c = r.child_node if !des_ids.include? c.id des_ids << c.id des << c pending.push(c) end end end des end # # # def current_parent(current_perspective, current_view) current_parents(current_perspective, current_view).first end # # # def current_parents(current_perspective, current_view) return parents.includes(cached_feature_names: :feature_name).references(cached_feature_names: :feature_name).where('cached_feature_names.view_id' => current_view.id).order('feature_names.name').select do |c| # parents(include: [:names, :child_relations]) c.child_relations.any? {|cr| cr.perspective==current_perspective} end end # # # def current_siblings(current_perspective, current_view) # if this feature doesn't have parent_relations, it's a root node. then return root nodes minus this feature # if thie feature DOES have parent relations, get the parent children, minus this feature (parent_relations.empty? ? self.class.current_roots(current_perspective, current_view) : current_parents(current_perspective, current_view).map(&:children).flatten.uniq) - [self] end # # # def current_ancestors(current_perspective) return ancestors.reverse.select do |c| c.child_relations.any? {|cr| cr.perspective==current_perspective} end end # # This is distinct from acts_as_family_tree's relations method, which only finds hierarchical child and parent relations. # def all_relations FeatureRelation.where(['child_node_id = ? OR parent_node_id = ?', id, id]) end # # # def to_s self.name end # # # def pictures_url kmap_path('pictures') end def videos_url kmap_path('videos') end def documents_url kmap_path('documents') end # # Find all features that are related through a FeatureRelation # def related_features relations.collect{|relation| relation.parent_node_id == self.id ? relation.child_node : relation.parent_node} end def associated? @@associated_models.any?{|model| model.find_by(feature_id: self.id)} || !Shape.find_by(fid: self.fid).nil? end def association_notes_for(association_type, options={}) conditions = {notable_type: self.class.name, notable_id: self.id, association_type: association_type, is_public: true} conditions.delete(:is_public) if !options[:include_private].nil? && options[:include_private] == true AssociationNote.where(conditions) end def clone_with_names new_feature = Feature.create(fid: Feature.generate_pid, is_blank: false, is_public: false, skip_update: true) names = self.names names_to_clones = Hash.new names.each do |name| cloned = name.dup cloned.feature = new_feature cloned.skip_update = true cloned.save names_to_clones[name.id] = cloned end relations = Array.new names.each { |name| name.relations.each { |relation| relations << relation if !relations.include? relation } } relations.each do |relation| new_relation = relation.dup new_relation.child_node = names_to_clones[new_relation.child_node.id] new_relation.parent_node = names_to_clones[new_relation.parent_node.id] new_relation.skip_update = true new_relation.save end new_feature.update_name_positions names.each{ |name| name.update_hierarchy } return new_feature end def summary current_language = Language.current current_language.nil? ? nil : self.summaries.find_by(language_id: current_language.id) end def caption current_language = Language.current current_language.nil? ? nil : self.captions.find_by(language_id: current_language.id) end def affiliations_by_user(user, options = {}) Affiliation.where(options.merge(feature_id: self.id, collection_id: user.collections.collect(&:id))) end def authorized?(user, options = {}) !affiliations_by_user(user, options).empty? end def authorized_for_descendants?(user) !affiliations_by_user(user, descendants: true).empty? end # Override uid to use fid instead of id def uid "#{Feature.uid_prefix}-#{self.fid}" end def uid_i self.fid*100 + Feature.uid_code end def related_features_count response = Feature.search_by("{!child of=block_type:parent}id:#{self.uid}", group: true, 'group.field': 'block_child_type', 'group.limit': 0)['grouped']['block_child_type'] response['matches'] > 0 ? response['groups'].select{|group| group['groupValue'] == "related_#{Feature.uid_prefix}"}.first['doclist']['numFound'] : 0 end def related_features_counts full_response = Feature.search_by("{!child of=block_type:parent}id:#{self.uid}", group: true, 'group.field': 'block_child_type', 'group.limit': 0, facet: true, 'facet.field': 'related_kmaps_node_type') response = full_response['grouped']['block_child_type'] facet_response = full_response['facet_counts']['facet_fields']['related_kmaps_node_type'] facet_hash = facet_response.each_slice(2).to_a.to_h { related_features: response['matches'] > 0 ? response['groups'].select{|group| group['groupValue'] == "related_#{Feature.uid_prefix}"}.first['doclist']['numFound'] : 0, parents: facet_hash['parent'], children: facet_hash['child'] } end def self.associated_models @@associated_models end # # # def self.current_roots(current_perspective, current_view) feature_ids = Rails.cache.fetch("features/current_roots/#{current_perspective.id if !current_perspective.nil?}/#{current_view.id if !current_view.nil?}", expires_in: 1.day) do joins(cached_feature_names: :feature_name).where(is_blank: false, cached_feature_names: {view_id: current_view.id}).order('feature_names.name').roots.find_all do |r| # self.includes(cached_feature_names: :feature_name).references(cached_feature_names: :feature_name).where(is_blank: false, cached_feature_names: {view_id: current_view.id}).order('feature_names.name').scoping do # roots.find_all do |r| # if ANY of the child relations are current, return true to nab this Feature r.child_relations.any? {|cr| cr.perspective==current_perspective } end.collect(&:id) # end end feature_ids.collect{ |fid| Feature.find(fid) }.sort_by{ |f| [f.position, f.prioritized_name(current_view).name] } end def self.current_roots_by_perspective(current_perspective) return super if defined?(super) feature_ids = Rails.cache.fetch("features/current_roots/#{current_perspective.id}", expires_in: 1.day) do self.where('features.is_blank' => false).scoping do self.roots.select do |r| # if ANY of the child relations are current, return true to nab this Feature r.child_relations.any? {|cr| cr.perspective==current_perspective } end end.collect(&:id) end feature_ids.collect{ |fid| Feature.find(fid) } end # currently only option accepted is 'only_hierarchical' def self.descendants_with_parent(fids) pending = fids.collect{|fid| Feature.get_by_fid(fid)} des = pending.collect{|f| [f, nil]} des_ids = pending.collect(&:id) while !pending.empty? e = pending.pop FeatureRelation.where(parent_node_id: e.id).each do |r| c = r.child_node if !des_ids.include? c.id des_ids << c.id des << [c, e, r] pending.push(c) end end end des end def self.recursive_descendants_with_depth(fids) res = [] fids.each do |fid| f = Feature.get_by_fid(fid) res += f.recursive_descendants_with_depth end res end def self.recursive_descendants_by_perspective_with_depth(fids, perspective) res = [] fids.each do |fid| f = Feature.get_by_fid(fid) res += f.recursive_descendants_by_perspective_with_depth(perspective) end res end # currently only option accepted is 'only_hierarchical' def self.descendants_by_perspective_with_parent(fids, perspective, options ={}) pending = fids.collect{|fid| Feature.get_by_fid(fid)} des = pending.collect{|f| [f, nil]} des_ids = pending.collect(&:id) conditions = {perspective_id: perspective.id} conditions[:feature_relation_type_id] = FeatureRelationType.hierarchy_ids if options[:only_hierarchical] while !pending.empty? e = pending.pop conditions[:parent_node_id] = e.id FeatureRelation.where(conditions).each do |r| c = r.child_node if !des_ids.include? c.id des_ids << c.id des << [c, e, r] pending.push(c) end end end des end def self.generate_pid KmapsEngine::FeaturePidGenerator.next end # # given a "context_id" (Feature.id), this method only searches # the context's descendants. It returns an array # where the first element is the context Feature # and the second element is the collection of matching descendants. # # context_id - the id of a Feature # filter - any string filter value # options - the standard find(:all) options # def self.contextual_search(string_context_id, filter, search_options={}) context_id = string_context_id.to_i # for some reason this parameter has been especially susceptible to SQL injection attack payload results = self.search(filter, search_options) results = results.where(['(features.id = ? OR features.ancestor_ids LIKE ?)', context_id, "%.#{context_id}.%"]) if !context_id.blank? # the context feature might not be returned # use detect to find a feature.id match against the context_id # if it isn't found, just do a standard find: context_feature = results.detect {|i| i.id.to_s==context_id} || find(context_id) rescue nil [context_feature, results] end # # A basic search method that uses a single value for filtering on multiple columns # filter_value is used as the value to filter on # options - the standard arguments sent to ActiveRecord::Base.paginate (WillPaginate gem) # See http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001416 # def self.search(search) # Setup the base rules if search.scope && search.scope == 'name' conditions = build_like_conditions(%W(feature_names.name), search.filter, {match: search.match}) else conditions = build_like_conditions(%W(descriptions.content feature_names.name), search.filter, {match: search.match}) end if !conditions.blank? fid = search.filter.gsub(/[^\d]/, '') if !fid.blank? conditions[0] << ' OR features.fid = ?' conditions << fid.to_i end end search_results = self.where(conditions).includes([:names, :descriptions]).references([:names, :descriptions]).order('features.position') search_results = search_results.where('descriptions.content IS NOT NULL') if search.has_descriptions return search_results end def self.name_search(filter_value) Feature.includes(:names).references(:names).where(['features.is_public = ? AND feature_names.name ILIKE ?', 1, "%#{filter_value}%"]).order('features.position') end def self.blank Feature.all.reject{|f| f.associated? } end def self.associated Feature.all.select{|f| f.associated? } end def self.get_by_fid(fid) key = "features-fid/#{fid}" feature_id = Rails.cache.fetch(key, expires_in: 1.day) do feature = self.find_by(fid: fid) feature.nil? ? nil : feature.id end # TODO: this won't be necessary when upgrading to rails 6.0 using skip_nil if feature_id.nil? Rails.cache.delete(key) return nil else return Feature.find(feature_id) end end def feature self end private def document_for_rsolr doc = defined?(super) ? super : nested_documents_for_rsolr v = View.get_by_code(KmapsEngine::ApplicationSettings.default_view_code) doc[:id] = self.uid doc[:uid_i] = self.uid_i name = self.prioritized_name(v) doc[:header] = name.nil? ? self.pid : name.name doc[:position_i] = self.position doc[:projects_ss] = self.affiliations.collect{ |a| a.collection.code } time_units = self.time_units_ordered_by_date.collect { |t| t.to_s } doc[:time_units_ss] = time_units if !time_units.blank? self.captions.each do |c| if doc["caption_#{c.language.code}"].blank? doc["caption_#{c.language.code}"] = [c.content] else doc["caption_#{c.language.code}"] << c.content end doc["caption_#{c.language.code}_#{c.id}_content_t"] = c.content citation_references = c.citations.collect { |ci| ci.bibliographic_reference } doc["caption_#{c.language.code}_#{c.id}_citation_references_ss"] = citation_references if !citation_references.blank? end mandala_text_mapping = Language.mandala_text_mappings.invert self.essays.each do |e| doc["homepage_text_#{mandala_text_mapping[e.language.id]}_s"] = e.text_id end self.summaries.each do |s| if doc["summary_#{s.language.code}"].blank? doc["summary_#{s.language.code}"] = [s.content] else doc["summary_#{s.language.code}"] << s.content end doc["summary_#{s.language.code}_#{s.id}_content_t"] = s.content citation_references = s.citations.collect { |c| c.bibliographic_reference } doc["summary_#{s.language.code}_#{s.id}_citation_references_ss"] = citation_references if !citation_references.blank? end # just adding main illustration i = self.illustration if !i.nil? p = i.picture doc["illustration_#{p.instance_of?(ExternalPicture) ? 'external' : 'mms'}_url"] = p.url end doc[:created_at] = self.created_at.utc.iso8601 doc[:updated_at] = self.updated_at.utc.iso8601 Perspective.where(is_public: true).each do |p| #['cult.reg', 'pol.admin.hier'].collect{ |code| Perspective.get_by_code(code) } tag = 'ancestors_' id_tag = 'ancestor_ids_' uid_tag = 'ancestor_uids_' hierarchy = self.ancestors_by_perspective(p) if hierarchy.blank? hierarchy = self.closest_ancestors_by_perspective(p) doc["ancestor_id_closest_#{p.code}_path"] = hierarchy.collect(&:fid).join('/') doc["level_closest_#{p.code}_i"] = hierarchy.size tag << 'closest_' id_tag << 'closest_' uid_tag << 'closest_' closest_fid = self.closest_hierarchical_feature_id_by_perspective(p) closest_ancestor_in_tree = closest_fid.nil? ? nil : Feature.find(closest_fid) path = closest_ancestor_in_tree.nil? ? [] : closest_ancestor_in_tree.ancestors_by_perspective(p).collect(&:fid) else path = hierarchy.collect(&:fid) doc["level_#{p.code}_i"] = path.size end tag << p.code id_tag << p.code uid_tag << p.code doc["ancestor_id_#{p.code}_path"] = path.join('/') doc[tag] = hierarchy.collect do |f| pn = f.prioritized_name(v) pn.nil? ? f.fid : pn.name end doc[id_tag] = hierarchy.collect{ |f| f.fid } doc[uid_tag] = hierarchy.collect{ |f| f.uid } end #name_ids = [] #names = self.names #names.each do |name| View.all.each do |v| name = self.prioritized_name(v) if !name.nil? #&& !name_ids.include?(name.id) #name_ids << name.id key_arr = ['name', v.code] #name.language.code] #rel_code = name.relationship_code #key_arr << rel_code if !rel_code.nil? #ws = name.writing_system #key_arr << ws.code if !ws.nil? key_str = key_arr.join('_') #if doc[key_str].blank? doc[key_str] = [name.name.s] #else #doc[key_str] << name.name #end end end names = self.names names.select(:writing_system_id).distinct.collect(&:writing_system).each do |w| next if w.nil? key_arr = ['name', w.code] #name.language.code] key_str = key_arr.join('_') names.where(writing_system: w).each do |name| if doc[key_str].blank? doc[key_str] = [name.name] else doc[key_str] << name.name end end end geo_codes = self.geo_codes geo_codes.each do |c| doc["code_#{c.geo_code_type.code}_value_s"] = c.geo_code_value citation_references = c.citations.collect { |c| c.bibliographic_reference } doc["code_#{c.geo_code_type.code}_citation_references_ss"] = citation_references if !citation_references.blank? time_units = c.time_units_ordered_by_date.collect { |t| t.to_s } doc["code_#{c.geo_code_type.code}_time_units_ss"] = time_units if !time_units.blank? c.notes.each { |n| n.rsolr_document_tags(doc, "code_#{c.geo_code_type.code}") } end child_documents = doc['_childDocuments_'] name_documents = names.recursive_roots_with_path.collect do |np| name = np.first path = np.second uid = "#{FeatureName.uid_prefix}-#{name.id}" writing_system = name.writing_system prefix = "related_#{FeatureName.uid_prefix}" child_document = { id: "#{self.uid}_#{uid}", origin_uid_s: self.uid, block_child_type: ["related_names"], #tree: FeatureName.uid_prefix, "#{prefix}_id_s" => uid, "#{prefix}_header_s" => name.name, "#{prefix}_path_s" => path.join('/'), "#{prefix}_level_i" => path.size, "#{prefix}_language_s" => name.language.name, "#{prefix}_relationship_s" => name.pp_display_string, block_type: ['child'] } citation_references = name.citations.collect { |c| c.bibliographic_reference } child_document["#{prefix}_citation_references_ss"] = citation_references if !citation_references.blank? time_units = name.time_units_ordered_by_date.collect { |t| t.to_s } child_document["#{prefix}_time_units_ss"] = time_units if !time_units.blank? name.notes.each { |n| n.rsolr_document_tags(child_document, prefix) } name.parent_relations.each do |r| citation_references = r.nil? ? nil : r.citations.collect { |c| c.bibliographic_reference } child_document["#{prefix}_relationship_#{r.id}_citation_references_ss"] = citation_references if !citation_references.blank? r.notes.each { |n| n.rsolr_document_tags(child_document, "#{prefix}_relationship_#{r.id}") } end etymology = name.etymology child_document["#{prefix}_etymology_s"] = etymology if !etymology.blank? if !writing_system.nil? child_document["#{prefix}_writing_system_s"] = writing_system.name child_document["#{prefix}_writing_system_code_s"] = writing_system.code end child_document end child_documents += name_documents doc['_childDocuments_'] = child_documents doc end def nested_documents_for_rsolr per = Perspective.get_by_code(KmapsEngine::ApplicationSettings.default_perspective_code) v = View.get_by_code(KmapsEngine::ApplicationSettings.default_view_code) hierarchy = self.closest_ancestors_by_perspective(per) prefix = "related_#{Feature.uid_prefix}" doc = { tree: Feature.uid_prefix, block_type: ['parent'], '_childDocuments_' => self.all_parent_relations.collect do |pr| name = pr.parent_node.prioritized_name(v) name_str = name.nil? ? pr.parent_node.pid : name.name parent = pr.parent_node relation_tag = { id: "#{self.uid}_#{pr.feature_relation_type.code}_#{parent.fid}", related_uid_s: parent.uid, origin_uid_s: self.uid, block_child_type: [prefix], "#{prefix}_id_s" => parent.uid, "#{prefix}_header_s" => name_str, "#{prefix}_path_s" => pr.parent_node.closest_ancestors_by_perspective(per).collect(&:fid).join('/'), "#{prefix}_relation_label_s" => pr.feature_relation_type.asymmetric_label, "#{prefix}_relation_code_s" => pr.feature_relation_type.code, related_kmaps_node_type: 'parent', block_type: ['child'] } p_rel_citation_references = pr.citations.collect { |c| c.bibliographic_reference } relation_tag["#{prefix}_relation_citation_references_ss"] = p_rel_citation_references if !p_rel_citation_references.blank? time_units = pr.time_units_ordered_by_date.collect { |t| t.to_s } relation_tag["#{prefix}_relation_time_units_ss"] = time_units if !time_units.blank? pr.notes.each { |n| n.rsolr_document_tags(relation_tag, prefix) } relation_tag end + self.all_child_relations.collect do |pr| name = pr.child_node.prioritized_name(v) name_str = name.nil? ? pr.child_node.pid : name.name child = pr.child_node relation_tag = { id: "#{self.uid}_#{pr.feature_relation_type.asymmetric_code}_#{child.fid}", related_uid_s: child.uid, origin_uid_s: self.uid, block_child_type: [prefix], "#{prefix}_id_s" => "#{Feature.uid_prefix}-#{child.fid}", "#{prefix}_header_s" => name_str, "#{prefix}_path_s" => pr.child_node.closest_ancestors_by_perspective(per).collect(&:fid).join('/'), "#{prefix}_relation_label_s" => pr.feature_relation_type.label, "#{prefix}_relation_code_s" => pr.feature_relation_type.asymmetric_code, related_kmaps_node_type: 'child', block_type: ['child'] } p_rel_citation_references = pr.citations.collect { |c| c.bibliographic_reference } relation_tag["#{prefix}_relation_citation_references_ss"] = p_rel_citation_references if !p_rel_citation_references.blank? time_units = pr.time_units_ordered_by_date.collect { |t| t.to_s } relation_tag["#{prefix}_relation_time_units_ss"] = time_units if !time_units.blank? pr.notes.each { |n| n.rsolr_document_tags(relation_tag, prefix) } relation_tag end } doc end def self.name_search_options(filter_value, options = {}) end end
41.885787
307
0.689935
62b4deaa994db20bf39cb737bd98d4a67ce2217c
850
require 'spec_helper' describe Facebook::Messenger::Incoming::Messaging::PassThreadControl do let :payload do { 'sender' => { 'id' => '3' }, 'recipient' => { 'id' => '3' }, 'timestamp' => 1_458_692_752_478, 'pass_thread_control' => { 'new_owner_app_id' => '123456789', 'metadata' => 'Additional content that the caller wants to set' } } end subject { described_class.new(payload) } describe '.new_owner_app_id' do it 'returns the new owner app id' do expect(subject.new_owner_app_id).to eq( payload['pass_thread_control']['new_owner_app_id'] ) end end describe '.metadata' do it 'returns the metadata' do expect(subject.metadata).to eq( payload['pass_thread_control']['metadata'] ) end end end
22.368421
71
0.596471
e9cb913d5e5db8f2393598ee85fcad22168611a7
89
# desc "Explaining what the task does" # task :welcome_css do # # Task goes here # end
17.8
38
0.685393
6a8dccda3a42272f05702c8eb0d53eb9bc51ec73
15,921
require 'linguist/language' require 'test/unit' require 'pygments' class TestLanguage < Test::Unit::TestCase include Linguist Lexer = Pygments::Lexer def test_ambiguous_extensions assert Language.ambiguous?('.cls') assert_equal Language['TeX'], Language.find_by_extension('cls') assert Language.ambiguous?('.h') assert_equal Language['C'], Language.find_by_extension('h') assert Language.ambiguous?('.m') assert_equal Language['Objective-C'], Language.find_by_extension('m') assert Language.ambiguous?('.pl') assert_equal Language['Perl'], Language.find_by_extension('pl') assert Language.ambiguous?('.r') assert_equal Language['R'], Language.find_by_extension('r') assert Language.ambiguous?('.t') assert_equal Language['Perl'], Language.find_by_extension('t') assert Language.ambiguous?('.v') assert_equal Language['Verilog'], Language.find_by_extension('v') end def test_lexer assert_equal Lexer['ActionScript 3'], Language['ActionScript'].lexer assert_equal Lexer['Bash'], Language['Gentoo Ebuild'].lexer assert_equal Lexer['Bash'], Language['Gentoo Eclass'].lexer assert_equal Lexer['Bash'], Language['Shell'].lexer assert_equal Lexer['C'], Language['OpenCL'].lexer assert_equal Lexer['C'], Language['XS'].lexer assert_equal Lexer['C++'], Language['C++'].lexer assert_equal Lexer['Coldfusion HTML'], Language['ColdFusion'].lexer assert_equal Lexer['Coq'], Language['Coq'].lexer assert_equal Lexer['Fortran'], Language['FORTRAN'].lexer assert_equal Lexer['Gherkin'], Language['Cucumber'].lexer assert_equal Lexer['HTML'], Language['HTML'].lexer assert_equal Lexer['HTML+Django/Jinja'], Language['HTML+Django'].lexer assert_equal Lexer['HTML+PHP'], Language['HTML+PHP'].lexer assert_equal Lexer['Java'], Language['ChucK'].lexer assert_equal Lexer['Java'], Language['Groovy'].lexer assert_equal Lexer['Java'], Language['Java'].lexer assert_equal Lexer['JavaScript'], Language['JSON'].lexer assert_equal Lexer['JavaScript'], Language['JavaScript'].lexer assert_equal Lexer['MOOCode'], Language['Moocode'].lexer assert_equal Lexer['MuPAD'], Language['mupad'].lexer assert_equal Lexer['NASM'], Language['Assembly'].lexer assert_equal Lexer['OCaml'], Language['F#'].lexer assert_equal Lexer['OCaml'], Language['OCaml'].lexer assert_equal Lexer['OpenEdge ABL'], Language['OpenEdge ABL'].lexer assert_equal Lexer['Standard ML'], Language['Standard ML'].lexer assert_equal Lexer['Ooc'], Language['ooc'].lexer assert_equal Lexer['REBOL'], Language['Rebol'].lexer assert_equal Lexer['RHTML'], Language['HTML+ERB'].lexer assert_equal Lexer['RHTML'], Language['RHTML'].lexer assert_equal Lexer['Ruby'], Language['Mirah'].lexer assert_equal Lexer['Ruby'], Language['Ruby'].lexer assert_equal Lexer['S'], Language['R'].lexer assert_equal Lexer['Scheme'], Language['Emacs Lisp'].lexer assert_equal Lexer['Scheme'], Language['Nu'].lexer assert_equal Lexer['Scheme'], Language['Racket'].lexer assert_equal Lexer['Scheme'], Language['Scheme'].lexer assert_equal Lexer['TeX'], Language['TeX'].lexer assert_equal Lexer['Text only'], Language['Text'].lexer assert_equal Lexer['Verilog'], Language['Verilog'].lexer assert_equal Lexer['aspx-vb'], Language['ASP'].lexer assert_equal Lexer['haXe'], Language['HaXe'].lexer assert_equal Lexer['reStructuredText'], Language['reStructuredText'].lexer end def test_find_by_alias assert_equal Language['ASP'], Language.find_by_alias('asp') assert_equal Language['ASP'], Language.find_by_alias('aspx') assert_equal Language['ASP'], Language.find_by_alias('aspx-vb') assert_equal Language['ActionScript'], Language.find_by_alias('as3') assert_equal Language['Assembly'], Language.find_by_alias('nasm') assert_equal Language['Batchfile'], Language.find_by_alias('bat') assert_equal Language['C#'], Language.find_by_alias('c#') assert_equal Language['C#'], Language.find_by_alias('csharp') assert_equal Language['C'], Language.find_by_alias('c') assert_equal Language['C++'], Language.find_by_alias('c++') assert_equal Language['C++'], Language.find_by_alias('cpp') assert_equal Language['CoffeeScript'], Language.find_by_alias('coffee') assert_equal Language['ColdFusion'], Language.find_by_alias('cfm') assert_equal Language['Common Lisp'], Language.find_by_alias('common-lisp') assert_equal Language['Common Lisp'], Language.find_by_alias('lisp') assert_equal Language['Darcs Patch'], Language.find_by_alias('dpatch') assert_equal Language['Emacs Lisp'], Language.find_by_alias('elisp') assert_equal Language['Emacs Lisp'], Language.find_by_alias('emacs') assert_equal Language['Emacs Lisp'], Language.find_by_alias('emacs-lisp') assert_equal Language['Gettext Catalog'], Language.find_by_alias('pot') assert_equal Language['HTML'], Language.find_by_alias('html') assert_equal Language['HTML+ERB'], Language.find_by_alias('html+erb') assert_equal Language['IRC log'], Language.find_by_alias('irc') assert_equal Language['JSON'], Language.find_by_alias('json') assert_equal Language['Java Server Pages'], Language.find_by_alias('jsp') assert_equal Language['Java'], Language.find_by_alias('java') assert_equal Language['JavaScript'], Language.find_by_alias('javascript') assert_equal Language['JavaScript'], Language.find_by_alias('js') assert_equal Language['Literate Haskell'], Language.find_by_alias('lhs') assert_equal Language['Literate Haskell'], Language.find_by_alias('literate-haskell') assert_equal Language['OpenEdge ABL'], Language.find_by_alias('openedge') assert_equal Language['OpenEdge ABL'], Language.find_by_alias('progress') assert_equal Language['OpenEdge ABL'], Language.find_by_alias('abl') assert_equal Language['Parrot Internal Representation'], Language.find_by_alias('pir') assert_equal Language['Powershell'], Language.find_by_alias('posh') assert_equal Language['Puppet'], Language.find_by_alias('puppet') assert_equal Language['Pure Data'], Language.find_by_alias('pure-data') assert_equal Language['Raw token data'], Language.find_by_alias('raw') assert_equal Language['Ruby'], Language.find_by_alias('rb') assert_equal Language['Ruby'], Language.find_by_alias('ruby') assert_equal Language['Scheme'], Language.find_by_alias('scheme') assert_equal Language['Shell'], Language.find_by_alias('bash') assert_equal Language['Shell'], Language.find_by_alias('sh') assert_equal Language['Shell'], Language.find_by_alias('shell') assert_equal Language['Shell'], Language.find_by_alias('zsh') assert_equal Language['TeX'], Language.find_by_alias('tex') assert_equal Language['VimL'], Language.find_by_alias('vim') assert_equal Language['VimL'], Language.find_by_alias('viml') assert_equal Language['reStructuredText'], Language.find_by_alias('rst') end def test_groups # Test a couple identity cases assert_equal Language['Perl'], Language['Perl'].group assert_equal Language['Python'], Language['Python'].group assert_equal Language['Ruby'], Language['Ruby'].group # Test a few special groups assert_equal Language['Assembly'], Language['GAS'].group assert_equal Language['C'], Language['OpenCL'].group assert_equal Language['Haskell'], Language['Literate Haskell'].group assert_equal Language['Java'], Language['Java Server Pages'].group assert_equal Language['Python'], Language['Cython'].group assert_equal Language['Python'], Language['NumPy'].group assert_equal Language['Shell'], Language['Batchfile'].group assert_equal Language['Shell'], Language['Gentoo Ebuild'].group assert_equal Language['Shell'], Language['Gentoo Eclass'].group assert_equal Language['Shell'], Language['Tcsh'].group # Ensure everyone has a group Language.all.each do |language| assert language.group, "#{language} has no group" end end # Used for code search indexing. Changing any of these values may # require reindexing repositories. def test_search_term assert_equal 'perl', Language['Perl'].search_term assert_equal 'python', Language['Python'].search_term assert_equal 'ruby', Language['Ruby'].search_term assert_equal 'common-lisp', Language['Common Lisp'].search_term assert_equal 'html+erb', Language['HTML+ERB'].search_term assert_equal 'max/msp', Language['Max/MSP'].search_term assert_equal 'puppet', Language['Puppet'].search_term assert_equal 'pure-data', Language['Pure Data'].search_term assert_equal 'aspx-vb', Language['ASP'].search_term assert_equal 'as3', Language['ActionScript'].search_term assert_equal 'nasm', Language['Assembly'].search_term assert_equal 'bat', Language['Batchfile'].search_term assert_equal 'csharp', Language['C#'].search_term assert_equal 'cpp', Language['C++'].search_term assert_equal 'cfm', Language['ColdFusion'].search_term assert_equal 'dpatch', Language['Darcs Patch'].search_term assert_equal 'ocaml', Language['F#'].search_term assert_equal 'pot', Language['Gettext Catalog'].search_term assert_equal 'irc', Language['IRC log'].search_term assert_equal 'lhs', Language['Literate Haskell'].search_term assert_equal 'ruby', Language['Mirah'].search_term assert_equal 'raw', Language['Raw token data'].search_term assert_equal 'bash', Language['Shell'].search_term assert_equal 'vim', Language['VimL'].search_term assert_equal 'jsp', Language['Java Server Pages'].search_term assert_equal 'rst', Language['reStructuredText'].search_term end def test_popular assert Language['Ruby'].popular? assert Language['Perl'].popular? assert Language['Python'].popular? assert Language['Assembly'].unpopular? assert Language['Brainfuck'].unpopular? end def test_programming assert_equal :programming, Language['JavaScript'].type assert_equal :programming, Language['Perl'].type assert_equal :programming, Language['Powershell'].type assert_equal :programming, Language['Python'].type assert_equal :programming, Language['Ruby'].type end def test_markup assert_equal :markup, Language['HTML'].type assert_equal :markup, Language['YAML'].type end def test_other assert_nil Language['Brainfuck'].type assert_nil Language['Makefile'].type end def test_searchable assert Language['Ruby'].searchable? assert !Language['Gettext Catalog'].searchable? assert !Language['SQL'].searchable? end def test_find_by_name ruby = Language['Ruby'] assert_equal ruby, Language.find_by_name('Ruby') end def test_find_all_by_name Language.all.each do |language| assert_equal language, Language.find_by_name(language.name) assert_equal language, Language[language.name] end end def test_find_all_by_alias Language.all.each do |language| language.aliases.each do |name| assert_equal language, Language.find_by_alias(name) assert_equal language, Language[name] end end end def test_find_by_extension assert_equal Language['Ruby'], Language.find_by_extension('.rb') assert_equal Language['Ruby'], Language.find_by_extension('rb') assert_equal Language['Groff'], Language.find_by_extension('man') assert_equal Language['Groff'], Language.find_by_extension('1') assert_equal Language['Groff'], Language.find_by_extension('2') assert_equal Language['Groff'], Language.find_by_extension('3') assert_equal Language['PHP'], Language.find_by_extension('php') assert_equal Language['PHP'], Language.find_by_extension('php3') assert_equal Language['PHP'], Language.find_by_extension('php4') assert_equal Language['PHP'], Language.find_by_extension('php5') assert_equal Language['Powershell'], Language.find_by_extension('psm1') assert_equal Language['Powershell'], Language.find_by_extension('ps1') assert_nil Language.find_by_extension('.kt') end def test_find_all_by_extension Language.all.each do |language| language.extensions.each do |extension| unless Language.ambiguous?(extension) assert_equal language, Language.find_by_extension(extension) end end end end def test_find_by_filename assert_equal Language['Ruby'], Language.find_by_filename('foo.rb') assert_equal Language['Ruby'], Language.find_by_filename('foo/bar.rb') assert_equal Language['Ruby'], Language.find_by_filename('Rakefile') assert_nil Language.find_by_filename('rb') assert_nil Language.find_by_filename('.rb') assert_nil Language.find_by_filename('.kt') end def test_find assert_equal 'Ruby', Language['Ruby'].name assert_equal 'Ruby', Language['ruby'].name assert_equal 'C++', Language['C++'].name assert_equal 'C++', Language['c++'].name assert_equal 'C++', Language['cpp'].name assert_equal 'C#', Language['C#'].name assert_equal 'C#', Language['c#'].name assert_equal 'C#', Language['csharp'].name assert_nil Language['defunkt'] end def test_name assert_equal 'Perl', Language['Perl'].name assert_equal 'Python', Language['Python'].name assert_equal 'Ruby', Language['Ruby'].name end def test_escaped_name assert_equal 'C', Language['C'].escaped_name assert_equal 'C%23', Language['C#'].escaped_name assert_equal 'C%2B%2B', Language['C++'].escaped_name assert_equal 'Objective-C', Language['Objective-C'].escaped_name assert_equal 'Common%20Lisp', Language['Common Lisp'].escaped_name assert_equal 'Max%2FMSP', Language['Max/MSP'].escaped_name end def test_error_without_name assert_raise ArgumentError do Language.new :name => nil end end def test_ace_mode assert_equal 'c_cpp', Language['C++'].ace_mode assert_equal 'coffee', Language['CoffeeScript'].ace_mode assert_equal 'csharp', Language['C#'].ace_mode assert_equal 'css', Language['CSS'].ace_mode assert_equal 'javascript', Language['JavaScript'].ace_mode assert_equal 'text', Language['Text'].ace_mode end def test_ace_modes assert Language.ace_modes.include?(Language['Text']) assert Language.ace_modes.include?(Language['Ruby']) assert !Language.ace_modes.include?(Language['FORTRAN']) end def test_extensions assert Language['Perl'].extensions.include?('.pl') assert Language['Python'].extensions.include?('.py') assert Language['Ruby'].extensions.include?('.rb') end def test_primary_extension assert_equal '.pl', Language['Perl'].primary_extension assert_equal '.py', Language['Python'].primary_extension assert_equal '.rb', Language['Ruby'].primary_extension # This is a nasty requirement, but theres some code in GitHub that # expects this. Really want to drop this. Language.all.each do |language| assert language.primary_extension, "#{language} has no primary extension" end end def test_eql assert Language['Ruby'].eql?(Language['Ruby']) assert !Language['Ruby'].eql?(Language['Python']) assert !Language['Ruby'].eql?(Language.new(:name => 'Ruby')) end def test_colorize assert_equal <<-HTML, Language['Text'].colorize("Hello") <div class="highlight"><pre>Hello </pre> </div> HTML assert_equal <<-HTML, Language['Ruby'].colorize("def foo\n 'foo'\nend\n") <div class="highlight"><pre><span class="k">def</span> <span class="nf">foo</span> <span class="s1">&#39;foo&#39;</span> <span class="k">end</span> </pre> </div> HTML end end
43.619178
90
0.71189
7ab717093cc6949b6d0db31fab7a5e1820ed07d7
2,779
require 'spec_helper' require 'hanami_request_test' RSpec.describe 'API influencers', type: :request, vcr: true do include HanamiRequestTest subject { last_json_response } let(:endpoint) { '/api' } context 'when searching for :name' do context 'when no result is found' do it 'returns an empty :data[:influencers] list' do post endpoint, query: '{ influencers(name: "Socrates") { people { id } events { id } } }' expect(last_json_response[:data][:influencers][:people]).to be_empty expect(last_json_response[:data][:influencers][:events]).to be_empty end end context 'with an incomplete name as argument' do context 'when some people are found' do let(:influencer01) { build :person, id: 1, name: 'Dom Pedro I', earliest_date: Date.new(1000, 1, 1) } let(:influencer02) { build :person, id: 2, name: 'Dom Pedro II', earliest_date: Date.new(1100, 1, 1) } let(:event) { build :event, id: 1, name: 'Pedro War', earliest_date: Date.new(1050, 1, 1) } def index_people(people) Influencers::Indexer.new(influencers: people, index_object: Influencers::PersonIndexObject).save end def index_event Influencers::Indexer.new(influencers: [event], index_object: Influencers::EventIndexObject).save end before do index_people([influencer01, influencer02]) index_event post endpoint, query: '{ influencers(name: "Pedro") { people { id name gender type earliest_date } ' \ 'events { id name type earliest_date } } }' end after { database_clean } it 'returns a list of influencers' do expect(last_json_response[:data][:influencers][:people].count).to eq 2 expect(last_json_response[:data][:influencers][:events].count).to eq 1 expect(last_json_response[:data][:influencers][:people][0]).to eq( id: influencer02.id, name: influencer02.name, gender: influencer02.gender, type: influencer02.type.to_s.downcase, earliest_date: influencer02.earliest_date.to_s ) expect(last_json_response[:data][:influencers][:people][1]).to eq( id: influencer01.id, name: influencer01.name, gender: influencer01.gender, type: influencer01.type.to_s.downcase, earliest_date: influencer01.earliest_date.to_s ) expect(last_json_response[:data][:influencers][:events][0]).to eq( id: event.id, name: event.name, type: event.type.to_s.downcase, earliest_date: event.earliest_date.to_s ) end end end end end
37.554054
110
0.619288
d5a4d1fe3e43ab8773c2483fc3f32f3bf885367c
472
# loop - class Loop - command loop - repeats block until break called class Loop < BaseCommand def call(*args, env:, frames:) if args[0].instance_of? Block result = true block = args[0] begin loop { result = block.call env: env, frames: frames } rescue VirtualMachine::BreakCalled return true end result else env[:err].puts 'loop: first argument must be a block' result = false end end end
22.47619
69
0.614407
2171e84f044fba07731c82ad7ba37d5dfd1efa2e
84
FactoryBot.define do sequence :email do |n| "email#{n}@example.com" end end
14
27
0.666667
f758706dd7e5a78d79d15a1c66768bac52a4ee2f
1,681
# frozen_string_literal: true require_relative "../adapter" module Lita # A namespace to hold all subclasses of {Adapter}. module Adapters # An adapter for testing Lita and Lita plugins. # @since 4.6.0 class Test < Adapter # When true, calls to {#run_concurrently} will block the current thread. This is the default # because it's desirable for the majority of tests. It should be set to +false+ for tests # specifically testing asynchrony. config :blocking, types: [TrueClass, FalseClass], default: true # Adapter-specific methods exposed through {Robot}. class ChatService def initialize(sent_messages) @sent_messages = sent_messages end # An array of recorded outgoing messages. def sent_messages @sent_messages.dup end end def initialize(robot) super self.sent_messages = [] end # Adapter-specific methods available via {Robot#chat_service}. def chat_service ChatService.new(sent_messages) end # Records outgoing messages. def send_messages(_target, strings) sent_messages.concat(strings) end # If the +blocking+ config attribute is +true+ (which is the default), the block will be run # on the current thread, so tests can be written without concern for asynchrony. def run_concurrently(&block) if config.blocking block.call else super end end private # An array of recorded outgoing messages. attr_accessor :sent_messages end Lita.register_adapter(:test, Test) end end
26.68254
98
0.649613
1a92eb416bfac0d9838f10dbc7468c0b878871c2
11,327
require 'spec_helper_acceptance' describe 'iis_application' do before(:all) do # Remove 'Default Web Site' to start from a clean slate remove_all_sites(); end context 'when creating an application' do context 'with normal parameters' do before(:all) do @site_name = SecureRandom.hex(10) @app_name = SecureRandom.hex(10) create_path('C:\inetpub\basic') @manifest = <<-HERE iis_site { '#{@site_name}': ensure => 'started', physicalpath => 'C:\\inetpub\\basic', applicationpool => 'DefaultAppPool', } iis_application { '#{@app_name}': ensure => 'present', sitename => '#{@site_name}', physicalpath => 'C:\\inetpub\\basic', } HERE end it_behaves_like 'an idempotent resource' # TestRail ID: C100060 context 'when puppet resource is run' do before(:all) do @result = on(default, puppet('resource', 'iis_application', "#{@site_name}\\\\#{@app_name}")) end include_context 'with a puppet resource run' puppet_resource_should_show('sitename', @site_name) puppet_resource_should_show('physicalpath', 'C:\inetpub\basic') puppet_resource_should_show('applicationpool', 'DefaultAppPool') end after(:all) do remove_app(@app_name) remove_all_sites end end # TestRail ID: C100061 context 'with virtual_directory' do before(:all) do @site_name = SecureRandom.hex(10) @app_name = SecureRandom.hex(10) create_site(@site_name, true) create_path('C:\inetpub\vdir') create_virtual_directory(@site_name, @app_name, 'C:\inetpub\vdir') @manifest = <<-HERE iis_application { '#{@site_name}\\#{@app_name}': ensure => 'present', virtual_directory => 'IIS:\\Sites\\#{@site_name}\\#{@app_name}', } HERE end it_behaves_like 'an idempotent resource' context 'when puppet resource is run' do before(:all) do @result = on(default, puppet('resource', 'iis_application', "#{@site_name}\\\\#{@app_name}")) end include_context 'with a puppet resource run' puppet_resource_should_show('sitename', @site_name) puppet_resource_should_show('physicalpath', 'C:\inetpub\vdir') puppet_resource_should_show('applicationpool', 'DefaultAppPool') end after(:all) do remove_app(@app_name) remove_all_sites end end context 'with nested virtual directory' do before(:all) do @site_name = SecureRandom.hex(10) @app_name = SecureRandom.hex(10) create_site(@site_name, true) create_path("c:\\inetpub\\wwwroot\\subFolder\\#{@app_name}") @manifest = <<-HERE iis_application{'subFolder/#{@app_name}': ensure => 'present', applicationname => 'subFolder/#{@app_name}', physicalpath => 'c:\\inetpub\\wwwroot\\subFolder\\#{@app_name}', sitename => '#{@site_name}' } HERE end it_behaves_like 'an idempotent resource' describe "application validation" do it "should create the correct application" do @result = on(default, puppet('resource', 'iis_application', "#{@site_name}\\\\subFolder/#{@app_name}")) expect(@result.stdout).to match(/(sitename)(\s*)(=>)(\s*)('#{@site_name}'),/) expect(@result.stdout).to match(/iis_application { '#{@site_name}\\subFolder\/#{@app_name}':/) expect(@result.stdout).to match(/ensure\s*=> 'present',/) end end after(:all) do remove_app(@app_name) remove_all_sites end end context 'with nested virtual directory and single namevar' do before(:all) do @site_name = SecureRandom.hex(10) @app_name = SecureRandom.hex(10) create_site(@site_name, true) create_path("c:\\inetpub\\wwwroot\\subFolder\\#{@app_name}") @manifest = <<-HERE iis_application{'subFolder/#{@app_name}': ensure => 'present', physicalpath => 'c:\\inetpub\\wwwroot\\subFolder\\#{@app_name}', sitename => '#{@site_name}' } HERE end it_behaves_like 'an idempotent resource' describe "application validation" do it "should create the correct application" do @result = on(default, puppet('resource', 'iis_application', "#{@site_name}\\\\subFolder/#{@app_name}")) expect(@result.stdout).to match(/(sitename)(\s*)(=>)(\s*)('#{@site_name}'),/) expect(@result.stdout).to match(/iis_application { '#{@site_name}\\subFolder\/#{@app_name}':/) expect(@result.stdout).to match(/ensure\s*=> 'present',/) end end after(:all) do remove_app(@app_name) remove_all_sites end end context 'with incorrect virtual directory name format' do context 'with a leading slash' do before(:all) do @site_name = SecureRandom.hex(10) @app_name = SecureRandom.hex(10) create_site(@site_name, true) create_path("c:\\inetpub\\wwwroot\\subFolder\\#{@app_name}") @manifest = <<-HERE iis_application{'subFolder/#{@app_name}': ensure => 'present', applicationname => '/subFolder/#{@app_name}', physicalpath => 'c:\\inetpub\\wwwroot\\subFolder\\#{@app_name}', sitename => '#{@site_name}' } HERE end # a lading slash in applicationname causes the name matching to fail and runs # loses idempotency. A validation rule was added to prevent this. it_behaves_like 'a failing manifest' after(:all) do remove_app(@app_name) remove_all_sites end end end context 'with two level nested virtual directory' do before(:all) do @site_name = SecureRandom.hex(10) @app_name = SecureRandom.hex(10) create_site(@site_name, true) create_path("c:\\inetpub\\wwwroot\\subFolder\\sub2\\#{@app_name}") @manifest = <<-HERE iis_application{'subFolder/sub2/#{@app_name}': ensure => 'present', applicationname => 'subFolder/sub2/#{@app_name}', physicalpath => 'c:\\inetpub\\wwwroot\\subFolder\\sub2\\#{@app_name}', sitename => '#{@site_name}' } HERE end it_behaves_like 'an idempotent resource' describe "application validation" do it "should create the correct application" do @result = on(default, puppet('resource', 'iis_application', "#{@site_name}\\\\subFolder/sub2/#{@app_name}")) expect(@result.stdout).to match(/(sitename)(\s*)(=>)(\s*)('#{@site_name}'),/) expect(@result.stdout).to match(/iis_application { '#{@site_name}\\subFolder\/sub2\/#{@app_name}':/) expect(@result.stdout).to match(/ensure\s*=> 'present',/) end end after(:all) do remove_app(@app_name) remove_all_sites end end end # TestRail ID: C100062 context 'when setting' do skip 'sslflags - blocked by MODULES-5561' do before(:all) do @site_name = SecureRandom.hex(10) @app_name = SecureRandom.hex(10) create_site(@site_name, true) create_path('C:\inetpub\wwwroot') create_path('C:\inetpub\modify') site_hostname = 'www.puppet.local' thumbprint = create_selfsigned_cert(site_hostname) create_app(@site_name, @app_name, 'C:\inetpub\wwwroot') @manifest = <<-HERE iis_site { '#{@site_name}': ensure => 'started', physicalpath => 'C:\\inetpub\\wwwroot', applicationpool => 'DefaultAppPool', bindings => [ { 'bindinginformation' => '*:80:#{site_hostname}', 'protocol' => 'http', }, { 'bindinginformation' => '*:443:#{site_hostname}', 'protocol' => 'https', 'certificatestorename' => 'MY', 'certificatehash' => '#{thumbprint.downcase}', 'sslflags' => 0, }, ], } iis_application { '#{@app_name}': ensure => 'present', sitename => '#{@site_name}', physicalpath => 'C:\\inetpub\\modify', sslflags => ['Ssl','SslRequireCert'], } HERE end it_behaves_like 'an idempotent resource' end describe 'authenticationinfo' do before(:all) do @site_name = SecureRandom.hex(10) @app_name = SecureRandom.hex(10) create_site(@site_name, true) create_path('C:\inetpub\wwwroot') create_path('C:\inetpub\auth') create_app(@site_name, @app_name, 'C:\inetpub\auth') @manifest = <<-HERE iis_application { '#{@app_name}': ensure => 'present', sitename => '#{@site_name}', physicalpath => 'C:\\inetpub\\auth', authenticationinfo => { 'basic' => true, 'anonymous' => false, }, } HERE end it_behaves_like 'an idempotent resource' end describe 'applicationpool' do before(:all) do @site_name = SecureRandom.hex(10) @app_name = SecureRandom.hex(10) create_site(@site_name, true) create_path('C:\inetpub\wwwroot') create_path('C:\inetpub\auth') create_app(@site_name, @app_name, 'C:\inetpub\auth') create_app_pool('foo_pool') @manifest = <<-HERE iis_application { '#{@app_name}': ensure => 'present', sitename => '#{@site_name}', physicalpath => 'C:\\inetpub\\auth', applicationpool => 'foo_pool' } HERE end it_behaves_like 'an idempotent resource' end end # TestRail ID: C100063 context 'when removing an application' do before(:all) do @site_name = SecureRandom.hex(10) @app_name = SecureRandom.hex(10) create_site(@site_name, true) create_path('C:\inetpub\remove') create_virtual_directory(@site_name, @app_name, 'C:\inetpub\remove') create_app(@site_name, @app_name, 'C:\inetpub\remove') @manifest = <<-HERE iis_application { '#{@app_name}': ensure => 'absent', sitename => '#{@site_name}', physicalpath => 'C:\\inetpub\\remove', } HERE end it_behaves_like 'an idempotent resource' context 'when puppet resource is run' do before(:all) do @result = on(default, puppet('resource', 'iis_application', "#{@site_name}\\\\#{@app_name}")) end include_context 'with a puppet resource run' puppet_resource_should_show('ensure', 'absent') end after(:all) do remove_app(@app_name) end end end
33.81194
118
0.559283
6a908e3cdf078f3800ef4e24313886cc550a8b66
87
class PhonesCarrier < ActiveRecord::Base belongs_to :phone belongs_to :carrier end
17.4
40
0.793103
d599b41a34c71dc3e57006ca0f98e1ca533fbe6a
122
class Cities < ActiveRecord::Migration def change create_table :cities do |t| t.string :name end end end
17.428571
38
0.672131
f80af8f4f27e3be92772df6883c286b41b1cf31b
2,903
module OverSIP::SIP class TlsServer < TcpServer TLS_HANDSHAKE_MAX_TIME = 4 def post_init @client_pems = [] @client_last_pem = false start_tls({ :verify_peer => true, :cert_chain_file => ::OverSIP.tls_public_cert, :private_key_file => ::OverSIP.tls_private_cert, :ssl_version => %w(tlsv1 tlsv1_1 tlsv1_2) }) # If the remote client does never send us a TLS certificate # after the TCP connection we would leak by storing more and # more messages in @pending_messages array. @timer_tls_handshake = ::EM::Timer.new(TLS_HANDSHAKE_MAX_TIME) do unless @connected log_system_notice "TLS handshake not performed within #{TLS_HANDSHAKE_MAX_TIME} seconds, closing the connection" close_connection end end end def ssl_verify_peer pem # TODO: Dirty workaround for bug https://github.com/eventmachine/eventmachine/issues/194. return true if @client_last_pem == pem @client_last_pem = pem @client_pems << pem log_system_debug "received certificate num #{@client_pems.size} from client" if $oversip_debug # Validation must be done in ssl_handshake_completed after receiving all the certs, so return true. return true end def ssl_handshake_completed log_system_info "TLS connection established from " << remote_desc # @connected in TlsServer means "TLS connection" rather than # just "TCP connection". @connected = true @timer_tls_handshake.cancel if @timer_tls_handshake if ::OverSIP::SIP.callback_on_client_tls_handshake # Set the state to :waiting_for_on_client_tls_handshake so data received after TLS handshake but before # user callback validation is just stored. @state = :waiting_for_on_client_tls_handshake # Run OverSIP::SipEvents.on_client_tls_handshake. ::Fiber.new do begin log_system_debug "running OverSIP::SipEvents.on_client_tls_handshake()..." if $oversip_debug ::OverSIP::SipEvents.on_client_tls_handshake self, @client_pems # If the user of the peer has not closed the connection then continue. unless @local_closed or error? @state = :init # Call process_received_data() to process possible data received in the meanwhile. process_received_data else log_system_debug "connection closed, aborting" if $oversip_debug end rescue ::Exception => e log_system_error "error calling OverSIP::SipEvents.on_client_tls_handshake():" log_system_error e close_connection end end.resume end end def unbind cause=nil @timer_tls_handshake.cancel if @timer_tls_handshake super end end end
32.617978
122
0.665518
33e8f1572f55befa440e46ba78a48c463b7dd488
431
# frozen_string_literal: true class UffizziCore::Rating < UffizziCore::ApplicationRecord include AASM self.table_name = Rails.application.config.uffizzi_core[:table_names][:ratings] aasm(:state) do state :active, initial: true state :disabled event :activate do transitions from: [:disabled], to: :active end event :disable do transitions from: [:active], to: :disabled end end end
20.52381
81
0.698376
26e85bef9c7018483d243c32805231f84910add0
1,714
require "fileutils" require_relative 'credential' module UserConfig module Definitions class AzureCredential < Credential def initialize (provider, user_config_query_lambda) super(provider, user_config_query_lambda) end def get_client_id() return query("client_id") end def get_tenant() return query("tenant") end def get_subscription_id() return query("subscription_id") end def get_secret() return query("secret") end def get_ssh_public_key() filepath = get_ssh_public_key_path() return (@ssh_public_key_path ||= File.read(filepath)) end def get_ssh_public_key_path() return query("sshPublicKeyPath") end def get_secret_key_name() return File.basename(get_secret_key_path()) end def get_secret_key_path() return get_ssh_public_key_path().gsub(/\.pub/i, '') end def get_region() return query("region") end def to_h(key_prefix = @provider) items = {} add_if_exist(items, "client_id", get_client_id(), key_prefix) add_if_exist(items, "tenant", get_tenant(), key_prefix) add_if_exist(items, "subscription_id", get_subscription_id(), key_prefix) add_if_exist(items, "secret", get_secret(), key_prefix) add_if_exist(items, "secretKeyPath", get_secret_key_path(), key_prefix) add_if_exist(items, "region", get_region(), key_prefix) add_if_exist(items, "ssh_public_key", get_ssh_public_key(), key_prefix) return items end end end end
26.78125
82
0.621354
08fedb4076e176ecb4502eb5ac11ef98229a50f1
153
require 'test_helper' module SemiStatic class ProductTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end end
15.3
45
0.679739
39570cf007f82cbb7516126825f519f8f4e1914b
13,447
module Melbourne module AST class BackRef < Node attr_accessor :kind def initialize(line, ref) @line = line @kind = ref end Kinds = { :~ => 0, :& => 1, :"`" => 2, :"'" => 3, :+ => 4 } def mode unless mode = Kinds[@kind] raise "Unknown backref: #{@kind}" end mode end def bytecode(g) pos(g) g.last_match mode, 0 end def defined(g) if @kind == :~ g.push_literal "global-variable" return end f = g.new_label done = g.new_label g.last_match mode, 0 g.is_nil g.git f g.push_literal "$#{@kind}" g.goto done f.set! g.push :nil done.set! end def to_sexp [:back_ref, @kind] end end class NthRef < Node attr_accessor :which def initialize(line, ref) @line = line @which = ref end Mode = 5 def bytecode(g) pos(g) # These are for $1, $2, etc. We subtract 1 because # we start numbering the captures from 0. g.last_match Mode, @which - 1 end def defined(g) f = g.new_label done = g.new_label g.last_match Mode, @which - 1 g.is_nil g.git f g.push_literal "$#{@which}" g.goto done f.set! g.push :nil done.set! end def to_sexp [:nth_ref, @which] end end class VariableAccess < Node attr_accessor :name def initialize(line, name) @line = line @name = name end def value_defined(g, f) variable_defined(g, f) bytecode(g) end end class VariableAssignment < Node attr_accessor :name, :value def initialize(line, name, value) @line = line @name = name @value = value end def defined(g) g.push_literal "assignment" end def to_sexp sexp = [sexp_name, @name] sexp << @value.to_sexp if @value sexp end end class ClassVariableAccess < VariableAccess def or_bytecode(g) pos(g) done = g.new_label notfound = g.new_label variable_defined(g, notfound) # Ok, we know the value exists, get it. bytecode(g) g.dup g.git done g.pop # yield to generate the code for when it's not found notfound.set! yield done.set! end def bytecode(g) pos(g) push_scope(g) g.send :class_variable_get, 1 end def push_scope(g) if g.state.scope.module? g.push :self else g.push_scope end g.push_literal @name end def variable_defined(g, f) push_scope(g) g.send :class_variable_defined?, 1 g.gif f end def defined(g) f = g.new_label done = g.new_label variable_defined(g, f) g.push_literal "class variable" g.goto done f.set! g.push :nil done.set! end def to_sexp [:cvar, @name] end end class ClassVariableAssignment < VariableAssignment def bytecode(g) pos(g) if g.state.scope.module? g.push :self else g.push_scope end if @value g.push_literal @name @value.bytecode(g) else g.swap g.push_literal @name g.swap end pos(g) g.send :class_variable_set, 2 end def sexp_name :cvasgn end end class ClassVariableDeclaration < ClassVariableAssignment def sexp_name :cvdecl end end class CurrentException < Node def bytecode(g) pos(g) g.push_current_exception end def defined(g) g.push_literal "global-variable" end def to_sexp [:gvar, :$!] end end class GlobalVariableAccess < VariableAccess EnglishBackrefs = { :$LAST_MATCH_INFO => :~, :$MATCH => :&, :$PREMATCH => :'`', :$POSTMATCH => :"'", :$LAST_PAREN_MATCH => :+, } def self.for_name(line, name) case name when :$! CurrentException.new(line) when :$~ BackRef.new(line, :~) else if backref = EnglishBackrefs[name] BackRef.new(line, backref) else new(line, name) end end end def bytecode(g) pos(g) g.push_rubinius g.find_const :Globals g.push_literal @name g.send :[], 1 end def variable_defined(g, f) g.push_rubinius g.find_const :Globals g.push_literal @name g.send :key?, 1 g.gif f end def defined(g) f = g.new_label done = g.new_label variable_defined(g, f) g.push_literal "global-variable" g.goto done f.set! g.push :nil done.set! end def to_sexp [:gvar, @name] end end class GlobalVariableAssignment < VariableAssignment def bytecode(g) # @value can be nil if this is coming via an masgn, which means # the value is already on the stack. if @name == :$! @value.bytecode(g) if @value pos(g) g.raise_exc elsif @name == :$~ pos(g) # this is a noop for now, but we need to run the # value anyway because it might have side-effects @value.bytecode(g) if @value g.pop g.push :nil else pos(g) g.push_rubinius g.find_const :Globals if @value g.push_literal @name @value.bytecode(g) else g.swap g.push_literal @name g.swap end pos(g) g.send :[]=, 2 end end def sexp_name :gasgn end end class SplatAssignment < Node attr_accessor :value def initialize(line, value) @line = line @value = value end def bytecode(g) pos(g) g.cast_array @value.bytecode(g) end def to_sexp [:splat_assign, @value.to_sexp] end end class SplatArray < SplatAssignment def initialize(line, value, size) @line = line @value = value @size = size end def bytecode(g) pos(g) g.make_array @size @value.bytecode(g) end def to_sexp [:splat, @value.to_sexp] end end class SplatWrapped < SplatAssignment def bytecode(g) pos(g) assign = g.new_label g.dup g.push_cpath_top g.find_const :Array g.swap g.kind_of g.git assign g.make_array 1 assign.set! @value.bytecode(g) end def to_sexp [:splat, @value.to_sexp] end end class EmptySplat < Node def initialize(line, size) @line = line @size = size end def bytecode(g) pos(g) g.make_array @size end def to_sexp [:splat] end end class InstanceVariableAccess < VariableAccess def bytecode(g) pos(g) g.push_ivar @name end def variable_defined(g, f) g.push :self g.push_literal @name g.send :__instance_variable_defined_p__, 1 g.gif f end def defined(g) f = g.new_label done = g.new_label variable_defined(g, f) g.push_literal "instance-variable" g.goto done f.set! g.push :nil done.set! end def to_sexp [:ivar, @name] end end class InstanceVariableAssignment < VariableAssignment def bytecode(g) @value.bytecode(g) if @value pos(g) g.set_ivar @name end def sexp_name :iasgn end end class LocalVariableAccess < VariableAccess include LocalVariable def initialize(line, name) @line = line @name = name @variable = nil end def bytecode(g) pos(g) unless @variable g.state.scope.assign_local_reference self end @variable.get_bytecode(g) end def defined(g) g.push_literal "local-variable" end def value_defined(g, f) bytecode(g) end def to_sexp [:lvar, @name] end end class LocalVariableAssignment < VariableAssignment include LocalVariable def initialize(line, name, value) @line = line @name = name @value = value @variable = nil end def bytecode(g) unless @variable g.state.scope.assign_local_reference self end if @value @value.bytecode(g) end # Set the position after the value, so the position # reflects where the assignment itself is done pos(g) @variable.set_bytecode(g) end def sexp_name :lasgn end end class MultipleAssignment < Node attr_accessor :left, :right, :splat, :block def initialize(line, left, right, splat) @line = line @left = left @right = right @splat = nil @block = nil # support for |&b| @fixed = right.kind_of?(ArrayLiteral) ? true : false if splat.kind_of? Node if @left if right @splat = SplatAssignment.new line, splat else @splat = SplatWrapped.new line, splat end elsif @fixed @splat = SplatArray.new line, splat, right.body.size elsif right.kind_of? SplatValue @splat = splat else @splat = SplatWrapped.new line, splat end elsif splat and @fixed @splat = EmptySplat.new line, right.body.size end end def pad_short(g) short = @left.body.size - @right.body.size if short > 0 short.times { g.push :nil } g.make_array 0 if @splat end end def pop_excess(g) excess = @right.body.size - @left.body.size excess.times { g.pop } if excess > 0 end def make_array(g) size = @right.body.size - @left.body.size g.make_array size if size >= 0 end def rotate(g) if @splat size = @left.body.size + 1 else size = @right.body.size end g.rotate size end def iter_arguments @iter_arguments = true end def declare_local_scope(g) # Fix the scope for locals introduced by the left. We # do this before running the code for the right so that # right side sees the proper scoping of the locals on the left. if @left @left.body.each do |var| case var when LocalVariable g.state.scope.assign_local_reference var when MultipleAssignment var.declare_local_scope(g) end end end if @splat and @splat.kind_of?(SplatAssignment) if @splat.value.kind_of?(LocalVariable) g.state.scope.assign_local_reference @splat.value end end end def bytecode(g, array_on_stack=false) unless array_on_stack g.cast_array unless @right or (@splat and not @left) end declare_local_scope(g) if @fixed pad_short(g) if @left and !@splat @right.body.each { |x| x.bytecode(g) } pad_short(g) if @left and @splat if @left make_array(g) if @splat rotate(g) g.state.push_masgn @left.body.each do |x| x.bytecode(g) g.pop end g.state.pop_masgn pop_excess(g) unless @splat end else if @right @right.bytecode(g) g.cast_array unless @right.kind_of? ToArray end if @left g.state.push_masgn @left.body.each do |x| g.shift_array g.cast_array if x.kind_of? MultipleAssignment and x.left x.bytecode(g) g.pop end g.state.pop_masgn end end if @splat g.state.push_masgn @splat.bytecode(g) g.state.pop_masgn end if @right g.pop if !@fixed or @splat g.push :true end end def defined(g) g.push_literal "assignment" end def to_sexp left = @left ? @left.to_sexp : [:array] left << [:splat, @splat.to_sexp] if @splat left << @block.to_sexp if @block sexp = [:masgn, left] sexp << @right.to_sexp if @right sexp end end end end
19.602041
71
0.503384
5d67f521a7cc57e5284cd52f7500166a44a0303d
6,199
# Copyright 2016 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # DO NOT EDIT: Unless you're fixing a P0/P1 and/or a security issue. This class # is frozen to all new features from `google-cloud-spanner/v2.11.0` onwards. require "delegate" module Google module Cloud module Spanner class Database ## # Database::List is a special case Array with additional # values. # # @deprecated Use the result of # {Google::Cloud::Spanner::Admin::Database#database_admin Client#list_databases} # instead. class List < DelegateClass(::Array) ## # If not empty, indicates that there are more records that match # the request and this value should be passed to continue. attr_accessor :token ## # @private Create a new Database::List with an array of # Database instances. def initialize arr = [] super arr end ## # Whether there is a next page of databases. # # @return [Boolean] # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # databases = spanner.databases "my-instance" # if databases.next? # next_databases = databases.next # end def next? !token.nil? end ## # Retrieve the next page of databases. # # @return [Database::List] # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # databases = spanner.databases "my-instance" # if databases.next? # next_databases = databases.next # end def next return nil unless next? ensure_service! options = { token: token, max: @max } grpc = @service.list_databases @instance_id, **options self.class.from_grpc grpc, @service, @max end ## # Retrieves remaining results by repeatedly invoking {#next} until # {#next?} returns `false`. Calls the given block once for each # result, which is passed as the argument to the block. # # An Enumerator is returned if no block is given. # # This method will make repeated API calls until all remaining results # are retrieved. (Unlike `#each`, for example, which merely iterates # over the results returned by a single API call.) Use with caution. # # @param [Integer] request_limit The upper limit of API requests to # make to load all databases. Default is no limit. # @yield [database] The block for accessing each database. # @yieldparam [Database] database The database object. # # @return [Enumerator] # # @example Iterating each database by passing a block: # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # databases = spanner.databases "my-instance" # databases.all do |database| # puts database.database_id # end # # @example Using the enumerator by not passing a block: # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # databases = spanner.databases "my-instance" # all_database_ids = databases.all.map do |database| # database.database_id # end # # @example Limit the number of API calls made: # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # databases = spanner.databases "my-instance" # databases.all(request_limit: 10) do |database| # puts database.database_id # end # def all request_limit: nil, &block request_limit = request_limit.to_i if request_limit unless block_given? return enum_for :all, request_limit: request_limit end results = self loop do results.each(&block) if request_limit request_limit -= 1 break if request_limit.negative? end break unless results.next? results = results.next end end ## # @private New Database::List from a # `Google::Cloud::Spanner::Admin::Database::V1::ListDatabasesResponse` # object. def self.from_grpc grpc, service, instance_id, max = nil databases = List.new(Array(grpc.databases).map do |database| Database.from_grpc database, service end) databases.instance_variable_set :@instance_id, instance_id token = grpc.next_page_token token = nil if token == "".freeze databases.instance_variable_set :@token, token databases.instance_variable_set :@service, service databases.instance_variable_set :@max, max databases end protected ## # Raise an error unless an active service is available. def ensure_service! raise "Must have active connection" unless @service end end end end end end
34.631285
88
0.559606
7a04064f76adab938fe7ec4a6a72c055a66f38a7
1,095
# frozen_string_literal: true FactoryBot.define do factory(:channel_announcement, class: 'FactoryBotWrapper') do node_signature_1 { build(:signature, :wire) } node_signature_2 { build(:signature, :wire) } bitcoin_signature_1 { build(:signature, :wire) } bitcoin_signature_2 { build(:signature, :wire) } len { 0 } features { ''.htb } chain_hash { '06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f' } short_channel_id { 0 } node_id_1 { build(:key, :remote_funding_pubkey).pubkey } node_id_2 { build(:key, :local_funding_pubkey).pubkey } bitcoin_key_1 { build(:key, :local_pubkey).pubkey } bitcoin_key_2 { build(:key, :local_pubkey).pubkey } initialize_with do new(Lightning::Wire::LightningMessages::ChannelAnnouncement[ node_signature_1, node_signature_2, bitcoin_signature_1, bitcoin_signature_2, len, features, chain_hash, short_channel_id, node_id_1, node_id_2, bitcoin_key_1, bitcoin_key_2, ]) end end end
30.416667
85
0.672146
3825666ab079bd282b05563990381bd8742e989c
1,799
class GitSecret < Formula desc "Bash-tool to store the private data inside a git repo" homepage "https://sobolevn.github.io/git-secret/" license "MIT" head "https://github.com/sobolevn/git-secret.git" stable do url "https://github.com/sobolevn/git-secret/archive/v0.3.2.tar.gz" sha256 "07b32b096e5ff5b4818096b1858c1f69df4684bb0f256e620514cf88f44ded85" end bottle do sha256 cellar: :any_skip_relocation, catalina: "2fb53e4162baa1e614c3d73dbb24257604cf8b7864f73deeba21c784c6434193" sha256 cellar: :any_skip_relocation, mojave: "2fb53e4162baa1e614c3d73dbb24257604cf8b7864f73deeba21c784c6434193" sha256 cellar: :any_skip_relocation, high_sierra: "2fb53e4162baa1e614c3d73dbb24257604cf8b7864f73deeba21c784c6434193" end depends_on "gawk" depends_on "gnupg" def install system "make", "build" system "bash", "utils/install.sh", prefix end test do (testpath/"batch.gpg").write <<~EOS Key-Type: RSA Key-Length: 2048 Subkey-Type: RSA Subkey-Length: 2048 Name-Real: Testing Name-Email: [email protected] Expire-Date: 1d %no-protection %commit EOS begin system Formula["gnupg"].opt_bin/"gpg", "--batch", "--gen-key", "batch.gpg" system "git", "init" system "git", "config", "user.email", "[email protected]" system "git", "secret", "init" assert_match "[email protected] added", shell_output("git secret tell -m") (testpath/"shh.txt").write "Top Secret" (testpath/".gitignore").append_lines "shh.txt" system "git", "secret", "add", "shh.txt" system "git", "secret", "hide" assert_predicate testpath/"shh.txt.secret", :exist? ensure system Formula["gnupg"].opt_bin/"gpgconf", "--kill", "gpg-agent" end end end
33.314815
120
0.682601
edfd874b80878dc3d31d68fc57e6501e27d85064
173
class CreateFeeds < ActiveRecord::Migration[5.0] def change create_table :feeds do |t| t.string :title t.string :url t.timestamps end end end
15.727273
48
0.635838
6a3dd20f58d7aa23e9adb12290a82bb0f781c7f3
1,741
# frozen_string_literal: true require 'support/test_field_type' RSpec.describe EditInPlace::FieldTypeRegistrar do let(:registrar) { described_class.new } describe '#dup' do let(:dup) { registrar.dup } it 'returns a new FieldTypeRegistrar' do expect(dup).to be_an_instance_of described_class end end describe '#register' do context 'with a non-FieldType field type' do def register registrar.register :text, 'random bad object' end it 'raises an appropriate error' do expect { register }.to raise_error EditInPlace::InvalidFieldTypeError end it 'does not register the name' do ignore { register } expect(registrar.find(:text)).to be_nil end end context 'with a valid field type that is an instance of a subclass of FieldType' do before { registrar.register :text, TestFieldType.new('TEXT') } it 'registers it' do expect(registrar.find(:text).arg).to eq 'TEXT' end end context 'with a field type class' do before { registrar.register :complex, ComplexTestFieldType } it 'registers it' do expect(registrar.find(:complex)).to eq ComplexTestFieldType end end end describe '#register_all' do context 'with one non-FieldType field type' do def register registrar.register_all({ image: TestFieldType.new('IMAGE'), text: 'random object' }) end it 'raise an appropriate error' do expect { register }.to raise_error EditInPlace::InvalidFieldTypeError end it 'registers no field types' do ignore { register } expect(registrar.all).to be_empty end end end end
25.231884
87
0.651924
3911f4208e2b4134de0586052adb99d62bb19d30
744
class Organisation < ActiveRecord::Base has_and_belongs_to_many :users has_many :pull_requests, -> { order("created_at desc") }, through: :users scope :order_by_pull_requests, -> { order("organisations.pull_request_count desc") } paginates_per 99 class << self def create_from_github(response) params = { :github_id => response.id, :avatar_url => response._rels[:avatar].href } where(:login => response.login).first_or_create(params) end def with_user_counts joins(:users).select("organisations.*, COUNT(users.id) as users_count").group("organisations.id") end end def active_languages pull_requests.map(&:language).uniq! end def to_param login end end
23.25
103
0.68414
f790e0cd1f53c4ec4fedcd2d75dfb920db4b58f5
2,786
# Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Google module Apis # General options for API requests ClientOptions = Struct.new( :application_name, :application_version, :proxy_url, :use_net_http) RequestOptions = Struct.new( :authorization, :retries, :header, :timeout_sec, :open_timeout_sec) # General client options class ClientOptions # @!attribute [rw] application_name # @return [String] Name of the application, for identification in the User-Agent header # @!attribute [rw] application_version # @return [String] Version of the application, for identification in the User-Agent header # @!attribute [rw] proxy_url # @return [String] URL of a proxy server # Get the default options # @return [Google::Apis::ClientOptions] def self.default @options ||= ClientOptions.new end end # Request options class RequestOptions # @!attribute [rw] authorization # @return [Signet::OAuth2::Client, #apply(Hash)] OAuth2 credentials # @!attribute [rw] retries # @return [Fixnum] Number of times to retry requests on server error # @!attribute [rw] timeout_sec # @return [Fixnum] How long, in seconds, before requests time out # @!attribute [rw] open_timeout_sec # @return [Fixnum] How long, in seconds, before failed connections time out # @!attribute [rw] header # @return [Hash<String,String] Additional HTTP headers to include in requests # Get the default options # @return [Google::Apis::RequestOptions] def self.default @options ||= RequestOptions.new end def merge(options) return self if options.nil? new_options = dup members.each do |opt| opt = opt.to_sym new_options[opt] = options[opt] unless options[opt].nil? end new_options end end ClientOptions.default.use_net_http = false ClientOptions.default.application_name = 'unknown' ClientOptions.default.application_version = '0.0.0' RequestOptions.default.retries = 0 RequestOptions.default.open_timeout_sec = 20 end end
32.395349
98
0.667983
2895f46cc7ad5d6f55a92f768288ba348c134e8e
4,031
# frozen_string_literal: true require 'vk/api/methods' module Vk module API class Board < Vk::Schema::Namespace module Methods # Returns a list of topics on a community's discussion board. class GetTopics < Schema::Method # @!group Properties self.open = true self.method = 'board.getTopics' # @method initialize(arguments) # @param [Hash] arguments # @option arguments [Integer] :group_id ID of the community that owns the discussion board. # @option arguments [Array] :topic_ids IDs of topics to be returned (100 maximum). By default, all topics are returned.; ; If this parameter is set, the 'order', 'offset', and 'count' parameters are ignored. # @option arguments [Integer] :order Sort order:; '1' — by date updated in reverse chronological order.; '2' — by date created in reverse chronological order.; '-1' — by date updated in chronological order.; '-2' — by date created in chronological order.; ; If no sort order is specified, topics are returned in the order specified by the group administrator. Pinned topics are returned first, regardless of the sorting. # @option arguments [Integer] :offset Offset needed to return a specific subset of topics. # @option arguments [Integer] :count Number of topics to return. # @option arguments [Boolean] :extended '1' — to return information about users who created topics or who posted there last; '0' — to return no additional fields (default) # @option arguments [Integer] :preview '1' — to return the first comment in each topic;; '2' — to return the last comment in each topic;; '0' — to return no comments.; ; By default: '0'. # @option arguments [Integer] :preview_length Number of characters after which to truncate the previewed comment. To preview the full comment, specify '0'. # @return [Board::Methods::GetTopics] # @!group Arguments # @return [Integer] ID of the community that owns the discussion board. attribute :group_id, API::Types::Coercible::Int # @return [Array] IDs of topics to be returned (100 maximum). By default, all topics are returned.; ; If this parameter is set, the 'order', 'offset', and 'count' parameters are ignored. attribute :topic_ids, API::Types::Coercible::Array.member(API::Types::Coercible::Int).optional.default(nil) # @return [Integer] Sort order:; '1' — by date updated in reverse chronological order.; '2' — by date created in reverse chronological order.; '-1' — by date updated in chronological order.; '-2' — by date created in chronological order.; ; If no sort order is specified, topics are returned in the order specified by the group administrator. Pinned topics are returned first, regardless of the sorting. attribute :order, API::Types::Coercible::Int.enum("1", "2", "-1", "-2").optional.default(nil) # @return [Integer] Offset needed to return a specific subset of topics. attribute :offset, API::Types::Coercible::Int.optional.default(nil) # @return [Integer] Number of topics to return. attribute :count, API::Types::Coercible::Int.optional.default(40) # @return [Boolean] '1' — to return information about users who created topics or who posted there last; '0' — to return no additional fields (default) attribute :extended, API::Types::Form::Bool.optional.default(nil) # @return [Integer] '1' — to return the first comment in each topic;; '2' — to return the last comment in each topic;; '0' — to return no comments.; ; By default: '0'. attribute :preview, API::Types::Coercible::Int.optional.default(nil) # @return [Integer] Number of characters after which to truncate the previewed comment. To preview the full comment, specify '0'. attribute :preview_length, API::Types::Coercible::Int.optional.default(90) end end end end end
80.62
432
0.677499
2876b8b26e8abea61e6bf11aa83b2c2a8ae72c17
15,034
module Playwright # @ref https://github.com/microsoft/playwright-python/blob/master/playwright/_impl/_frame.py define_channel_owner :Frame do private def after_initialize if @initializer['parentFrame'] @parent_frame = ChannelOwners::Frame.from(@initializer['parentFrame']) @parent_frame.send(:append_child_frame_from_child, self) end @name = @initializer['name'] @url = @initializer['url'] @detached = false @child_frames = Set.new @load_states = Set.new(@initializer['loadStates']) @event_emitter = Object.new.extend(EventEmitter) @channel.on('loadstate', ->(params) { on_load_state(add: params['add'], remove: params['remove']) }) @channel.on('navigated', method(:on_frame_navigated)) end attr_reader :page, :parent_frame attr_writer :detached private def on_load_state(add:, remove:) if add @load_states << add @event_emitter.emit('loadstate', add) end if remove @load_states.delete(remove) end end private def on_frame_navigated(event) @url = event['url'] @name = event['name'] @event_emitter.emit('navigated', event) unless event['error'] @page&.emit('framenavigated', self) end end def goto(url, timeout: nil, waitUntil: nil, referer: nil) params = { url: url, timeout: timeout, waitUntil: waitUntil, referer: referer }.compact resp = @channel.send_message_to_server('goto', params) ChannelOwners::Response.from_nullable(resp) end private def setup_navigation_wait_helper(timeout:) WaitHelper.new.tap do |helper| helper.reject_on_event(@page, Events::Page::Close, AlreadyClosedError.new) helper.reject_on_event(@page, Events::Page::Crash, CrashedError.new) helper.reject_on_event(@page, Events::Page::FrameDetached, FrameAlreadyDetachedError.new) helper.reject_on_timeout(timeout, "Timeout #{timeout}ms exceeded.") end end def expect_navigation(timeout: nil, url: nil, waitUntil: nil, &block) option_wait_until = waitUntil || 'load' option_timeout = timeout || @page.send(:timeout_settings).navigation_timeout time_start = Time.now wait_helper = setup_navigation_wait_helper(timeout: option_timeout) predicate = if url matcher = UrlMatcher.new(url) ->(event) { event['error'] || matcher.match?(event['url']) } else ->(_) { true } end wait_helper.wait_for_event(@event_emitter, 'navigated', predicate: predicate) block&.call event = wait_helper.promise.value! if event['error'] raise event['error'] end unless @load_states.include?(option_wait_until) elapsed_time = Time.now - time_start if elapsed_time < option_timeout wait_for_load_state(state: option_wait_until, timeout: option_timeout - elapsed_time) end end request_json = event.dig('newDocument', 'request') request = ChannelOwners::Request.from_nullable(request_json) request&.response end def wait_for_url(url, timeout: nil, waitUntil: nil) matcher = UrlMatcher.new(url) if matcher.match?(@url) wait_for_load_state(state: waitUntil, timeout: timeout) else expect_navigation(timeout: timeout, url: url, waitUntil: waitUntil) end end def wait_for_load_state(state: nil, timeout: nil) option_state = state || 'load' option_timeout = timeout || @page.send(:timeout_settings).navigation_timeout unless %w(load domcontentloaded networkidle).include?(option_state) raise ArgumentError.new('state: expected one of (load|domcontentloaded|networkidle)') end if @load_states.include?(option_state) return end wait_helper = setup_navigation_wait_helper(timeout: option_timeout) predicate = ->(state) { state == option_state } wait_helper.wait_for_event(@event_emitter, 'loadstate', predicate: predicate) wait_helper.promise.value! nil end def evaluate(pageFunction, arg: nil) if JavaScript.function?(pageFunction) JavaScript::Function.new(pageFunction, arg).evaluate(@channel) else JavaScript::Expression.new(pageFunction).evaluate(@channel) end end def evaluate_handle(pageFunction, arg: nil) if JavaScript.function?(pageFunction) JavaScript::Function.new(pageFunction, arg).evaluate_handle(@channel) else JavaScript::Expression.new(pageFunction).evaluate_handle(@channel) end end def query_selector(selector) resp = @channel.send_message_to_server('querySelector', selector: selector) ChannelOwners::ElementHandle.from_nullable(resp) end def query_selector_all(selector) @channel.send_message_to_server('querySelectorAll', selector: selector).map do |el| ChannelOwners::ElementHandle.from(el) end end def wait_for_selector(selector, state: nil, timeout: nil) params = { selector: selector, state: state, timeout: timeout }.compact resp = @channel.send_message_to_server('waitForSelector', params) ChannelOwners::ElementHandle.from_nullable(resp) end def checked?(selector, timeout: nil) params = { selector: selector, timeout: timeout }.compact @channel.send_message_to_server('isChecked', params) end def disabled?(selector, timeout: nil) params = { selector: selector, timeout: timeout }.compact @channel.send_message_to_server('isDisabled', params) end def editable?(selector, timeout: nil) params = { selector: selector, timeout: timeout }.compact @channel.send_message_to_server('isEditable', params) end def enabled?(selector, timeout: nil) params = { selector: selector, timeout: timeout }.compact @channel.send_message_to_server('isEnabled', params) end def hidden?(selector, timeout: nil) params = { selector: selector, timeout: timeout }.compact @channel.send_message_to_server('isHidden', params) end def visible?(selector, timeout: nil) params = { selector: selector, timeout: timeout }.compact @channel.send_message_to_server('isVisible', params) end def dispatch_event(selector, type, eventInit: nil, timeout: nil) params = { selector: selector, type: type, eventInit: JavaScript::ValueSerializer.new(eventInit).serialize, timeout: timeout, }.compact @channel.send_message_to_server('dispatchEvent', params) nil end def eval_on_selector(selector, pageFunction, arg: nil) if JavaScript.function?(pageFunction) JavaScript::Function.new(pageFunction, arg).eval_on_selector(@channel, selector) else JavaScript::Expression.new(pageFunction).eval_on_selector(@channel, selector) end end def eval_on_selector_all(selector, pageFunction, arg: nil) if JavaScript.function?(pageFunction) JavaScript::Function.new(pageFunction, arg).eval_on_selector_all(@channel, selector) else JavaScript::Expression.new(pageFunction).eval_on_selector_all(@channel, selector) end end def content @channel.send_message_to_server('content') end def set_content(html, timeout: nil, waitUntil: nil) params = { html: html, timeout: timeout, waitUntil: waitUntil, }.compact @channel.send_message_to_server('setContent', params) nil end def name @name || '' end def url @url || '' end def child_frames @child_frames.to_a end def detached? @detached end def add_script_tag(content: nil, path: nil, type: nil, url: nil) params = { content: content, type: type, url: url, }.compact if path params[:content] = "#{File.read(path)}\n//# sourceURL=#{path}" end resp = @channel.send_message_to_server('addScriptTag', params) ChannelOwners::ElementHandle.from(resp) end def add_style_tag(content: nil, path: nil, url: nil) params = { content: content, url: url, }.compact if path params[:content] = "#{File.read(path)}\n/*# sourceURL=#{path}*/" end resp = @channel.send_message_to_server('addStyleTag', params) ChannelOwners::ElementHandle.from(resp) end def click( selector, button: nil, clickCount: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, timeout: nil) params = { selector: selector, button: button, clickCount: clickCount, delay: delay, force: force, modifiers: modifiers, noWaitAfter: noWaitAfter, position: position, timeout: timeout, }.compact @channel.send_message_to_server('click', params) nil end def dblclick( selector, button: nil, delay: nil, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, timeout: nil) params = { selector: selector, button: button, delay: delay, force: force, modifiers: modifiers, noWaitAfter: noWaitAfter, position: position, timeout: timeout, }.compact @channel.send_message_to_server('dblclick', params) nil end def tap_point( selector, force: nil, modifiers: nil, noWaitAfter: nil, position: nil, timeout: nil) params = { selector: selector, force: force, modifiers: modifiers, noWaitAfter: noWaitAfter, position: position, timeout: timeout, }.compact @channel.send_message_to_server('tap', params) nil end def fill(selector, value, noWaitAfter: nil, timeout: nil) params = { selector: selector, value: value, noWaitAfter: noWaitAfter, timeout: timeout, }.compact @channel.send_message_to_server('fill', params) nil end def focus(selector, timeout: nil) params = { selector: selector, timeout: timeout }.compact @channel.send_message_to_server('focus', params) nil end def text_content(selector, timeout: nil) params = { selector: selector, timeout: timeout }.compact @channel.send_message_to_server('textContent', params) end def inner_text(selector, timeout: nil) params = { selector: selector, timeout: timeout }.compact @channel.send_message_to_server('innerText', params) end def inner_html(selector, timeout: nil) params = { selector: selector, timeout: timeout }.compact @channel.send_message_to_server('innerHTML', params) end def get_attribute(selector, name, timeout: nil) params = { selector: selector, name: name, timeout: timeout, }.compact @channel.send_message_to_server('getAttribute', params) end def hover( selector, force: nil, modifiers: nil, position: nil, timeout: nil) params = { selector: selector, force: force, modifiers: modifiers, position: position, timeout: timeout, }.compact @channel.send_message_to_server('hover', params) nil end def select_option( selector, element: nil, index: nil, value: nil, label: nil, noWaitAfter: nil, timeout: nil) base_params = SelectOptionValues.new( element: element, index: index, value: value, label: label, ).as_params params = base_params + { selector: selector, noWaitAfter: noWaitAfter, timeout: timeout }.compact @channel.send_message_to_server('selectOption', params) nil end def set_input_files(selector, files, noWaitAfter: nil, timeout: nil) file_payloads = InputFiles.new(files).as_params params = { files: file_payloads, selector: selector, noWaitAfter: noWaitAfter, timeout: timeout }.compact @channel.send_message_to_server('setInputFiles', params) nil end def type( selector, text, delay: nil, noWaitAfter: nil, timeout: nil) params = { selector: selector, text: text, delay: delay, noWaitAfter: noWaitAfter, timeout: timeout, }.compact @channel.send_message_to_server('type', params) nil end def press( selector, key, delay: nil, noWaitAfter: nil, timeout: nil) params = { selector: selector, key: key, delay: delay, noWaitAfter: noWaitAfter, timeout: timeout, }.compact @channel.send_message_to_server('press', params) nil end def check( selector, force: nil, noWaitAfter: nil, position: nil, timeout: nil) params = { selector: selector, force: force, noWaitAfter: noWaitAfter, position: position, timeout: timeout, }.compact @channel.send_message_to_server('check', params) nil end def uncheck( selector, force: nil, noWaitAfter: nil, position: nil, timeout: nil) params = { selector: selector, force: force, noWaitAfter: noWaitAfter, position: position, timeout: timeout, }.compact @channel.send_message_to_server('uncheck', params) nil end def wait_for_function(pageFunction, arg: nil, polling: nil, timeout: nil) if polling.is_a?(String) && polling != 'raf' raise ArgumentError.new("Unknown polling option: #{polling}") end function_or_expression = if JavaScript.function?(pageFunction) JavaScript::Function.new(pageFunction, arg) else JavaScript::Expression.new(pageFunction) end function_or_expression.wait_for_function(@channel, polling: polling, timeout: timeout) end def title @channel.send_message_to_server('title') end # @param page [Page] # @note This method should be used internally. Accessed via .send method, so keep private! private def update_page_from_page(page) @page = page end # @param child [Frame] # @note This method should be used internally. Accessed via .send method, so keep private! private def append_child_frame_from_child(frame) @child_frames << frame end end end
27.534799
111
0.624185
79e232e519510d7d9e5194e166ac4920ccb07a8f
2,013
class Libmagic < Formula desc "Implementation of the file(1) command" homepage "https://www.darwinsys.com/file/" url "ftp://ftp.astron.com/pub/file/file-5.34.tar.gz" mirror "https://fossies.org/linux/misc/file-5.34.tar.gz" sha256 "f15a50dbbfa83fec0bd1161e8e191b092ec832720e30cd14536e044ac623b20a" bottle do sha256 "8b2bda908cc1602f73c0f3fd27fa9b9fcf037f96f3153a546bf65c3b97bf81d4" => :high_sierra sha256 "ea9fe45980bde7d86785748951b6e572e51cda4b4fad94c170923ce95331bce6" => :sierra sha256 "b5a77abc0e49da98e7436965824793520a06f4e5bf03f05814d96abd995ca7ea" => :el_capitan sha256 "a2b3e8bce493116fcbe5f0f9058246b23fac984f427ab9e70f93cac6333b9b87" => :x86_64_linux end deprecated_option "with-python" => "with-python@2" depends_on "python@2" => :optional def install system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}", "--enable-fsect-man5", "--enable-static" system "make", "install" (share+"misc/magic").install Dir["magic/Magdir/*"] if build.with? "python@2" cd "python" do system "python", *Language::Python.setup_install_args(prefix) end end # Don't dupe this system utility rm bin/"file" rm man1/"file.1" end test do (testpath/"test.c").write <<~EOS #include <assert.h> #include <stdio.h> #include <magic.h> int main(int argc, char **argv) { magic_t cookie = magic_open(MAGIC_MIME_TYPE); assert(cookie != NULL); assert(magic_load(cookie, NULL) == 0); // Prints the MIME type of the file referenced by the first argument. puts(magic_file(cookie, argv[1])); } EOS system ENV.cc, "-I#{include}", "-L#{lib}", "-lmagic", "test.c", "-o", "test" cp test_fixtures("test.png"), "test.png" assert_equal "image/png", shell_output("./test test.png").chomp end end
34.118644
94
0.642822
e8107ebf9e62c252c169dc5ab39b5a374daaeabb
1,547
require 'spec_helper' describe InboxHelper do describe "commentable_description_link" do context "for Deleted Objects" do it "should return the String 'Deleted Object'" do @commentable = FactoryGirl.create(:comment) @work = @commentable.ultimate_parent @work.destroy @commentable.reload commentable_description_link(@commentable).should eq "Deleted Object" end end context "for Tags" do it "should return a link to the Comment on the Tag" do @commentable = FactoryGirl.create(:tag_comment) string = commentable_description_link(@commentable) string.gsub("%20"," ").should eq "<a href=\"/tags/#{@commentable.ultimate_parent.name}/comments/#{@commentable.id}\">#{@commentable.ultimate_parent.name}</a>" end end context "for AdminPosts" do it "should return a link to the Comment on the Adminpost" do @commentable = FactoryGirl.create(:adminpost_comment) commentable_description_link(@commentable).should eq "<a href=\"/admin_posts/#{@commentable.ultimate_parent.id}/comments/#{@commentable.id}\">#{@commentable.ultimate_parent.title}</a>" end end context "for Works" do it "should return a link to the Comment on the Work" do @commentable = FactoryGirl.create(:comment) commentable_description_link(@commentable).should eq "<a href=\"/works/#{@commentable.ultimate_parent.id}/comments/#{@commentable.id}\">#{@commentable.ultimate_parent.title}</a>" end end end end
40.710526
192
0.689076
38bb3ee57e45277562adb8c48afa1a07c46d848c
733
# # Author:: Daniel Deleo (<[email protected]>) # Copyright:: Copyright (c) 2010 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module ChefServer VERSION = '10.14.0.beta.2' end
33.318182
74
0.742156
6a1c908adad39f5c568dfa66464721f0804d638c
1,348
# frozen_string_literal: true require "active_support/concern" module BitPlayer module ContentProviders # Presentation logic for a "new" or "edit" view on a data model. module FormViewProvider extend ActiveSupport::Concern included do def self.data_class(klass) @source_class = klass end def self.source_class @source_class || raise("Classes inheriting from #{self} must " \ "define a source class with " \ "`data_class <class>`") end def self.show_nav_link @show_nav_link = true end def self.hide_nav_link @show_nav_link = false end def self.show_nav_link? @show_nav_link end def self.view_type(type) unless %w( new edit ).include?(type) raise("view type must be one of 'new', 'edit'") end @view_type = type end def self.get_view_type @view_type end end def show_nav_link? self.class.show_nav_link? end def template "#{plural_name}/#{self.class.get_view_type}" end private def plural_name self.class.source_class.to_s.underscore.pluralize end end end end
22.098361
74
0.558605
113b29adcff3699a5cce05034c25ef3a6451e7ee
122
class AddSquirrelImageLink < ActiveRecord::Migration def change add_column :squirrels, :img_link, :string end end
20.333333
52
0.770492
9101981f08806aef9158575c59d90d5a7fd8806c
772
# encoding: UTF-8 # frozen_string_literal: true class MigrateStates < ActiveRecord::Migration def change execute %{UPDATE deposits SET aasm_state = 'submitted' WHERE aasm_state = 'submitting'} execute %{UPDATE deposits SET aasm_state = 'accepted' WHERE aasm_state = 'checked' OR aasm_state = 'warning'} execute %{UPDATE deposits SET aasm_state = 'canceled' WHERE aasm_state = 'cancelled'} execute %{UPDATE withdraws SET aasm_state = 'prepared' WHERE aasm_state = 'submitting'} execute %{UPDATE withdraws SET aasm_state = 'suspected' WHERE aasm_state = 'suspect'} execute %{UPDATE withdraws SET aasm_state = 'succeed' WHERE aasm_state = 'done'} execute %{UPDATE withdraws SET aasm_state = 'canceled' WHERE aasm_state = 'cancelled'} end end
51.466667
113
0.738342
ab1c17590673750c9194d64a8b9be5ba158726d2
204
exclude :test_strftime__gnuext_complex, "need important implem changes and almost useless feature" exclude :test_strftime__offset, "works with (-23..23) +24:00 and -24:00 'virtual' offsets not supported"
68
104
0.79902
08f01efcbd447ab2a937fa9153f0d9844a217d7c
428
require 'haml' require 'action_controller/railtie' Lolita.default_route = :rest require 'lolita/rails/routes' module ActionDispatch::Routing class Mapper protected def lolita_rest_route mapping, controllers resources mapping.plural,:only=>mapping.only.is_a?(Array) ? mapping.only : [:index,:new,:create,:edit,:update,:destroy], :controller=>controllers[:rest],:module=>mapping.module end end end
26.75
126
0.735981
ac2f1290b5f7168228ebe64b9639fd2b47de0dd0
614
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' # Add additional assets to the asset load path # Rails.application.config.assets.paths << Emoji.images_path # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # Rails.application.config.assets.precompile += %w( search.js ) # 这里相当于声明需要编译的样式、逻辑入口 # 相当于每个页面的主逻辑和主样式 Rails.application.config.assets.precompile += %w( depot.css scaffolds.css products.js)
38.375
93
0.775244
39fccc8a4f5c6e5cb69e5a324eb8f1a66cfe73ef
3,385
#============================================================================= # ** RGSS3 Decrypter # Algorithm: fux2 # Implementator: Shadow Momo #----------------------------------------------------------------------------- # * eg: decrypt("Game.rgss3a") #----------------------------------------------------------------------------- # * It is strictly prohibited to use this decrypter for any purpose except # learning and exchanging. # * Do not spread it out. # * We are not legally responsible for the decrypter provided. #============================================================================= def decrypt(path, output = "Decryption", islog = true) mkdir = ->(path){ path.scan(/^(.*)\\/){ mkdir.($1) } Dir.mkdir path unless Dir.exist? path } if Dir.exist? output output += Time.now.strftime("%j-%H-%M-%S") msgbox "Directory already exists! Will extract to new directory: #{output}" end mkdir.(output) logfile = File.open output + "\\" + "Decrypt.log", "w+" if islog log = ->(string){logfile.puts string if islog; puts string} log.("Begin") log.("") log.("Try to open archive...") archive = open path, "rb" if archive.read(8) != "RGSSAD\0\3" log.("Standard RPG Maker VX Ace Encrypted Archive Expected!") raise TypeError, "Standard RPG Maker VX Ace Encrypted Archive Expected!" end log.("Archive opened successfully.") key = archive.read(4).unpack("L")[0] * 9 + 3 files = [] log.("") log.("Analyse Files...") i = 0 loop do break if (offset = archive.read(4).unpack("L")[0] ^ key) == 0 i += 1 length = archive.read(4).unpack("L")[0] ^ key magickey = archive.read(4).unpack("L")[0] ^ key flength = archive.read(4).unpack("L")[0] ^ key filename = archive.read(flength) _ = "L" * ((flength + 3) / 4) filename += "\0" * 4 filename = filename.unpack(_).map{|x| x ^ key}.pack(_)[0, flength] log.("-File ##{i}: #{filename}") log.("--Offset: #{offset}\tLength: #{length}") files.push [offset, length, magickey, filename.force_encoding('utf-8')] end log.("All files analysed.") log.("") log.("Extract Files...") files.each_with_index do |(offset, length, magickey, filename), i| log.("-Extracting File ##{i + 1}: #{filename}") archive.pos = offset contents = archive.read(length) _ = "L" * ((length + 3) / 4) contents = (contents + "\0" * 4).unpack(_).collect{|x| unit = x ^ magickey magickey = magickey * 7 + 3 unit }.pack(_)[0, length] filename.scan(/^(.*)\\/){ mkdir.(output + "\\" + $1) } File.open output + "\\" + filename, "wb" do |data| data.write contents end log.("--Succeed.") end log.("All files extracted.") log.("") log.("End") log.("") log.("") log.("Now Check Completeness...") flag = true files.each_with_index{|(offset, length, magickey, filename), i| log.("-Checking File ##{i + 1}: #{filename}") begin load_data(output + "\\" + filename) log.("--OK!") rescue flag = false log.("--Failed!") end } log.(flag ? "Perfect!" : ":(") rescue => e begin log.("") log.("Abort on exception: #{e.inspect}!") log.("Decrypting failed.") end rescue nil ensure logfile.close if islog rescue nil archive.close rescue nil end decrypt("Encryption\\Game.rgss3a")
28.208333
79
0.529394
39fe704f5ce1c87b32cd00315b24a7a7c8f54bb4
1,352
require 'rom/initializer' require 'rom/http/types' require 'rom/http/attribute' require 'rom/http/schema' require 'rom/http/schema/dsl' module ROM module HTTP # HTTP-specific relation extensions # class Relation < ROM::Relation include ROM::HTTP adapter :http schema_class HTTP::Schema schema_dsl HTTP::Schema::DSL schema_attr_class HTTP::Attribute forward :with_headers, :add_header, :with_options, :with_base_path, :with_path, :append_path, :with_request_method, :with_params, :add_params def primary_key schema.primary_key_name end def project(*names) with(schema: schema.project(*names.flatten)) end def exclude(*names) with(schema: schema.exclude(*names)) end def rename(mapping) with(schema: schema.rename(mapping)) end def prefix(prefix) with(schema: schema.prefix(prefix)) end # @see Dataset#insert def insert(*tuples) dataset.insert(*tuples.map { |t| input_schema[t] }) end alias_method :<<, :insert # @see Dataset#update def update(*tuples) dataset.update(*tuples.map { |t| input_schema[t] }) end # @see Dataset#delete def delete dataset.delete end end end end
21.460317
61
0.616864
618ab9900bf8b441e7d925836c71ae45fc02daae
915
require "formula" class Ridenum < Formula homepage "https://github.com/trustedsec/ridenum" url "https://github.com/trustedsec/ridenum.git", :using => :git, :revision => "a6ed473" version "1.7" depends_on "python3" resource "pexpect" do url "https://pypi.python.org/packages/52/97/13924c85a4b7544a4174781360e0530a7fff23e62d76da0e211369dd61f5/pexpect-3.3.tar.gz" sha256 'dfea618d43e83cfff21504f18f98019ba520f330e4142e5185ef7c73527de5ba' end def install ENV.prepend_create_path "PYTHONPATH", libexec/"vendor/lib/python2.7/site-packages" %w[pexpect].each do |r| resource(r).stage do system "python", *Language::Python.setup_install_args(libexec/"vendor") end end ENV.prepend_create_path "PYTHONPATH", libexec bin.install "ridenum.py" libexec.install Dir["*"] bin.env_script_all_files(libexec/"bin", :PYTHONPATH => ENV["PYTHONPATH"]) end end
30.5
128
0.725683
5d13ac1352905f0eb4de4cbb04b226511cd7dd9e
78
module WriMetadata def self.table_name_prefix 'wri_metadata_' end end
13
28
0.769231
ab935d3004837b7bfbe523ac6d6c107093ecc2d3
290
require_relative '../helper' collection = 'dubaipeeps' punks = ImageComposite.new( 25, 14 ) # 25x14 = 350 punks.add_glob( "./#{collection}/ii/*.png" ) punks.save( "../collections/dubaipunks/dubaipunks-24x24.png" ) punks.zoom(2).save( "./tmp/[email protected]" ) puts "bye"
17.058824
62
0.675862
bb6f6bef5d718d16db4d4fa4dcd8fe332def563d
737
class SessionsController < ApplicationController def new end def create @user = User.find_by(email: params[:session][:email].downcase) if @user && @user.authenticate(params[:session][:password]) if @user.activated? log_in @user params[:session][:remember_me] == '1' ? remember(@user) : forget(@user) redirect_back_or @user else message = 'Account not activated. ' message += 'Check your email for activation link.' flash[:warning] = message redirect_to root_url end else flash.now[:danger] = 'Invalid email/password combination' render 'new' end end def destroy log_out if logged_in? redirect_to root_url end end
25.413793
79
0.636364
edf753a17b3b8f27011947020c3bcdcc4d3941cf
23
Travis::Features.start
11.5
22
0.826087
031ff8ff1170a0432e7bbc3bbdd3113d719b73d6
5,834
require "language/go" class Rclone < Formula desc "rsync for cloud storage" homepage "https://rclone.org/" url "https://github.com/ncw/rclone/archive/v1.36.tar.gz" sha256 "a573b70e3aeb355b943dddd6ae9375386fc21bf12dfba601d8d7280f97c4c884" bottle do cellar :any_skip_relocation sha256 "3620712255134b1c9d2ee003b7a24ead0c3442fb5b978d10e89a074aa4d5b12e" => :sierra sha256 "c82062a1b60bf6c721615e33184529387cedd639453f7e63ad2762fe9d90210c" => :el_capitan sha256 "aa03f9aaeb36428ec466dcff39256df1446723f3cf45a5e180a583d5a076ade3" => :yosemite end depends_on "go" => :build go_resource "golang.org/x/oauth2" do url "https://go.googlesource.com/oauth2.git", :revision => "1364adb2c63445016c5ed4518fc71f6a3cda6169" end go_resource "golang.org/x/net" do url "https://go.googlesource.com/net.git", :revision => "6a513affb38dc9788b449d59ffed099b8de18fa0" end go_resource "golang.org/x/tools" do url "https://go.googlesource.com/tools.git", :revision => "9e7459099f9afd6a15464d69d93c6eed49bb545d" end go_resource "google.golang.org/api" do url "https://code.googlesource.com/google-api-go-client.git", :revision => "fa0566afd4c8fdae644725fdf9b57b5851a20742" end go_resource "google.golang.org/cloud" do url "https://code.googlesource.com/gocloud.git", :revision => "30fab6304c9888af49f1884cf4eddad7027e2e7b" end go_resource "golang.org/x/crypto" do url "https://go.googlesource.com/crypto.git", :revision => "bc89c496413265e715159bdc8478ee9a92fdc265" end go_resource "golang.org/x/text" do url "https://go.googlesource.com/text.git", :revision => "2910a502d2bf9e43193af9d68ca516529614eed3" end go_resource "github.com/kisielk/errcheck" do url "https://github.com/kisielk/errcheck.git", :revision => "50ffcb6f3595daac70aff9e63afe8b8b277b1a1a" end go_resource "github.com/golang/lint" do url "https://github.com/golang/lint.git", :revision => "c7bacac2b21ca01afa1dee0acf64df3ce047c28f" end go_resource "github.com/tsenart/tb" do url "https://github.com/tsenart/tb.git", :revision => "19f4c3d79d2bd67d0911b2e310b999eeea4454c1" end go_resource "github.com/stacktic/dropbox" do url "https://github.com/stacktic/dropbox.git", :revision => "58f839b21094d5e0af7caf613599830589233d20" end go_resource "github.com/spf13/pflag" do url "https://github.com/spf13/pflag.git", :revision => "1560c1005499d61b80f865c04d39ca7505bf7f0b" end go_resource "github.com/skratchdot/open-golang" do url "https://github.com/skratchdot/open-golang.git", :revision => "75fb7ed4208cf72d323d7d02fd1a5964a7a9073c" end go_resource "github.com/Unknwon/goconfig" do url "https://github.com/Unknwon/goconfig.git", :revision => "5f601ca6ef4d5cea8d52be2f8b3a420ee4b574a5" end go_resource "github.com/VividCortex/ewma" do url "https://github.com/VividCortex/ewma.git", :revision => "8b9f1311551e712ea8a06b494238b8a2351e1c33" end go_resource "github.com/aws/aws-sdk-go" do url "https://github.com/aws/aws-sdk-go.git", :revision => "3b8c171554fc7d4fc53b87e25d4926a9e7495c2e" end go_resource "github.com/mreiferson/go-httpclient" do url "https://github.com/mreiferson/go-httpclient.git", :revision => "31f0106b4474f14bc441575c19d3a5fa21aa1f6c" end go_resource "github.com/ncw/go-acd" do url "https://github.com/ncw/go-acd.git", :revision => "0bd73ce86fffd8afeafe4e46f419f1a8ce6324b9" end go_resource "github.com/ncw/swift" do url "https://github.com/ncw/swift.git", :revision => "b964f2ca856aac39885e258ad25aec08d5f64ee6" end go_resource "github.com/pkg/errors" do url "https://github.com/pkg/errors.git", :revision => "1d2e60385a13aaa66134984235061c2f9302520e" end go_resource "github.com/google/go-querystring" do url "https://github.com/google/go-querystring.git", :revision => "9235644dd9e52eeae6fa48efd539fdc351a0af53" end go_resource "bazil.org/fuse" do url "https://github.com/bazil/fuse.git", :revision => "371fbbdaa8987b715bdd21d6adc4c9b20155f748" end go_resource "github.com/ogier/pflag" do url "https://github.com/ogier/pflag.git", :revision => "45c278ab3607870051a2ea9040bb85fcb8557481" end go_resource "github.com/rfjakob/eme" do url "https://github.com/rfjakob/eme.git", :revision => "601d0e278ceda9aa2085a61c9265f6e690ef5255" end go_resource "github.com/spf13/cobra" do url "https://github.com/spf13/cobra.git", :revision => "37c3f8060359192150945916cbc2d72bce804b4d" end go_resource "github.com/cpuguy83/go-md2man" do url "https://github.com/cpuguy83/go-md2man.git", :revision => "2724a9c9051aa62e9cca11304e7dd518e9e41599" end go_resource "github.com/russross/blackfriday" do url "https://github.com/russross/blackfriday.git", :revision => "93622da34e54fb6529bfb7c57e710f37a8d9cbd8" end go_resource "github.com/shurcooL/sanitized_anchor_name" do url "https://github.com/shurcooL/sanitized_anchor_name.git", :revision => "10ef21a441db47d8b13ebcc5fd2310f636973c77" end def install ENV["GOPATH"] = buildpath mkdir_p buildpath/"src/github.com/ncw/" ln_s buildpath, buildpath/"src/github.com/ncw/rclone" Language::Go.stage_deps resources, buildpath/"src" system "go", "build", "-o", bin/"rclone" system bin/"rclone", "genautocomplete", "bash_completion" bash_completion.install "bash_completion" => "rclone" end test do (testpath/"file1.txt").write "Test!" system "#{bin}/rclone", "copy", testpath/"file1.txt", testpath/"dist" assert_match File.read(testpath/"file1.txt"), File.read(testpath/"dist/file1.txt") end end
33.337143
92
0.723003
5d831cdd22b5f810e4ad346b31516e729698f30c
519
require 'netatlas/command_listener' require 'netatlas/event_publisher' require 'netatlas/collector_publisher' require 'netatlas/scheduler' require 'netatlas/worker' class NetAtlas::PollerGroup < Celluloid::SupervisionGroup supervise NetAtlas::CommandListener, :as => :command_listener supervise NetAtlas::EventPublisher, :as => :event_publisher supervise NetAtlas::CollectorPublisher, :as => :collector_publisher supervise NetAtlas::Scheduler, :as => :scheduler pool NetAtlas::Worker, :as => :worker_pool end
39.923077
69
0.797688
b9ae986132597a7908328737ff686004ad0a2c0c
1,601
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{juke} s.version = "0.1.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Brian Smith"] s.date = %q{2011-02-09} s.description = %q{JSON API steps for Cucumber, hand-crafted for you in Juke *nod to Aruba*} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.md" ] s.files = [ ".document", "LICENSE", "README.md", "Rakefile", "VERSION", "juke.gemspec", "lib/juke.rb", "lib/juke/adapters/rack.rb", "lib/juke/adapters/rails.rb", "lib/juke/api.rb", "lib/juke/cucumber.rb", "lib/juke/ext/utils.rb", "lib/juke/formatters/json.rb" ] s.homepage = %q{http://github.com/Lytol/juke} s.require_paths = ["lib"] s.rubygems_version = %q{1.3.7} s.summary = %q{JSON API steps for Cucumber} if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, [">= 1.2.9"]) s.add_development_dependency(%q<yard>, [">= 0"]) else s.add_dependency(%q<rspec>, [">= 1.2.9"]) s.add_dependency(%q<yard>, [">= 0"]) end else s.add_dependency(%q<rspec>, [">= 1.2.9"]) s.add_dependency(%q<yard>, [">= 0"]) end end
28.589286
105
0.628357
e89cbaa06d50f9fe2aba2c43d4ad7891d5da4e87
761
module ActiveMerchant #:nodoc: module Billing #:nodoc: class PayflowNvResponse < Response def profile_id @params['profileid'] end def payment_history @payment_history ||= get_history end protected def get_history hist = [] @params.reject {|key,val| key !~ /p_result/}.collect {|r| r[0].gsub(/p_result/, "")}.sort.each do |idx| item = { 'payment_num' => "#{idx}", 'amt' => @params["p_amt#{idx}"], 'transtime' => @params["p_transtime#{idx}"], 'result' => @params["p_result#{idx}"], 'state' => @params["p_transtate#{idx}"], } hist << item end return hist end end end end
26.241379
111
0.508541
6a4e9db9cbcc254bb3642e4468f922e1c57b11c9
66
FactoryGirl.define do factory :laugh do volume 10 end end
11
21
0.712121
38ca4681d9cfcc7defd58495af147cb897c30689
43
module DeviseToken VERSION = '0.1.1' end
10.75
19
0.697674
b9b24692a84467b26cffd4a56a886386b8295bbf
4,982
require 'rails_helper' RSpec.describe 'Confirmable', type: :feature do def visit_user_confirmation_with_token(confirmation_token) visit user_confirmation_path(confirmation_token: confirmation_token) end def resend_confirmation user = create_user(confirm: false) ActionMailer::Base.deliveries.clear visit new_user_session_path click_link "Didn't receive confirmation instructions?" fill_in 'user_email', with: user.email click_button 'Resend confirmation instructions' end it 'is able to request a new confirmation' do resend_confirmation expect(current_path).to eq '/users/sign_in' expect(page).to have_selector('div', text: 'You will receive an email with instructions for how to confirm your email address in a few minutes') expect(ActionMailer::Base.deliveries.size).to eq 1 expect(ActionMailer::Base.deliveries.first.from).to eq ['[email protected]'] end it 'is able to confirm the account when confirmation token is valid' do user = create_user(confirm: false, confirmation_sent_at: 2.days.ago) expect(user).not_to be_confirmed visit_user_confirmation_with_token(user.primary_email_record.confirmation_token) expect(page).to have_selector('div', text: 'Your email address has been successfully confirmed.') expect(current_path).to eq '/users/sign_in' expect(user.reload).to be_confirmed expect(user.primary_email_record).to be_confirmed end describe '#email=' do context 'when unconfirmed access is disallowed' do it 'does not change primary email' do user = create_user first_email = user.primary_email_record user.email = generate_email expect(user.primary_email_record.email).to eq(first_email.email) end it 'changes primary email if confirmed' do user = create_user new_email = create_email(user, confirm: true) user.email = new_email.email expect(user.primary_email_record.email).to eq(new_email.email) end end context 'when unconfirmed access is allowed' do before do Devise.setup do |config| config.allow_unconfirmed_access_for = 2.days end end after do Devise.setup do |config| config.allow_unconfirmed_access_for = 0.day end end it 'changes primary email to the new email' do user = create_user new_email = generate_email user.email = new_email expect(user.primary_email_record.email).to eq(new_email) end end end describe 'Unconfirmed sign in' do context 'with primary email' do it 'shows the error message' do user = create_user(confirm: false) visit new_user_session_path fill_in 'user_email', with: user.email fill_in 'user_password', with: '12345678' click_button 'Log in' expect(current_path).to eq new_user_session_path expect(page).to have_selector('div#flash_alert', text: 'You have to confirm your email address before continuing.') end end context 'with non-primary email' do it 'shows the error message' do user = create_user secondary_email = create_email(user, confirm: false) visit new_user_session_path fill_in 'user_email', with: secondary_email.email fill_in 'user_password', with: '12345678' click_button 'Log in' expect(current_path).to eq new_user_session_path expect(page).to have_selector('div#flash_alert', text: 'You have to confirm your email address before continuing.') end end context 'when unconfirmed access is allowed' do before do Devise.setup do |config| config.allow_unconfirmed_access_for = 2.days end end after do Devise.setup do |config| config.allow_unconfirmed_access_for = 0.day end end context 'with primary email' do it 'signs the user in' do user = create_user(confirm: false) visit new_user_session_path fill_in 'user_email', with: user.email fill_in 'user_password', with: '12345678' click_button 'Log in' expect(current_path).to eq root_path expect(page).to have_selector('div', text: 'Signed in successfully.') end end context 'with non-primary email' do it 'shows the error message' do user = create_user secondary_email = create_email(user, confirm: false) visit new_user_session_path fill_in 'user_email', with: secondary_email.email fill_in 'user_password', with: '12345678' click_button 'Log in' expect(current_path).to eq new_user_session_path expect(page).to have_selector('div#flash_alert', text: 'You have to confirm your email address before continuing.') end end end end end
32.141935
148
0.679647
080302acffb3e257eab29ee222da616f3ba0c9ef
456
Gem::Specification.new do |spec| spec.name = "truth_or_dare" spec.version = "0.0.3" spec.authors = ["Julie Graceffa"] spec.email = ["[email protected]"] spec.summary = %q{Truth or dare game} spec.description = %q{Allows user to play truth or dare game and pick their option} spec.license = "MIT" spec.files = ["lib/truth_or_dare.rb"] spec.executables = ["truth_or_dare"] end
30.4
87
0.609649
f725869dca71d02da877df4fc68b6b33e6188452
1,483
Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Configure static asset server for tests with Cache-Control for performance config.serve_static_assets = true config.static_cache_control = "public, max-age=3600" # Log error messages when you accidentally call methods on nil config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Print deprecation notices to the stderr config.active_support.deprecation = :stderr if Rails::VERSION::MAJOR == 3 && ENV['THREADSAFE'] == 'true' config.threadsafe! end end
38.025641
84
0.770061
e95422080dfe5c8fb318d0837ae1be6e8a19a597
4,482
# frozen_string_literal: true require 'spec_helper' describe RuboCop::Cop::Style::NumericLiteralPrefix, :config do subject(:cop) { described_class.new(config) } context 'octal literals' do context 'when config is zero_with_o' do let(:cop_config) do { 'EnforcedOctalStyle' => 'zero_with_o' } end it 'registers an offense for prefixes `0` and `0O`' do inspect_source(cop, ['a = 01234', 'b(0O1234)']) expect(cop.offenses.size).to eq(2) expect(cop.messages.uniq).to eq(['Use 0o for octal literals.']) expect(cop.highlights).to eq(%w(01234 0O1234)) end it 'does not register offense for lowercase prefix' do inspect_source(cop, ['a = 0o101', 'b = 0o567']) expect(cop.messages).to be_empty end it 'autocorrects an octal literal starting with 0' do corrected = autocorrect_source(cop, ['a = 01234']) expect(corrected).to eq('a = 0o1234') end it 'autocorrects an octal literal starting with 0O' do corrected = autocorrect_source(cop, ['b(0O1234, a)']) expect(corrected).to eq('b(0o1234, a)') end end context 'when config is zero_only' do let(:cop_config) do { 'EnforcedOctalStyle' => 'zero_only' } end it 'registers an offense for prefix `0O` and `0o`' do inspect_source(cop, ['a = 0O1234', 'b(0o1234)']) expect(cop.offenses.size).to eq(2) expect(cop.messages.uniq).to eq(['Use 0 for octal literals.']) expect(cop.highlights).to eq(%w(0O1234 0o1234)) end it 'does not register offense for prefix `0`' do inspect_source(cop, 'b = 0567') expect(cop.messages).to be_empty end it 'autocorrects an octal literal starting with 0O or 0o' do corrected = autocorrect_source(cop, ['a = 0O1234', 'b(0o1234)']) expect(corrected).to eq "a = 01234\nb(01234)" end it 'does not autocorrect an octal literal starting with 0' do corrected = autocorrect_source(cop, ['b(01234, a)']) expect(corrected).to eq 'b(01234, a)' end end end context 'hex literals' do it 'registers an offense for uppercase prefix' do inspect_source(cop, ['a = 0X1AC', 'b(0XABC)']) expect(cop.offenses.size).to eq(2) expect(cop.messages.uniq).to eq(['Use 0x for hexadecimal literals.']) expect(cop.highlights).to eq(%w(0X1AC 0XABC)) end it 'does not register offense for lowercase prefix' do inspect_source(cop, 'a = 0x101') expect(cop.messages).to be_empty end it 'autocorrects literals with uppercase prefix' do corrected = autocorrect_source(cop, ['a = 0XAB']) expect(corrected).to eq 'a = 0xAB' end end context 'binary literals' do it 'registers an offense for uppercase prefix' do inspect_source(cop, ['a = 0B10101', 'b(0B111)']) expect(cop.offenses.size).to eq(2) expect(cop.messages.uniq).to eq(['Use 0b for binary literals.']) expect(cop.highlights).to eq(%w(0B10101 0B111)) end it 'does not register offense for lowercase prefix' do inspect_source(cop, 'a = 0b101') expect(cop.messages).to be_empty end it 'autocorrects literals with uppercase prefix' do corrected = autocorrect_source(cop, ['a = 0B1010']) expect(corrected).to eq 'a = 0b1010' end end context 'decimal literals' do it 'registers an offense for prefixes' do inspect_source(cop, ['a = 0d1234', 'b(0D1234)']) expect(cop.offenses.size).to eq(2) expect(cop.messages.uniq) .to eq(['Do not use prefixes for decimal literals.']) expect(cop.highlights).to eq(%w(0d1234 0D1234)) end it 'does not register offense for no prefix' do inspect_source(cop, 'a = 101') expect(cop.messages).to be_empty end it 'autocorrects literals with prefix' do corrected = autocorrect_source(cop, ['a = 0d1234', 'b(0D1990)']) expect(corrected).to eq "a = 1234\nb(1990)" end it 'does not autocorrect literals with no prefix' do corrected = autocorrect_source(cop, ['a = 1234', 'b(1990)']) expect(corrected).to eq "a = 1234\nb(1990)" end end end
32.014286
75
0.597947
d54dbe2e4d969c41ffaf3132e7c378fffb0887c8
1,169
# frozen_string_literal: true require 'spec_helper' require 'cfn-model/parser/cfn_parser' describe CfnParser do before :each do @cfn_parser = CfnParser.new end context 'a template with a lambda function' do it 'has assocated role_object when ref id' do json_test_templates('lambda_function/lambda_function_with_getatt_role').each do |template| cfn_model = @cfn_parser.parse IO.read(template) actual_functions = cfn_model.resources_by_type('AWS::Lambda::Function') actual_computed_role = actual_functions.find do |function| function.role_object end expect(actual_computed_role).to_not be_nil end end it 'does not have associated role_object when string id' do json_test_templates('lambda_function/lambda_function_with_string_role').each do |template| cfn_model = @cfn_parser.parse IO.read(template) actual_functions = cfn_model.resources_by_type('AWS::Lambda::Function') actual_computed_role = actual_functions.find do |function| function.role_object end expect(actual_computed_role).to be_nil end end end end
29.974359
96
0.717707
113c94425a0c0598880054528133c54ffda31910
301
module Travis module Feierabend class MemoryStorage def initialize @in_use = {} end def store(label, data) @in_use[label] ||= [] @in_use[label].push(data) end def list_in_use(label) @in_use[label] || [] end end end end
15.842105
33
0.531561
bf1a45e329c130552e9a667086fd097199721702
181
FactoryBot.define do factory :lock_script do address hash_type { "type" } args { "0x#{SecureRandom.hex(20)}" } code_hash { "0x#{SecureRandom.hex(32)}" } end end
20.111111
45
0.635359
3384d953aff4580194d0ba37984ea8a64809cd4d
2,020
require "set" module Celluloid module ClassMethods extend Forwardable def_delegators :"Celluloid::Supervision::Container::Pool", :pooling_options # Create a new pool of workers. Accepts the following options: # # * size: how many workers to create. Default is worker per CPU core # * args: array of arguments to pass when creating a worker # def pool(config={}, &block) _ = Celluloid.supervise(pooling_options(config, block: block, actors: self)) _.actors.last end # Same as pool, but links to the pool manager def pool_link(klass, config={}, &block) Supervision::Container::Pool.new_link(pooling_options(config, block: block, actors: klass)) end end module Supervision class Container extend Forwardable def_delegators :"Celluloid::Supervision::Container::Pool", :pooling_options def pool(klass, config={}, &block) _ = supervise(pooling_options(config, block: block, actors: klass)) _.actors.last end class Instance attr_accessor :pool, :pool_size end class << self # Register a pool of actors to be launched on group startup def pool(klass, config, &block) blocks << lambda do |container| container.pool(klass, config, &block) end end end class Pool include Behavior class << self def pooling_options(config={},mixins={}) combined = { :type => Celluloid::Supervision::Container::Pool }.merge(config).merge(mixins) combined[:args] = [[:block, :actors, :size, :args].inject({}) { |e,p| e[p] = combined.delete(p) if combined[p]; e }] combined end end identifier! :size, :pool configuration do @supervisor = Container::Pool @method = "pool_link" @pool = true @pool_size = @cofiguration[:size] @configuration end end end end end
28.055556
128
0.606931
1867501cd4f2f5b34bacd927beb8a48c0871eec4
2,754
require 'spec_helper' require 'fileutils' require 'bosh/director/core/templates/template_blob_cache' module Bosh::Director::Core::Templates describe TemplateBlobCache do let(:job_template) { double('Bosh::Director::DeploymentPlan::Job', download_blob: '/template1', blobstore_id: 'blob-id') } let(:job_template2) { double('Bosh::Director::DeploymentPlan::Job', download_blob: '/template2', blobstore_id: 'blob-id2') } describe '#with_fresh_cache' do class ConsistencyDummy def ensure_this_cache_is_cleaned(cache) expect(cache).to receive(:clean_cache!) end end it 'cleans the cache after the work is done' do dummy = ConsistencyDummy.new expect(dummy). to receive(:ensure_this_cache_is_cleaned). with(an_instance_of(TemplateBlobCache)) TemplateBlobCache.with_fresh_cache do |cache| dummy.ensure_this_cache_is_cleaned(cache) end end end describe '#download_blob' do context 'when the blob has not been downloaded' do it 'should download the blob' do expect(subject.download_blob(job_template)).to eq('/template1') expect(job_template).to have_received(:download_blob) end end context 'when the blob has already been downloaded' do it 'should not re-download the blob' do expect(subject.download_blob(job_template)).to eq('/template1') expect(subject.download_blob(job_template)).to eq('/template1') expect(job_template).to have_received(:download_blob).once end it 'should be thread safe' do subject # ensure this has been initiated before we launch threads allow(job_template).to receive(:download_blob) { Thread.pass; '/template1' } t1 = Thread.new { expect(subject.download_blob(job_template)).to eq('/template1') } t2 = Thread.new { expect(subject.download_blob(job_template)).to eq('/template1') } t1.join t2.join expect(job_template).to have_received(:download_blob).once end end end describe '#clean' do before do subject.download_blob(job_template) subject.download_blob(job_template2) end it 'removes all the files that got downloaded' do expect(FileUtils).to receive(:rm_f).with('/template1') expect(FileUtils).to receive(:rm_f).with('/template2') subject.clean_cache! end it 'clears its internal cache list' do subject.download_blob(job_template) subject.clean_cache! subject.download_blob(job_template) expect(job_template).to have_received(:download_blob).twice end end end end
33.180723
128
0.665214
e96e6537a9eae27abed922721c2c6bc54610d62a
4,455
# Provides implementation for Spree payment process logic for Spree::PaymentMethod::PAYONE::CashOnDelivery module Spree::PAYONE module Provider module Payment class CashOnDelivery < Spree::PAYONE::Provider::Payment::Base # Sets initial data. def initialize(options) super(options) @shipping_provider = options[:shipping_provider] end # Proceses payment method authorize action. def authorize(money, cash_on_delivery_source, payment_method_options = {}) Spree::PAYONE::Logger.info "Authorize process started" request = Spree::PAYONE::Proxy::Request.new request.preauthorization_request set_initial_request_parameters(request) set_cash_on_delivery_request_parameters(request, cash_on_delivery_source) set_amount_request_parameters(request, money, payment_method_options) set_order_request_parameters(request, payment_method_options) set_personal_data_request_parameters(request, payment_method_options) set_billing_request_parameters(request, payment_method_options) set_shipping_request_parameters(request, payment_method_options) response = process_request request, payment_method_options payment_provider_response response end # Proceses gateway purchase action. def purchase(money, cash_on_delivery_source, payment_method_options = {}) Spree::PAYONE::Logger.info "Purchase process started" request = Spree::PAYONE::Proxy::Request.new request.authorization_request set_initial_request_parameters(request) set_cash_on_delivery_request_parameters(request, cash_on_delivery_source) set_amount_request_parameters(request, money, payment_method_options) set_order_request_parameters(request, payment_method_options) set_personal_data_request_parameters(request, payment_method_options) set_billing_request_parameters(request, payment_method_options) set_shipping_request_parameters(request, payment_method_options) response = process_request request, payment_method_options payment_provider_response response end # Proceses gateway capture action. def capture(money, response_code, payment_method_options = {}) Spree::PAYONE::Logger.info "Capture process started" request = Spree::PAYONE::Proxy::Request.new request.capture_request set_initial_request_parameters(request) set_amount_request_parameters(request, money, payment_method_options) set_payment_process_parameters(request, response_code) response = process_request request, payment_method_options payment_provider_response response end # Proceses gateway void action. def void(response_code, provider_source, gateway_options = {}) Spree::PAYONE::Logger.info "Void process started" payment_payment_provider_successful_response end # Proceses gateway credit action. def credit(money, response_code, gateway_options = {}) Spree::PAYONE::Logger.info "Credit process started" request = Spree::PAYONE::Proxy::Request.new request.debit_request set_initial_request_parameters(request) set_amount_request_parameters(request, '-' + money.to_s, gateway_options) set_payment_process_parameters(request, response_code) set_sequence_request_parameters(request, response_code) response = process_request request, payment_method_options payment_provider_response response end # Sets cash on delivery parameters. def set_cash_on_delivery_request_parameters(request, cash_on_delivery_source) request.cash_on_delivery_clearingtype request.shippingprovider= shipping_provider() end # Returns cash on delivery type. def shipping_provider() type = Spree::PAYONE::Utils::ShippingProvider.validate(@shipping_provider) if type != nil return type else return '' end end end end end end
42.428571
106
0.679012
919c1e4a5b2050309402b169e3b47266d879c445
1,346
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'techbook_helper/version' Gem::Specification.new do |spec| spec.name = "techbook_helper" spec.version = TechbookHelper::VERSION spec.authors = ["Georg Romas"] spec.email = ["[email protected]"] spec.summary = %q{Build start book template for TechBook from CrestWave technologies} spec.description = %q{This is helper to start wright technical book stored in git with and published on TechBook developed by CrestWave technologies} spec.homepage = "https://rubygems.org/gems/techbook_helper" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } #spec.bindir = "bin" #spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.executables = ['techbook'] spec.require_paths = ["lib"] spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) # if spec.respond_to?(:metadata) # spec.metadata['allowed_push_host'] = "https://github.com/roma86/TechBook_helper.git" # end spec.add_development_dependency "bundler", "~> 1.8" spec.add_development_dependency "rake", "~> 10.0" spec.add_runtime_dependency "colorize" end
40.787879
153
0.673848
bbd8320d6dda7a15832fb949d1c63964d1511bed
1,489
# encoding: utf-8 require 'spec_helper' describe Github::Client::Issues::Comments, '#create' do let(:user) { 'peter-murach' } let(:repo) { 'github' } let(:number) { 1 } let(:inputs) { { 'body' => 'a new comment' } } let(:request_path) { "/repos/#{user}/#{repo}/issues/#{number}/comments" } before { stub_post(request_path).with(:body => inputs). to_return(:body => body, :status => status, :headers => {:content_type => "application/json; charset=utf-8"}) } after { reset_authentication_for(subject) } context "resouce created" do let(:body) { fixture('issues/comment.json') } let(:status) { 201 } it "should fail to create resource if 'body' input is missing" do expect { subject.create user, repo, number, inputs.except('body') }.to raise_error(Github::Error::RequiredParams) end it "should create resource successfully" do subject.create user, repo, number, inputs a_post(request_path).with(body: inputs).should have_been_made end it "should return the resource" do comment = subject.create user, repo, number, inputs comment.should be_a Github::ResponseWrapper end it "should get the comment information" do comment = subject.create user, repo, number, inputs comment.user.login.should == 'octocat' end end it_should_behave_like 'request failure' do let(:requestable) { subject.create user, repo, number, inputs } end end # create
29.78
75
0.657488
bf7794dbb6d864389d81ad47aedf3fd9f30c2483
447
require 'base64' require 'json' require 'stringio' require 'zlib' module Jets::Job::Helpers module LogEventHelper def log_event encoded = event["awslogs"]["data"] compressed_string = Base64.decode64(encoded) gz = Zlib::GzipReader.new(StringIO.new(compressed_string)) uncompressed_string = gz.read data = JSON.load(uncompressed_string) ActiveSupport::HashWithIndifferentAccess.new(data) end end end
24.833333
64
0.715884
795d7fccf94a0ca7f3236105c6a41e6adb70d59f
158
module TharyelViewTool class Renderer def self.copyright(name, msg) "&copy; #{Time.now.year} | <b>#{name}</b> #{msg}".html_safe end end end
19.75
65
0.626582
1adc08bc8f8a6b47811bd10083ec670684761cba
1,097
module PermitYo module Default module UserExtensions def self.included(recipient) recipient.extend ClassMethods end module ClassMethods def acts_as_authorized_user include PermitYo::Default::UserExtensions::InstanceMethods end end module InstanceMethods def has_role?(role) self.send(:"#{role}?") if self.respond_to?(:"#{role}?") end end end module ModelExtensions def self.included(recipient) recipient.extend ClassMethods end module ClassMethods def acts_as_authorizable include PermitYo::Default::ModelExtensions::InstanceMethods end end module InstanceMethods def accepts_role?(role, user) if role == "self" self == user elsif self.respond_to? role self.send(role) == user elsif self.respond_to? role.pluralize self.send(role.pluralize).include?(user) else false end end end end end end
23.340426
69
0.587967
01cf9740d1f5cf454c98f64b795ec7cf27800c34
903
require 'spec_helper' describe 'Projects > Snippets > User comments on a snippet', :js do let(:project) { create(:project) } let!(:snippet) { create(:project_snippet, project: project, author: user) } let(:user) { create(:user) } before do project.add_master(user) sign_in(user) visit(project_snippet_path(project, snippet)) end it 'leaves a comment on a snippet' do page.within('.js-main-target-form') do fill_in('note_note', with: 'Good snippet!') click_button('Comment') end wait_for_requests expect(page).to have_content('Good snippet!') end it 'should have autocomplete' do find('#note_note').native.send_keys('') fill_in 'note[note]', with: '@' expect(page).to have_selector('.atwho-view') end it 'should have zen mode' do find('.js-zen-enter').click() expect(page).to have_selector('.fullscreen') end end
23.763158
77
0.664452
bb8a10462a68971ecdfd4da3e9aad1916e211c64
192
Rails.application.routes.draw do root to: proc { [404, {}, ['404 (Not Found)']] } post '/distance', to: 'distances#create', as: 'distance' get '/cost', to: 'costs#show', as: 'cost' end
27.428571
58
0.614583
1a78bfddf7476ccf7472cd7aaf7613a55cdaad3e
2,565
module Dapp module Dimg module Build module Stage class ImportArtifact < ArtifactBase def initialize(dimg) @dimg = dimg end def signature hashsum [*dependencies.flatten, change_options] end def image @image ||= Image::Scratch.new(name: image_name, dapp: dimg.dapp) end def image_add_mounts end def prepare_image super do change_options.each do |k, v| image.public_send("add_change_#{k}", v) end end end protected def apply_artifact(artifact, image) return if dimg.dapp.dry_run? artifact_name = artifact[:name] artifact_dimg = artifact[:dimg] cwd = artifact[:options][:cwd] to = artifact[:options][:to] include_paths = artifact[:options][:include_paths] owner = artifact[:options][:owner] group = artifact[:options][:group] sudo = dimg.dapp.sudo_command(owner: Process.uid, group: Process.gid) credentials = '' credentials += "--owner=#{owner} " if owner credentials += "--group=#{group} " if group credentials += '--numeric-owner' archive_path = dimg.tmp_path('artifact', artifact_name, 'archive.tar.gz') container_archive_path = File.join(artifact_dimg.container_tmp_path(artifact_name), 'archive.tar.gz') exclude_paths = artifact[:options][:exclude_paths].map { |path| "--exclude=#{path}" }.join(' ') include_paths = include_paths.empty? ? [File.join(cwd, '*')] : include_paths.map { |path| File.join(cwd, path, '*') } include_paths.map! { |path| path[1..-1] } # relative path command = "#{sudo} #{dimg.dapp.tar_bin} #{tar_option_transform(cwd, to)} -czf #{container_archive_path} #{exclude_paths} #{include_paths.join(' ')} #{credentials}" run_artifact_dimg(artifact_dimg, artifact_name, command) image.add_archive archive_path end private def tar_option_transform(cwd, to) format = proc do |path| res = path.chomp('/').reverse.chomp('/').reverse res = res.gsub('/', '\/') res end "--transform \"s/^#{format.call(cwd)}/#{format.call(to)}/\"" end end # ImportArtifact end # Stage end # Build end # Dimg end # Dapp
33.311688
175
0.548538
e2fe6078760f98574a2eb74c99205d875c7f0d88
616
require 'rails/generators' module Mei class RoutesGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) desc """ This generator makes the following changes to your application: 1. Injects route declarations into your routes.rb """ # Add Mei to the routes def inject_mei_routes unless IO.read("config/routes.rb").include?('Mei::Engine') marker = 'Rails.application.routes.draw do' insert_into_file "config/routes.rb", :after => marker do %q{ mount Mei::Engine => '/' } end end end end end
22.814815
65
0.646104
1d890ac3cc51837301a13f7759c8ecb5b56184d4
2,078
require_relative '../../../../test_helper' require_relative '../endpoint_test_helper' class UsersTest < Minitest::Test extend Smartsheet::Test::EndpointHelper attr_accessor :mock_client attr_accessor :smartsheet_client def category smartsheet_client.users end def self.endpoints [ { symbol: :add, method: :post, url: ['users'], args: {body: {}}, has_params: true, headers: nil }, { symbol: :get_current, method: :get, url: ['users', 'me'], args: {}, has_params: false, headers: nil }, { symbol: :get, method: :get, url: ['users', :user_id], args: {user_id: 123}, has_params: false, headers: nil }, { symbol: :list, method: :get, url: ['users'], args: {}, has_params: true, headers: nil }, { symbol: :remove, method: :delete, url: ['users', :user_id], args: {user_id: 123}, has_params: true, headers: nil }, { symbol: :update, method: :put, url: ['users', :user_id], args: {user_id: 123, body: {}}, has_params: false, headers: nil }, { symbol: :add_profile_image, method: :post, url: ['users', :user_id, 'profileimage'], args: {user_id: 123, file: {}, filename: 'file', file_length: 123}, has_params: false, headers: nil }, { symbol: :add_profile_image_from_path, method: :post, url: ['users', :user_id, 'profileimage'], args: {user_id: 123, path: 'file'}, has_params: false, headers: nil }, ] end define_setup define_endpoints_tests end
23.613636
79
0.443696
2183c667227220c8877dbf33b8d30c17722d2688
4,961
# frozen_string_literal: true # WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE module Aws::ComprehendMedical # When ComprehendMedical returns an error response, the Ruby SDK constructs and raises an error. # These errors all extend Aws::ComprehendMedical::Errors::ServiceError < {Aws::Errors::ServiceError} # # You can rescue all ComprehendMedical errors using ServiceError: # # begin # # do stuff # rescue Aws::ComprehendMedical::Errors::ServiceError # # rescues all ComprehendMedical API errors # end # # # ## Request Context # ServiceError objects have a {Aws::Errors::ServiceError#context #context} method that returns # information about the request that generated the error. # See {Seahorse::Client::RequestContext} for more information. # # ## Error Classes # * {InternalServerException} # * {InvalidEncodingException} # * {InvalidRequestException} # * {ResourceNotFoundException} # * {ServiceUnavailableException} # * {TextSizeLimitExceededException} # * {TooManyRequestsException} # * {ValidationException} # # Additionally, error classes are dynamically generated for service errors based on the error code # if they are not defined above. module Errors extend Aws::Errors::DynamicErrors class InternalServerException < ServiceError # @param [Seahorse::Client::RequestContext] context # @param [String] message # @param [Aws::ComprehendMedical::Types::InternalServerException] data def initialize(context, message, data = Aws::EmptyStructure.new) super(context, message, data) end # @return [String] def message @message || @data[:message] end end class InvalidEncodingException < ServiceError # @param [Seahorse::Client::RequestContext] context # @param [String] message # @param [Aws::ComprehendMedical::Types::InvalidEncodingException] data def initialize(context, message, data = Aws::EmptyStructure.new) super(context, message, data) end # @return [String] def message @message || @data[:message] end end class InvalidRequestException < ServiceError # @param [Seahorse::Client::RequestContext] context # @param [String] message # @param [Aws::ComprehendMedical::Types::InvalidRequestException] data def initialize(context, message, data = Aws::EmptyStructure.new) super(context, message, data) end # @return [String] def message @message || @data[:message] end end class ResourceNotFoundException < ServiceError # @param [Seahorse::Client::RequestContext] context # @param [String] message # @param [Aws::ComprehendMedical::Types::ResourceNotFoundException] data def initialize(context, message, data = Aws::EmptyStructure.new) super(context, message, data) end # @return [String] def message @message || @data[:message] end end class ServiceUnavailableException < ServiceError # @param [Seahorse::Client::RequestContext] context # @param [String] message # @param [Aws::ComprehendMedical::Types::ServiceUnavailableException] data def initialize(context, message, data = Aws::EmptyStructure.new) super(context, message, data) end # @return [String] def message @message || @data[:message] end end class TextSizeLimitExceededException < ServiceError # @param [Seahorse::Client::RequestContext] context # @param [String] message # @param [Aws::ComprehendMedical::Types::TextSizeLimitExceededException] data def initialize(context, message, data = Aws::EmptyStructure.new) super(context, message, data) end # @return [String] def message @message || @data[:message] end end class TooManyRequestsException < ServiceError # @param [Seahorse::Client::RequestContext] context # @param [String] message # @param [Aws::ComprehendMedical::Types::TooManyRequestsException] data def initialize(context, message, data = Aws::EmptyStructure.new) super(context, message, data) end # @return [String] def message @message || @data[:message] end end class ValidationException < ServiceError # @param [Seahorse::Client::RequestContext] context # @param [String] message # @param [Aws::ComprehendMedical::Types::ValidationException] data def initialize(context, message, data = Aws::EmptyStructure.new) super(context, message, data) end # @return [String] def message @message || @data[:message] end end end end
29.706587
102
0.667406
0376034ec47f97f1770ae439182e0bef79680650
59
class Employee < ApplicationRecord has_many :entries end
14.75
34
0.813559
1d478243ca41abe4dcb55ab3356fa578156d8fdf
1,121
# # Cookbook Name:: redis # Recipe:: default # # Copyright 2010, Estately, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ### Install the OneHub PPA to get Redis 2.2.x apt_repository "onehub-ppa" do uri "http://ppa.launchpad.net/onehub/ppa/ubuntu/" key "CCC23219" keyserver "keyserver.ubuntu.com" distribution "lucid" components %w( main ) action :add end package "redis-server" service "redis-server" do supports [:restart] action :enable end template "/etc/redis/redis.conf" do owner "root" group "root" mode 0644 notifies :restart, resources( :service => "redis-server" ) end
24.369565
74
0.724353
6a2bdda7953aeeb71b12943be62dc8e18dd7b634
242
# frozen_string_literal: true require "helper" class TestSimpleCovHtml < Minitest::Test def test_defined assert defined?(SimpleCov::Formatter::HTMLFormatter) assert defined?(SimpleCov::Formatter::HTMLFormatter::VERSION) end end
22
65
0.77686
5d4bab1119771c114382ddb081a6ac10d24a6b13
9,690
# frozen_string_literal: true require "singleton" module Mime class Mimes attr_reader :symbols include Enumerable def initialize @mimes = [] @symbols = [] end def each @mimes.each { |x| yield x } end def <<(type) @mimes << type @symbols << type.to_sym end def delete_if @mimes.delete_if do |x| if yield x @symbols.delete(x.to_sym) true end end end end SET = Mimes.new EXTENSION_LOOKUP = {} LOOKUP = {} class << self def [](type) return type if type.is_a?(Type) Type.lookup_by_extension(type) end def fetch(type) return type if type.is_a?(Type) EXTENSION_LOOKUP.fetch(type.to_s) { |k| yield k } end end # Encapsulates the notion of a MIME type. Can be used at render time, for example, with: # # class PostsController < ActionController::Base # def show # @post = Post.find(params[:id]) # # respond_to do |format| # format.html # format.ics { render body: @post.to_ics, mime_type: Mime::Type.lookup("text/calendar") } # format.xml { render xml: @post } # end # end # end class Type attr_reader :symbol @register_callbacks = [] # A simple helper class used in parsing the accept header. class AcceptItem #:nodoc: attr_accessor :index, :name, :q alias :to_s :name def initialize(index, name, q = nil) @index = index @name = name q ||= 0.0 if @name == "*/*" # Default wildcard match to end of list. @q = ((q || 1.0).to_f * 100).to_i end def <=>(item) result = item.q <=> @q result = @index <=> item.index if result == 0 result end end class AcceptList #:nodoc: def self.sort!(list) list.sort! text_xml_idx = find_item_by_name list, "text/xml" app_xml_idx = find_item_by_name list, Mime[:xml].to_s # Take care of the broken text/xml entry by renaming or deleting it. if text_xml_idx && app_xml_idx app_xml = list[app_xml_idx] text_xml = list[text_xml_idx] app_xml.q = [text_xml.q, app_xml.q].max # Set the q value to the max of the two. if app_xml_idx > text_xml_idx # Make sure app_xml is ahead of text_xml in the list. list[app_xml_idx], list[text_xml_idx] = text_xml, app_xml app_xml_idx, text_xml_idx = text_xml_idx, app_xml_idx end list.delete_at(text_xml_idx) # Delete text_xml from the list. elsif text_xml_idx list[text_xml_idx].name = Mime[:xml].to_s end # Look for more specific XML-based types and sort them ahead of app/xml. if app_xml_idx app_xml = list[app_xml_idx] idx = app_xml_idx while idx < list.length type = list[idx] break if type.q < app_xml.q if type.name.end_with? "+xml" list[app_xml_idx], list[idx] = list[idx], app_xml app_xml_idx = idx end idx += 1 end end list.map! { |i| Mime::Type.lookup(i.name) }.uniq! list end def self.find_item_by_name(array, name) array.index { |item| item.name == name } end end class << self TRAILING_STAR_REGEXP = /^(text|application)\/\*/ PARAMETER_SEPARATOR_REGEXP = /;\s*\w+="?\w+"?/ def register_callback(&block) @register_callbacks << block end def lookup(string) LOOKUP[string] || Type.new(string) end def lookup_by_extension(extension) EXTENSION_LOOKUP[extension.to_s] end # Registers an alias that's not used on MIME type lookup, but can be referenced directly. Especially useful for # rendering different HTML versions depending on the user agent, like an iPhone. def register_alias(string, symbol, extension_synonyms = []) register(string, symbol, [], extension_synonyms, true) end def register(string, symbol, mime_type_synonyms = [], extension_synonyms = [], skip_lookup = false) new_mime = Type.new(string, symbol, mime_type_synonyms) SET << new_mime ([string] + mime_type_synonyms).each { |str| LOOKUP[str] = new_mime } unless skip_lookup ([symbol] + extension_synonyms).each { |ext| EXTENSION_LOOKUP[ext.to_s] = new_mime } @register_callbacks.each do |callback| callback.call(new_mime) end new_mime end def parse(accept_header) if !accept_header.include?(",") accept_header = accept_header.split(PARAMETER_SEPARATOR_REGEXP).first return [] unless accept_header parse_trailing_star(accept_header) || [Mime::Type.lookup(accept_header)].compact else list, index = [], 0 accept_header.split(",").each do |header| params, q = header.split(PARAMETER_SEPARATOR_REGEXP) next unless params params.strip! next if params.empty? params = parse_trailing_star(params) || [params] params.each do |m| list << AcceptItem.new(index, m.to_s, q) index += 1 end end AcceptList.sort! list end end def parse_trailing_star(accept_header) parse_data_with_trailing_star($1) if accept_header =~ TRAILING_STAR_REGEXP end # For an input of <tt>'text'</tt>, returns <tt>[Mime[:json], Mime[:xml], Mime[:ics], # Mime[:html], Mime[:css], Mime[:csv], Mime[:js], Mime[:yaml], Mime[:text]</tt>. # # For an input of <tt>'application'</tt>, returns <tt>[Mime[:html], Mime[:js], # Mime[:xml], Mime[:yaml], Mime[:atom], Mime[:json], Mime[:rss], Mime[:url_encoded_form]</tt>. def parse_data_with_trailing_star(type) Mime::SET.select { |m| m.match?(type) } end # This method is opposite of register method. # # To unregister a MIME type: # # Mime::Type.unregister(:mobile) def unregister(symbol) symbol = symbol.downcase if mime = Mime[symbol] SET.delete_if { |v| v.eql?(mime) } LOOKUP.delete_if { |_, v| v.eql?(mime) } EXTENSION_LOOKUP.delete_if { |_, v| v.eql?(mime) } end end end attr_reader :hash MIME_NAME = "[a-zA-Z0-9][a-zA-Z0-9#{Regexp.escape('!#$&-^_.+')}]{0,126}" MIME_PARAMETER_KEY = "[a-zA-Z0-9][a-zA-Z0-9#{Regexp.escape('!#$&-^_.+')}]{0,126}" MIME_PARAMETER_VALUE = "#{Regexp.escape('"')}?[a-zA-Z0-9][a-zA-Z0-9#{Regexp.escape('!#$&-^_.+')}]{0,126}#{Regexp.escape('"')}?" MIME_PARAMETER = "\s*\;\s*#{MIME_PARAMETER_KEY}(?:\=#{MIME_PARAMETER_VALUE})?" MIME_REGEXP = /\A(?:\*\/\*|#{MIME_NAME}\/(?:\*|#{MIME_NAME})(?:\s*#{MIME_PARAMETER}\s*)*)\z/ class InvalidMimeType < StandardError; end def initialize(string, symbol = nil, synonyms = []) unless MIME_REGEXP.match?(string) raise InvalidMimeType, "#{string.inspect} is not a valid MIME type" end @symbol, @synonyms = symbol, synonyms @string = string @hash = [@string, @synonyms, @symbol].hash end def to_s @string end def to_str to_s end def to_sym @symbol end def ref symbol || to_s end def ===(list) if list.is_a?(Array) (@synonyms + [ self ]).any? { |synonym| list.include?(synonym) } else super end end def ==(mime_type) return false unless mime_type (@synonyms + [ self ]).any? do |synonym| synonym.to_s == mime_type.to_s || synonym.to_sym == mime_type.to_sym end end def eql?(other) super || (self.class == other.class && @string == other.string && @synonyms == other.synonyms && @symbol == other.symbol) end def =~(mime_type) return false unless mime_type regexp = Regexp.new(Regexp.quote(mime_type.to_s)) @synonyms.any? { |synonym| synonym.to_s =~ regexp } || @string =~ regexp end def match?(mime_type) return false unless mime_type regexp = Regexp.new(Regexp.quote(mime_type.to_s)) @synonyms.any? { |synonym| synonym.to_s.match?(regexp) } || @string.match?(regexp) end def html? (symbol == :html) || /html/.match?(@string) end def all?; false; end protected attr_reader :string, :synonyms private def to_ary; end def to_a; end def method_missing(method, *args) if method.end_with?("?") method[0..-2].downcase.to_sym == to_sym else super end end def respond_to_missing?(method, include_private = false) method.end_with?("?") || super end end class AllType < Type include Singleton def initialize super "*/*", nil end def all?; true; end def html?; true; end end # ALL isn't a real MIME type, so we don't register it for lookup with the # other concrete types. It's a wildcard match that we use for +respond_to+ # negotiation internals. ALL = AllType.instance class NullType include Singleton def nil? true end def to_s "" end def ref; end private def respond_to_missing?(method, _) method.end_with?("?") end def method_missing(method, *args) false if method.end_with?("?") end end end require "action_dispatch/http/mime_types"
26.842105
131
0.577296
792f37cf666457a99969c81461cbbffd32646d8a
1,411
module Doorkeeper module OAuth class AuthorizationCodeRequest include Validations include OAuth::RequestConcern validate :attributes, error: :invalid_request validate :client, error: :invalid_client validate :grant, error: :invalid_grant validate :redirect_uri, error: :invalid_redirect_uri attr_accessor :server, :grant, :client, :redirect_uri, :access_token def initialize(server, grant, client, parameters = {}) @server = server @client = client @grant = grant @redirect_uri = parameters[:redirect_uri] end private def before_successful_response grant.transaction do grant.lock! raise Errors::InvalidGrantReuse if grant.revoked? grant.revoke find_or_create_access_token(grant.application, grant.resource_owner_id, grant.scopes, server) end end def validate_attributes redirect_uri.present? end def validate_client !!client end def validate_grant return false unless grant && grant.application_id == client.id grant.accessible? end def validate_redirect_uri grant.redirect_uri == redirect_uri end end end end
25.654545
74
0.592488
7a1b34481141f5fe5ac6c5e88b17eab45c0558f3
603
require_relative '../spec_helper' DEPENDS_TEST_DIR = 'spec/fixtures/depends' DEPENDS_BASE_DIR = DEPENDS_TEST_DIR def update_appmap_index cmd = [ './exe/appmap-index', '--appmap-dir', DEPENDS_TEST_DIR ] if ENV['DEBUG'] == 'true' cmd << '--verbose' end system cmd.join(' ') or raise "Failed to update AppMap index in #{DEPENDS_TEST_DIR}" end RSpec.configure do |rspec| rspec.before do Dir.glob("#{DEPENDS_TEST_DIR}/*.appmap.json").each { |fname| FileUtils.touch fname } update_appmap_index FileUtils.rm_rf 'spec/tmp' FileUtils.mkdir_p 'spec/tmp' end end
21.535714
88
0.688226
f857e9cf5461c4d2b4b078a1a9d233e21af041c9
7,322
describe AutotestResultsJob do let(:assignment) { create :assignment } let(:grouping) { create(:grouping, assignment: assignment) } let(:test_runs) { create_list(:test_run, 3, grouping: grouping, status: :in_progress) } context 'when running as a background job' do let(:job_args) { [assignment.id] } let(:job) { described_class.perform_later(*job_args) } context 'if there is no job currently in progress' do before { Redis::Namespace.new(Rails.root.to_s).del('autotest_results') } include_examples 'background job' it 'sets the redis key' do job expect(Redis::Namespace.new(Rails.root.to_s).get('autotest_results')).not_to be_nil end end context 'if there is a job currently in progress' do before do Redis::Namespace.new(Rails.root.to_s).set('autotest_results', 1) clear_enqueued_jobs clear_performed_jobs end after do clear_enqueued_jobs clear_performed_jobs Redis::Namespace.new(Rails.root.to_s).del('autotest_results') end it 'does not enqueue a job' do expect { job }.not_to have_enqueued_job end end end describe '#perform' do before do Redis::Namespace.new(Rails.root.to_s).del('autotest_results') allow_any_instance_of(AutotestSetting).to( receive(:send_request!).and_return(OpenStruct.new(body: { api_key: 'someapikey' }.to_json)) ) course = create(:course) course.autotest_setting = create(:autotest_setting) course.save test_runs.each_with_index { |t, i| t.update!(autotest_test_id: i + 1) } end subject { described_class.perform_now } context 'tests are set up for an assignment' do let(:assignment) { create :assignment, assignment_properties_attributes: { remote_autotest_settings_id: 10 } } let(:dummy_return) { Net::HTTPSuccess.new(1.0, '200', 'OK') } let(:body) { '{}' } before { allow(dummy_return).to receive(:body) { body } } context 'when getting the statuses of the tests' do it 'should set headers' do expect_any_instance_of(AutotestResultsJob).to receive(:send_request!) do |_job, net_obj| expect(net_obj['Api-Key']).to eq assignment.course.autotest_setting.api_key expect(net_obj['Content-Type']).to eq 'application/json' dummy_return end subject end it 'should send an api request to the autotester' do expect_any_instance_of(AutotestResultsJob).to receive(:send_request!) do |_job, net_obj, uri| expect(net_obj.instance_of?(Net::HTTP::Get)).to be true expect(uri.to_s).to eq "#{assignment.course.autotest_setting.url}/settings/10/tests/status" expect(JSON.parse(net_obj.body)['test_ids']).to contain_exactly(1, 2, 3) dummy_return end subject end include_examples 'autotest jobs' end context 'after getting the statuses of the tests' do before { allow_any_instance_of(AutotestResultsJob).to receive(:statuses).and_return(status_return) } shared_examples 'rescheduling a job' do before { allow_any_instance_of(AutotestResultsJob).to receive(:results) } it 'should schedule another job in a minute' do expect(AutotestResultsJob).to receive(:set).with(wait: 5.seconds).once.and_call_original expect_any_instance_of(ActiveJob::ConfiguredJob).to receive(:perform_later).once subject end end shared_examples 'getting results' do context 'a successful request' do it 'should set headers' do allow_any_instance_of(TestRun).to receive(:update_results!) expect_any_instance_of(AutotestResultsJob).to receive(:send_request) do |_job, net_obj| expect(net_obj['Api-Key']).to eq assignment.course.autotest_setting.api_key expect(net_obj['Content-Type']).to eq 'application/json' dummy_return end subject end it 'should send an api request to the autotester' do allow_any_instance_of(TestRun).to receive(:update_results!) expect_any_instance_of(AutotestResultsJob).to receive(:send_request) do |_job, net_obj, uri| expect(net_obj.instance_of?(Net::HTTP::Get)).to be true expect(uri.to_s).to eq "#{assignment.course.autotest_setting.url}/settings/10/test/2" dummy_return end subject end it 'should call update_results! for the test_run' do allow_any_instance_of(AutotestResultsJob).to receive(:send_request).and_return(dummy_return) expect_any_instance_of(TestRun).to receive(:update_results!).with({}) do |test_run| expect(test_run.autotest_test_id).to eq 2 end subject end end context 'an unsuccessful request' do let(:dummy_return) { Net::HTTPServerError.new(1.0, '500', 'Server Error') } before do allow_any_instance_of(AutotestResultsJob).to receive(:send_request).and_return(dummy_return) end it 'should call failure for the test_run' do expect_any_instance_of(TestRun).to receive(:failure).with('{}') do |test_run| expect(test_run.autotest_test_id).to eq 2 end subject end end end context 'when at least one of the statuses is "started"' do let(:status_return) { { 1 => 'finished', 2 => 'started', 3 => 'finished' } } include_examples 'rescheduling a job' end context 'when at least one of the statuses is "queued"' do let(:status_return) { { 1 => 'finished', 2 => 'queued', 3 => 'finished' } } include_examples 'rescheduling a job' end context 'when at least one of the statuses is "deferred"' do let(:status_return) { { 1 => 'finished', 2 => 'deferred', 3 => 'finished' } } include_examples 'rescheduling a job' end context 'when at least one of the statuses is "finished"' do let(:status_return) { { 1 => 'started', 2 => 'finished', 3 => 'started' } } include_examples 'getting results' end context 'when at least one of the statuses is "failed"' do let(:status_return) { { 1 => 'started', 2 => 'failed', 3 => 'started' } } include_examples 'getting results' end context 'when at least one of the statuses is something else' do let(:status_return) { { 1 => 'started', 2 => 'something else', 3 => 'started' } } it 'should call failure for the test_run' do expect_any_instance_of(TestRun).to receive(:failure).with('something else') do |test_run| expect(test_run.autotest_test_id).to eq 2 end subject end end end end context 'tests are not set up' do it 'should try again with reduced retries' do expect { subject }.to raise_error(I18n.t('automated_tests.settings_not_setup')) end end end end
45.478261
116
0.623737
1cf1c815277820a2697954dc2bd5969f863eff72
837
namespace :v1x2, :path => "v1.2" do resources :stageaction, :only => %i(show update) get "/openapi.json", :to => "root#openapi" post "/graphql", :to => "graphql#query" resources :actions, :only => [:show] resources :requests, :only => %i(create index show) do resources :requests, :only => [:index] resources :actions, :only => %i(create index) end get "/requests/:id/content", :to => "requests#show" resources :workflows, :only => %i(index destroy update show) post '/workflows/:id/link', :to => "workflows#link", :as => 'link' post '/workflows/:id/unlink', :to => "workflows#unlink", :as => 'unlink' post '/workflows/:id/reposition', :to => "workflows#reposition", :as => 'reposition' resources :templates, :only => %i(index show) do resources :workflows, :only => %i(create index) end end
32.192308
86
0.633214
f8eca64707642d51d0e6937a99623642c9732872
823
cask "alt-tab" do version "6.34.0" sha256 "85791a9f5fec9f3fca4da9e2a709e73d9019bdc470067cab97142174da678ceb" url "https://github.com/lwouis/alt-tab-macos/releases/download/v#{version}/AltTab-#{version}.zip" name "AltTab" desc "Enable Windows-like alt-tab" homepage "https://github.com/lwouis/alt-tab-macos" livecheck do url :url strategy :github_latest end auto_updates true depends_on macos: ">= :sierra" app "AltTab.app" uninstall quit: "com.lwouis.alt-tab-macos" zap trash: [ "~/Library/Application Support/com.lwouis.alt-tab-macos", "~/Library/Caches/com.lwouis.alt-tab-macos", "~/Library/Cookies/com.lwouis.alt-tab-macos.binarycookies", "~/Library/LaunchAgents/com.lwouis.alt-tab-macos.plist", "~/Library/Preferences/com.lwouis.alt-tab-macos.plist", ] end
27.433333
99
0.715674
2189d739bdc7718056979308cf770249ce9a177a
415
module OfxS4m class Header attr_accessor :head attr_accessor :version def initialize(head = nil) @head = head clear_head end private def clear_head if @head @head = @head.split("\n").map{|item| item.split(":") if item.split(":").size == 2 }.compact.to_h @version = @head["VERSION"] unless @head.nil? || [email protected]?('VERSION') end end end end
21.842105
104
0.580723
7a27822888b94d501fd8fa68460b6343b21e663d
2,215
# -*- encoding: utf-8 -*- # # Author:: Fletcher Nichol (<[email protected]>) # # Copyright (C) 2013, Fletcher Nichol # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Kitchen # Utility methods to help ouput colorized text in a terminal. The # implementation is a compressed mashup of code from the Thor and Foreman # projects. # # @author Fletcher Nichol <[email protected]> module Color ANSI = { reset: 0, black: 30, red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, cyan: 36, white: 37, bright_black: 90, bright_red: 91, bright_green: 92, bright_yellow: 93, bright_blue: 94, bright_magenta: 95, bright_cyan: 96, bright_white: 97 }.freeze COLORS = %w{ cyan yellow green magenta blue bright_cyan bright_yellow bright_green bright_magenta bright_blue }.freeze # Returns an ansi escaped string representing a color control sequence. # # @param name [Symbol] a valid color representation, taken from # Kitchen::Color::ANSI # @return [String] an ansi escaped string if the color is valid and an # empty string otherwise def self.escape(name) return "" if name.nil? return "" unless ANSI[name] "\e[#{ANSI[name]}m" end # Returns a colorized ansi escaped string with the given color. # # @param str [String] a string to colorize # @param name [Symbol] a valid color representation, taken from # Kitchen::Color::ANSI # @return [String] an ansi escaped string if the color is valid and an # unescaped string otherwise def self.colorize(str, name) color = escape(name) color.empty? ? str : "#{color}#{str}#{escape(:reset)}" end end end
34.609375
75
0.684424
87e4a2f72aa00f1be518472677fe25511b978615
2,429
class ShibbolethSp < Formula desc "Shibboleth 2 Service Provider daemon" homepage "https://wiki.shibboleth.net/confluence/display/SHIB2" url "https://shibboleth.net/downloads/service-provider/3.0.4/shibboleth-sp-3.0.4.tar.bz2" sha256 "f5dc0fd028b74db4aaae76b59ec98e8a719c38cfe0f1d722feb2d5e0b9880cff" revision 1 bottle do rebuild 1 sha256 "8a09632277ead38ae04cb9fd0bf036cc3511d06e6a7a85745847dffee849927b" => :catalina sha256 "0955fcb426b32fcbe3875c106681d69bcc6ecdddf25f19c1ef585b1168aeeaae" => :mojave sha256 "09bec26e3cdfd3dbcb15c851589a223b5b7907771eca4ad96b9ed6b51587e37d" => :high_sierra end depends_on "apr" => :build depends_on "apr-util" => :build depends_on "pkg-config" => :build depends_on "boost" depends_on "httpd" if MacOS.version >= :high_sierra depends_on "log4shib" depends_on :macos => :yosemite depends_on "opensaml" depends_on "[email protected]" depends_on "unixodbc" depends_on "xerces-c" depends_on "xml-security-c" depends_on "xml-tooling-c" def install ENV.cxx11 args = %W[ --disable-debug --disable-dependency-tracking --disable-silent-rules --prefix=#{prefix} --localstatedir=#{var} --sysconfdir=#{etc} --with-xmltooling=#{Formula["xml-tooling-c"].opt_prefix} --with-saml=#{Formula["opensaml"].opt_prefix} --enable-apache-24 DYLD_LIBRARY_PATH=#{lib} ] if MacOS.version >= :high_sierra args << "--with-apxs24=#{Formula["httpd"].opt_bin}/apxs" end system "./configure", *args system "make", "install" end def post_install (var/"run/shibboleth/").mkpath (var/"cache/shibboleth").mkpath end plist_options :startup => true, :manual => "shibd" def plist; <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_sbin}/shibd</string> <string>-F</string> <string>-f</string> <string>-p</string> <string>#{var}/run/shibboleth/shibd.pid</string> </array> <key>RunAtLoad</key> <true/> <key>KeepAlive</key> <true/> </dict> </plist> EOS end test do system sbin/"shibd", "-t" end end
27.91954
115
0.657884
2810938ddfcde179e45d9cb26c4d714e0da67440
6,233
require 'active_support/core_ext/class/subclasses' require 'active_support/core_ext/object/blank' require 'stringio' require 'rack_console/expr_helpers' require 'rack_console/configuration' require 'rack_console/method_introspection' require 'rack_console/formatting' module RackConsole module AppHelpers include ExprHelpers, Configuration, MethodIntrospection, Formatting def with_access if has_console_access? yield else raise Error, "not authorized" end end def css_dir config[:css_dir] end def js_dir config[:js_dir] end def eval_context case context = config[:eval_context] when Proc context.call else context end end ############################### def check_access! unauthorized! unless has_console_access? end def unauthorized! raise Error, "not authorized" end def console! haml :console, locals: locals, layout: layout end def evaluate_expr! return if @result_evaled result_capture! do @stdin = StringIO.new('') @stdout = StringIO.new('') @stderr = StringIO.new('') @result_ok = false @expr = (params[:expr] || '').strip unless @expr.blank? @result_evaled = true Timeout.timeout(config[:eval_timeout] || 120) do capture_stdio! do @result = eval_expr(eval_target, @expr, eval_binding) @result_ok = true end end end end end def eval_expr et, expr, bi expr_str = "begin; #{@expr} \n; end" case et when nil, false eval(expr_str, b) when Module et.module_eval(expr_str) else et.instance_eval(expr_str) end end def evaluate_module! evaluate_expr! @show_stdio = @show_result = false if @result_ok && @result.is_a?(Module) result_capture! do @module = @result expr_for_object! @module end end end def evaluate_method! evaluate_expr! @show_stdio = @show_result = false if @result_ok && @result.is_a?(Module) result_capture! do @module = @result @method_name = params[:name] @method_kind = params[:kind].to_s =~ /i/ ? :instance_method : :method @method = @module.send(@method_kind, @method_name) rescue nil unless @method @method = @module.send(:method, @method_name) @method_kind = :method end @result = @method expr_for_object! @method, @module, @method_kind end end end def capture_stdio! @captured_stdio = true _stdin, _stdout, _stderr = $stdin, $stdout, $stderr $stdin, $stdout, $stderr = @stdin, @stdout, @stderr begin yield ensure $stdin, $stdout, $stderr = _stdin, _stdout, _stderr end end def evaluate_methods! @methods = nil result_capture! do @methods = methods_matching(params) end end def prepare_file! path = params[:splat][0] file, line = href_to_file_line(path) result_capture! do unless has_file_access? file content_type 'text/plain' return "NOT A LOADABLE FILE" end @source_file = SourceFile.new([ file, line ]).load! end end def result_capture! @result_ok = false result = yield @result_ok = true result rescue ::StandardError, ::ScriptError @error = $! @error_description = @error.inspect ensure interpret_result! end def interpret_result! @result_extended = @result.singleton_class.included_modules rescue nil @result_class = @result.class.name if @is_module = (::Module === @result) @module = @result @ancestors = @module.ancestors.drop(1) if @is_class = (::Class === @module) @superclass = @module.superclass @subclasses = @module.subclasses.sort_by{|c| c.name || ''} end @constants = @module.constants(false).sort.map{|n| [ n, const_get_safe(@module, n) ]} @methods = methods_for_module(@module) end if @is_method = (::Method === @result || ::UnboundMethod === @result || MockMethod === @result) @method = @result @method_source_location = @method.source_location begin @method_source = @method_source_location && SourceFile.new(@method_source_location).load!.narrow_to_block! rescue @method_source = nil end end end =begin def each_module &blk ObjectSpace.each_object(::Module, &blk) end =end def each_module &blk (@@each_module ||= find_modules(::Object)).each(&blk) end @@each_module = nil def find_modules mod acc = Set.new stack = [ mod ] while m = stack.pop unless acc.include?(m) acc << m m.constants(false).each do | name | val = begin const_get_safe(m, name) rescue Object nil end stack << val if Module === val end end end acc = acc.to_a acc end # const_get can cause all sorts of autoload behavior. # Therefore we temporarly disable code loading methods. def const_get_safe m, name neuter_method(::Kernel, :load, :require, :require_relative) do m.const_get(name) end rescue Object "ERROR: #{$!.inspect}" end def neuter_method mod, *names save_names = { } names.each do | name | save_name = save_names[name] = :"neuter_method_#{@@method_name_counter += 1}" mod.alias_method save_name, name end begin names.each do | name | mod.define_method(name) {|*args| nil} end yield ensure save_names.each do | name, save_name | mod.alias_method name, save_name mod.remove_method save_name end end end @@method_name_counter = 0 extend self end end
25.650206
116
0.577892
1a24818de1cec1b4df6ba602f0d2898a97e2dc63
201
FactoryGirl.define do factory :stock_item, class: Spree::StockItem do backorderable true stock_location variant after(:create) { |object| object.adjust_count_on_hand(10) } end end
20.1
63
0.726368
e940d0a7cfc6d50636d457d8f03f87452e37a4f8
2,312
# # Cookbook:: ruby_rbenv # Resource:: system_install # # Author:: Dan Webb <[email protected]> # # Copyright:: 2017-2018, Dan Webb # # 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. # # Install rbenv to a system wide location provides :rbenv_system_install property :git_url, String, default: 'https://github.com/rbenv/rbenv.git' property :git_ref, String, default: 'master' property :global_prefix, String, default: '/usr/local/rbenv' property :update_rbenv, [true, false], default: true action :install do node.run_state['root_path'] ||= {} node.run_state['root_path']['system'] = new_resource.global_prefix package package_prerequisites directory '/etc/profile.d' do owner 'root' mode '0755' end template '/etc/profile.d/rbenv.sh' do cookbook 'ruby_rbenv' source 'rbenv.sh.erb' owner 'root' mode '0755' variables(global_prefix: new_resource.global_prefix) end git new_resource.global_prefix do repository new_resource.git_url reference new_resource.git_ref checkout_branch "deploy" action :checkout if new_resource.update_rbenv == false notifies :run, 'ruby_block[Add rbenv to PATH]', :immediately notifies :run, 'bash[Initialize system rbenv]', :immediately end directory "#{new_resource.global_prefix}/plugins" do owner 'root' mode '0755' end # Initialize rbenv ruby_block 'Add rbenv to PATH' do block do ENV['PATH'] = "#{new_resource.global_prefix}/shims:#{new_resource.global_prefix}/bin:#{ENV['PATH']}" end action :nothing end bash 'Initialize system rbenv' do code %(PATH="#{new_resource.global_prefix}/bin:$PATH" rbenv init -) environment('RBENV_ROOT' => new_resource.global_prefix) action :nothing end end action_class do include Chef::Rbenv::Helpers end
28.54321
106
0.721021