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
|
---|---|---|---|---|---|
030c4c83e674622f90c4938a99c3f71c2667a764 | 2,341 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
# devise config
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
end
| 35.469697 | 87 | 0.762067 |
1ad43cf06256da410ba1f46bba4e5942f6da4731 | 766 | require File.join( File.dirname(__FILE__), 'test.rb')
class CredentialsTest < Test::Unit::TestCase
def file_contents
{:key => :value}.to_yaml
end
def test_that_credentials_file_is_not_loaded_if_it_dne
File.stubs(:exist?).returns(false)
File.expects(:open).never
Netflix::Credentials.from_file
end
def test_that_credentials_file_is_loaded_if_present
File.stubs(:exist?).returns(true)
File.expects(:open).returns(file_contents)
Netflix::Credentials.from_file
end
def test_that_values_from_file_are_present
File.stubs(:exist?).returns(true)
File.stubs(:open).returns({:key => :my_key, :secret => 'quiet!'}.to_yaml)
assert_equal :my_key, Netflix::Credentials.from_file.key
end
end
| 27.357143 | 78 | 0.712794 |
7a94cc2237acb4611bded5b4ecb5b5dc708d5f0e | 5,247 | module Fl::Framework::Comment::Neo4j
# Implementation of the comment object for a Neo4j database.
#
# === Properties
# This class defines the following properties:
# - +title+ is a string containing a title for the comment.
# - +contents+ is a astring containing the contents of the comment.
# - +created_at+ is an Integer containing the UNIX creation time.
# - +updated_at+ is an Integer containing the UNIX modification time.
#
# === Associations
# Fl::Framework::Comment::Neo4j::Comment defines a number of associations:
# - *commentable* is the object associated with this comment (the _commentable_ object).
# - *author* is the entity (typically a user) that created the comment.
# - *comments* is the list of comments associated with this comment (and therefore, the comment's
# subcomments that make up the conversation about the comment).
class Comment
include Neo4j::ActiveNode
include Fl::Framework::Comment::Access
include Fl::Framework::Comment::Validation
include Fl::Framework::Comment::ModelHash
include Fl::Framework::Comment::TitleManagement
include Fl::Framework::Comment::AttributeFilters
include Fl::Framework::Comment::Helper
include Fl::Framework::Comment::Commentable
# @!attribute [rw] title
# The comment title; typically generated from the first (40) character of the contents.
# @return [String] Returns the comment title.
property :title, type: String
# @!attribute [rw] contents
# The comment contents.
# @return [String] Returns the comment contents.
property :contents, type: String
# @!attribute [rw] created_at
# The time when the comment was created.
# @return [Integer] Returns the timestamp of the creation time of the comment.
property :created_at, type: Integer
# @!attribute [rw] updated_at
# The time when the comment was updated.
# @return [Integer] Returns the timestamp of the modification time of the comment.
property :updated_at, type: Integer
# @!attribute [r] commentable
# The object to which the comment is attached.
# @return [Object] Returns the object to which the comment is attached. This object is expected
# to have included the {Fl::Framework::Comment::Commentable} module and registered via
# {Fl::Framework::Comment::Commentable#has_comments}.
has_one :out, :commentable, rel_class: :'Fl::Framework::Neo4j::Rel::Core::CommentFor'
# @!attribute [r] author
# The entity that created the comment, and therefore owns it.
# @return [Object] Returns the object that created the comment.
has_one :in, :author, rel_class: :'Fl::Framework::Neo4j::Rel::Core::IsOwnerOf'
# has_comments defines the :comments association
# @!attribute [rw] comments
# The comments for this comment.
# It is possible to comment on a comment.
# @return [Neo4j::ActiveNode::Query] Returns a Neo4j ActiveNode association listing comments.
has_comments
before_create :_populate_timestamps
before_save :_update_updated_at
# Initializer.
#
# @param attrs [Hash] A hash of initialization parameters.
# @option attrs [Object, Hash, String] :author The comment author. The value is resolved via a call
# to {Fl::Framework::Comment::Comment::Helper.author_from_parameter}.
# @option attrs [Object, Hash, String] :commentable The associated commentable. The value is resolved via
# a call to {Fl::Framework::Comment::Comment::Helper.commentable_from_parameter}.
# @option attrs [String] :contents The comment contents.
# @option attrs [String] :title The comment title; if not given, the first 40 characters of the content
# are used.
def initialize(attrs = {})
begin
attrs[:author] = Fl::Framework::Comment::Helper.author_from_parameter(attrs)
rescue => exc
self.errors[:author] << exc.message
end
begin
attrs[:commentable] = Fl::Framework::Comment::Helper.commentable_from_parameter(attrs)
rescue => exc
self.errors[:commentable] << exc.message
end
@needs_updated_at = true
super(attrs)
end
# @!visibility private
alias _original_created_at= created_at=
# @!visibility private
alias _original_updated_at= updated_at=
# Set the creation time.
#
# @param ctime The creation time; this can be an integer UNIX timestamp, or a TimeWithZone instance.
def created_at=(ctime)
ctime = ctime.to_i unless ctime.is_a?(Integer)
self._original_created_at=(ctime)
end
# Set the update time.
#
# @param utime The update time; this can be an integer UNIX timestamp, or a TimeWithZone instance.
def updated_at=(utime)
@needs_updated_at = false
utime = utime.to_i unless utime.is_a?(Integer)
self._original_updated_at=(utime)
end
private
def _populate_timestamps()
ts = Time.new.to_i
_original_created_at=(ts) if self.created_at.blank?
_original_updated_at=(ts) if self.updated_at.blank?
end
def _update_updated_at()
if @needs_updated_at
ts = Time.new.to_i
_original_updated_at=(ts)
end
@needs_updated_at = true
end
end
end
| 36.4375 | 109 | 0.695826 |
5db225a1e0907be0a5e159f995ab10caa2261629 | 1,190 | module AnyStyle
describe Format::CSL do
let(:ap) { Parser.new }
let(:refs) {[
'Derrida, J. (c.1967). L’écriture et la différence (1 éd.). Paris: Éditions du Seuil.',
'Perec, Georges. A Void. London: The Harvill Press, 1995. p.108.',
]}
it 'Converts parse results to CSL items' do
items = ap.parse(refs, format: 'csl')
expect(items).to be_a(::Array)
expect(items.size).to eq(refs.length)
expect(items[0][:type]).to eq('book')
expect(items[0][:author][0][:family]).to eq('Derrida')
expect(items[0][:title]).to eq('L’écriture et la différence')
expect(items[0][:issued]).to eq('1967~')
expect(items[1][:issued]).to eq('1995')
end
it 'Supports CiteProc date syntax' do
items = ap.parse(refs, format: 'csl', date_format: 'citeproc')
expect(items[0][:issued]).to eq({ :'date-parts' => [[1967]], :circa => true })
expect(items[1][:issued]).to eq({ :'date-parts' => [[1995]] })
end
it 'Converts Core Data to CSL without errors' do
items = resource('parser/core.xml', format: 'csl')
expect(items).to be_a(::Array)
expect(items.size).to be > 1000
end
end
end
| 34 | 93 | 0.597479 |
4a636122d96b1494e81e6c569fd0f2e93569df18 | 449 | require "test_helper"
class WhiteListTest < ActiveModel::TestCase
def setup
@white_list = ActiveModel::MassAssignmentSecurity::WhiteList.new
@included_key = 'first_name'
@white_list += [ @included_key ]
end
test "deny? is false for included items" do
assert_equal false, @white_list.deny?(@included_key)
end
test "deny? is true for non-included items" do
assert_equal true, @white_list.deny?('admin')
end
end
| 22.45 | 70 | 0.712695 |
3863a2c987d2baad58c13c97132950db2f4bb8b3 | 1,625 | module Math
def distance(a, b)
unless (a.is_a?(Hash) && b.is_a?(Hash) && a.keys == b.keys) || (a.is_a?(Array) && b.is_a?(Array) && a.size == b.size)
raise ArgumentError, "Arguments must be Hashes with identical keys or Arrays of the same size"
end
sum = 0
a.keys.each { |k| sum += (a[k] - b[k]) ** 2 } if a.is_a?(Hash)
a.each_with_index { |v, i| sum += (a[i] - b[i]) ** 2 } if a.is_a?(Array)
sqrt(sum)
end
def multiple_regression(dx, dy, dz)
regression = {}
regression[:slope], regression[:offset] = {}, {}
size = dx.size
raise "arguments not same length!" unless size == dy.size && size == dz.size
if size == 1
regression[:slope] = { :x => dx[0], :y => dy[0], :z => dz[0] }
regression[:offset] = { :x => 0, :y => 0, :z => 0 }
return regression
end
sxx = syy = szz = sxy = szx = syz = sx = sy = sz = 0
dx.zip(dy, dz).each do |x, y, z|
sxx += x ** 2
syy += y ** 2
szz += z ** 2
sxy += x * y
szx += z * x
syz += y * z
sx += x
sy += y
sz += z
end
regression[:slope][:x] = ( size * sxy - sx * sz ) / ( size * sxx - sx ** 2 ).to_f
regression[:slope][:y] = ( size * syz - sz * sy ) / ( size * syy - sz ** 2 ).to_f
regression[:slope][:z] = ( size * syz - sz * sy ) / ( size * szz - sy ** 2 ).to_f
regression[:offset][:x] = (sz - regression[:slope][:x] * sx) / size
regression[:offset][:y] = (sy - regression[:slope][:y] * sz) / size
regression[:offset][:z] = (sx - regression[:slope][:z] * sy) / size
regression
end
end
| 33.163265 | 121 | 0.493538 |
910e5b0fb6f864024fea566cadacff6a32a21844 | 817 | require_relative 'connection'
class Request
class << self
def where(resource_path, query = {}, options = {})
response, status = get_json(resource_path, query)
status == 200 ? response : errors(response)
end
def get(id, query)
response, status = get_json(id, query)
status == 200 ? response : errors(response)
end
def errors(response)
error = { errors: { status: response["status"], message: response["message"] } }
response.merge(error)
end
def get_json(root_path, query = {})
query_string = query.map{|k,v| "#{k}=#{v}"}.join("&")
path = query.empty?? root_path : "#{root_path}?#{query_string}"
response = api.get(path)
[JSON.parse(response.body), response.status]
end
def api
Connection.api
end
end
end | 27.233333 | 86 | 0.614443 |
1826c018e9bcf736c374fd29a01a223bcd0e75f1 | 1,535 | # frozen_string_literal: true
require 'structures/word'
require 'utility/interleave_arrays'
require 'utility/presets'
# Owoify module is the main module where owoify function lies in.
# Since owoify is literally just a function, users are expected to invoke owoify by calling Owoify.owoify().
module Owoify
# The main entry point of the owoify function.
# Pass in the source string and the desired owoify level.
def self.owoify(source, level = 'owo')
word_matches = source.scan(/[^\s]+/).flatten
space_matches = source.scan(/\s+/).flatten
words = word_matches.map { |x| Word.new(x) }
spaces = space_matches.map { |x| Word.new(x) }
actual_level = level.downcase
words.map! do |w|
SPECIFIC_WORD_MAPPING_LIST.each do |f|
w = f.call(w)
end
case actual_level
when 'owo'
OWO_MAPPING_LIST.each do |f|
w = f.call(w)
end
when 'uwu'
UWU_MAPPING_LIST.each do |f|
w = f.call(w)
end
OWO_MAPPING_LIST.each do |f|
w = f.call(w)
end
when 'uvu'
UVU_MAPPING_LIST.each do |f|
w = f.call(w)
end
UWU_MAPPING_LIST.each do |f|
w = f.call(w)
end
OWO_MAPPING_LIST.each do |f|
w = f.call(w)
end
else
raise ArgumentError, 'The specified owoify level is not supported.'
end
w
end
result = interleave_arrays(words, spaces)
result_strings = result.map(&:to_s)
result_strings.join
end
end
| 27.909091 | 108 | 0.613681 |
1a90fe0b57e822758e2e4b7d96ad9d220c15a686 | 993 | class UsersController < ApplicationController
get '/signup' do
if !logged_in?
erb :'users/create_user'
else
redirect to '/jobs'
end
end
post '/signup' do
if !logged_in?
user = User.new(params)
if user.save
session[:user_id] = user.id
redirect to '/jobs'
else
redirect to '/signup'
end
else
redirect to '/jobs'
end
end
get '/login' do
if !logged_in?
erb :'users/login'
else
redirect '/jobs'
end
end
post '/login' do
@user = User.find_by(username: params[:username])
if @user && @user.authenticate(params[:password])
session[:user_id] = @user.id
redirect "/jobs"
else
erb :'users/error'
end
end
get '/logout' do
if logged_in?
session.clear
redirect to '/login'
else
redirect to '/'
end
end
get '/users/:slug' do
@user = User.find_by_slug(params[:slug])
erb :'users/show'
end
end
| 17.421053 | 53 | 0.566969 |
d5f783eed8e076a19deb801fe0d037b45d9cae3c | 152 | # frozen_string_literal: true
class Query::HerbariumAll < Query::HerbariumBase
def initialize_flavor
add_sort_order_to_title
super
end
end
| 16.888889 | 48 | 0.782895 |
289c35e8ad3f3744c4ccf50cbf6a1d6d7aa4a308 | 905 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ptt/version'
Gem::Specification.new do |spec|
spec.name = 'ptt'
spec.version = PTT::VERSION
spec.authors = ['Alexander Sulim']
spec.email = ['[email protected]']
spec.summary = %q{PTT - Pneumatic Tube Transport}
spec.description = %q{PTT - messaging based on AMQP and some conventions}
spec.homepage = ''
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_runtime_dependency 'bunny'
spec.add_runtime_dependency 'json'
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'rspec'
end
| 33.518519 | 77 | 0.656354 |
bbe3fa71ac15976f063b68baf330b19d0417b21d | 561 | module Ufo::Utils
class Squeezer
def initialize(data)
@data = data
end
def squeeze(new_data=nil)
data = new_data.nil? ? @data : new_data
case data
when Array
data.map! { |v| squeeze(v) }
when Hash
data.each_with_object({}) do |(k,v), squeezed|
# only remove nil and empty Array values within Hash structures
squeezed[k] = squeeze(v) unless v.nil? || v.is_a?(Array) && v.empty?
squeezed
end
else
data # do not transform
end
end
end
end
| 22.44 | 78 | 0.56328 |
1c6d150e0043a6a6291dd1d7c450cc1db3113c21 | 2,135 | require 'yaml'
use_inline_resources # ~FC113
def whyrun_supported?
true
end
action :create do
user 'prometheus' do
system true
shell '/bin/false'
home new_resource.home_dir
end
directory new_resource.home_dir do
action :create
recursive true
mode '0755'
owner 'prometheus'
group 'prometheus'
end
directory new_resource.home_dir + '/bin' do
action :create
owner 'prometheus'
group 'prometheus'
mode 0755
end
remote_file Chef::Config[:file_cache_path] + '/' + new_resource.filename do
source new_resource.uri
checksum new_resource.checksum
action :create_if_missing
end
execute 'untar alertmanager' do
cwd Chef::Config[:file_cache_path]
command 'tar zxf ' + new_resource.filename
creates Chef::Config[:file_cache_path] + '/' + new_resource.pathname + '/alertmanager'
end
%w(alertmanager amtool).each do |p|
execute 'install ' + p + 'binaries' do
cwd Chef::Config[:file_cache_path] + '/' + new_resource.pathname
command 'cp ' + p + ' /opt/prometheus/bin/' + p + '-' + new_resource.version
creates '/opt/prometheus/bin/' + p + '-' + new_resource.version
end
end
template '/etc/default/alertmanager' do
source new_resource.template_name
cookbook new_resource.cookbook
owner 'prometheus'
group 'prometheus'
variables(
args: new_resource.arguments
)
end
systemd_service 'alertmanager' do
unit do
description 'Alertmanager for Prometheus Monitoring'
documentation 'https://www.prometheus.io'
after %w( multi-user.service )
end
service do
type 'simple'
exec_start '/opt/prometheus/bin/alertmanager-' + new_resource.version + ' $ARGS'
exec_reload '/bin/kill -HUP $MAINPID'
service_environment_file '/etc/default/alertmanager'
timeout_stop_sec '20s'
send_sigkill false
end
end
service 'alertmanager' do
action [:start, :enable]
subscribes :restart, 'template[/etc/default/alertmanager]',:delayed
subscribes :restart, 'systemd_service[/etc/systemd/system/alertmanager.service]',:delayed
end
end
| 28.092105 | 93 | 0.689461 |
79bfb5e441aefa66fd7d1e074cb5170e4a9a2f49 | 40 | # CHEF-5199 regression test.
return nil
| 13.333333 | 28 | 0.775 |
61ab8b5713b9fe875051f991dc8f32a28daf85c4 | 4,959 | require 'uri'
require 'nokogiri'
require 'thread/pool'
class User < ActiveRecord::Base
has_one :session, primary_key: :niconico_id, dependent: :destroy
has_many :mylists, dependent: :destroy
has_many :entries, through: :mylists
has_many :videos, ->{uniq}, through: :entries
has_many :tags, ->{ select('count(tags.id) as taggings_count, tags.id, tags.name').group('tags.id') }, through: :videos
validates :niconico_id, presence: true, uniqueness: true
TOP_URL = URI.parse('http://www.nicovideo.jp/my/mylist')
def self.authenticate(params)
session = Session.create_by_authenticating(params)
return nil if session.nil?
user = User.find_by(niconico_id: session.user_id)
user = User.create!(niconico_id: session.user_id) if user.nil?
user.fetch_profile
user.fetch_mylist
user.fetch_video_detail
user.save
user
end
def fetch_profile
return self if self.session.nil?
http = Net::HTTP.new(TOP_URL.host, TOP_URL.port)
response = http.start do |http|
uri = URI::Generic.build(path: TOP_URL.path, query: TOP_URL.query)
req = Net::HTTP::Get.new(uri.to_s)
req['Cookie'] = self.session.cookie
http.request(req)
end
doc = Nokogiri::HTML.parse(response.body)
img = doc.xpath('//div[@class="userDetail"]/div[@class="avatar"]/*/img')[0]
uri = URI.parse(img.attribute('src').value)
self.avatar = URI::HTTP.build(host: uri.host, path: uri.path)
self.nickname = img.attribute('alt').value
self
end
def fetch_mylist
save_entries = lambda do |mylist, entries|
entries.to_a.each do |entry|
next if entry['item_type'].to_i != 0
video_attributes = {
video_id: entry['item_data']['video_id'],
title: entry['item_data']['title'],
thumbnail_url: entry['item_data']['thumbnail_url'],
group_type: entry['item_data']['group_type'],
watch_id: entry['item_data']['watch_id'],
is_deleting: entry['item_data']['deleted'].to_i != 0,
created_time: Time.at(entry['item_data']['first_retrieve'].to_i),
updated_time: Time.at(entry['item_data']['update_time'].to_i),
play_count: entry['item_data']['view_counter'].to_i,
mylist_count: entry['item_data']['mylist_counter'].to_i,
comment_count: entry['item_data']['num_res'].to_i,
seconds: entry['item_data']['length_seconds'].to_i,
latest_comment: entry['item_data']['last_res_body'],
}
video = Video.find_by(video_id: entry['item_data']['video_id'])
if video.nil? then
video = Video.create(video_attributes)
else
video.update(video_attributes)
end
entry_attributes = {
mylist_id: mylist.id,
video_id: video.id,
item_type: entry['item_type'],
item_id: entry['item_id'],
created_time: Time.at(entry['create_time'].to_i),
updated_time: Time.at(entry['update_time'].to_i),
description: entry['description'],
}
entry = Entry.find_by(mylist_id: mylist.id, video_id: video.id)
if entry.nil? then
entry = Entry.create(entry_attributes)
else
entry.update(entry_attributes)
end
end
end
mylist = Mylist.find_by(user_id: self.id, group_id: nil)
mylist = Mylist.create(user_id: self.id, group_id: nil) if mylist.nil?
save_entries[mylist, NicoApi::Mylist::Deflist.new(self.session).list]
mylist_group_list = NicoApi::Mylist::MylistGroup.new(self.session).list.to_a
mylist_group_list.each do |group|
group_attributes = {
group_id: group['id'].to_i,
user_id: self.id,
name: group['name'],
description: group['description'],
is_public: group['public'].to_i != 0,
sort_order: group['sort_order'].to_i,
created_time: Time.at(group['create_time'].to_i),
updated_time: Time.at(group['update_time'].to_i)
}
mylist = Mylist.find_by(user_id: self.id, group_id: group['id'].to_i)
if mylist.nil? then
mylist = Mylist.create(group_attributes)
else
mylist.update(group_attributes)
end
save_entries[mylist, NicoApi::Mylist::Mylist.new(self.session, mylist.group_id).list]
end
end
def fetch_video_detail
jobs = 20
self.videos.find_in_batches(batch_size: jobs) do |videos|
pool = Thread.pool(jobs)
videos.each do |video|
pool.process do
detail = NicoApi::Ext::Getthumbinfo.new.get(video.video_id)
next if detail.nil?
video.description = detail['description']
video.tag_list.add(*detail['tags']['tag'])
end
end
pool.shutdown
videos.each(&:save)
end
end
end
| 33.965753 | 121 | 0.616455 |
4aa2244e6199bdc463fbac5be5a7cc430fc2d91e | 1,923 | class GmtAT4 < Formula
desc "Manipulation of geographic and Cartesian data sets"
homepage "https://gmt.soest.hawaii.edu/"
url "ftp://ftp.soest.hawaii.edu/gmt/gmt-4.5.18-src.tar.bz2"
mirror "https://fossies.org/linux/misc/GMT/gmt-4.5.18-src.tar.bz2"
mirror "https://mirrors.ustc.edu.cn/gmt/gmt-4.5.18-src.tar.bz2"
sha256 "27c30b516c317fed8e44efa84a0262f866521d80cfe76a61bf12952efb522b63"
revision 5
bottle do
sha256 "e3350e06c424fe32e0b20532c0589affb36406930747f6b8c41d7c510eb235bd" => :mojave
sha256 "5741caf61b491bfe27f4b3aff36550085653a0bfd4cdc7d58e1df5f5258d2a2c" => :high_sierra
sha256 "2a633e4769f899759837fa328f31fea2ac181599d6b0b1f54e4402fd9d44f423" => :sierra
end
keg_only :versioned_formula
depends_on "gdal"
depends_on "netcdf"
resource "gshhg" do
url "ftp://ftp.soest.hawaii.edu/gmt/gshhg-gmt-2.3.7.tar.gz"
mirror "https://fossies.org/linux/misc/GMT/gshhg-gmt-2.3.7.tar.gz"
mirror "https://mirrors.ustc.edu.cn/gmt/gshhg-gmt-2.3.7.tar.gz"
sha256 "9bb1a956fca0718c083bef842e625797535a00ce81f175df08b042c2a92cfe7f"
end
def install
ENV.deparallelize # Parallel builds don't work due to missing makefile dependencies
system "./configure", "--prefix=#{prefix}",
"--datadir=#{share}/gmt4",
"--enable-gdal=#{Formula["gdal"].opt_prefix}",
"--enable-netcdf=#{Formula["netcdf"].opt_prefix}",
"--enable-shared",
"--enable-triangle",
"--disable-xgrid",
"--disable-mex"
system "make"
system "make", "install-gmt", "install-data", "install-suppl", "install-man"
(share/"gmt4").install resource("gshhg")
end
test do
system "#{bin}/gmt pscoast -R-90/-70/0/20 -JM6i -P -Ba5 -Gchocolate > test.ps"
assert_predicate testpath/"test.ps", :exist?
end
end
| 40.0625 | 93 | 0.658346 |
389e4348db51116cbd1944c5bff372d9a6bb7ec3 | 91 | class HomeController < ApplicationController
def index
end
def conversion
end
end
| 11.375 | 44 | 0.769231 |
331f49d207a7800ab35464a288be1949561e23a9 | 175 | # frozen_string_literal: true
# Copyright The OpenTelemetry Authors
#
# SPDX-License-Identifier: Apache-2.0
require 'minitest/autorun'
require 'opentelemetry-propagator-b3'
| 19.444444 | 37 | 0.8 |
7a5e437716007a37c1c5e307fe55fb1c87e9d2e3 | 803 | module StyleTestMacros
def xml(part)
File.read(File.join(File.dirname(__FILE__), "data", "styles", "#{part}_styles.xml")).strip
end
def self.included(base)
attr_reader :style
base.extend ClassMethods
end
module ClassMethods
def it_should_output_correct_xml(style_xml: nil)
it "should be able to output the correct XML" do
if style_xml.nil?
style_xml = described_class.to_s.split(/::/).last
style_xml = style_xml.gsub(/(.)([A-Z])/, '\1_\2').downcase
end
generated_xml = Nokogiri::XML::Builder.new do |xml|
xml.styleFoo("xmlns:w" => "http://wnamespace.com") {
style.build_xml(xml)
}
end.to_xml
expect(generated_xml).to eq(xml(style_xml) + "\n")
end
end
end
end
| 23.617647 | 94 | 0.612702 |
089913f29c2fb925b54574556f0e0df4f50b181d | 3,027 | class StaticDocument < ActiveRecord::Base
self.abstract_class = true
# === Associations
belongs_to :user
belongs_to :shipping_address, :polymorphic => true
belongs_to :billing_address, :polymorphic => true
belongs_to :payment_method
# === Validations
validates_presence_of :billing_address
validates_associated :billing_address, :message => 'is incomplete'
# === AR Callbacks
before_create :assign_uuid
# === Methods
def taxed_price
return ((lines.sum("taxed_price") + total_taxed_shipping_price) - rebate - tax_reduction)
end
def total_gross_shipping_price
return gross_price + shipping_cost
end
def gross_price
return (lines.sum("gross_price") - rebate)
end
def products_taxed_price
return ((lines.sum("taxed_price")) - rebate - tax_reduction)
end
def weight
weight = 0.0
lines.each do |l|
weight += l.quantity * l.weight unless l.weight.blank?
end
return weight
end
def taxes
product_taxes = lines.sum('taxes')
return product_taxes
end
def total_taxes
taxes + shipping_taxes - tax_reduction
end
def total_taxed_shipping_price
shipping_cost + shipping_taxes
end
# Tax reduction that happens due to a rebate on the whole order
def tax_reduction
if has_rebate?
previous_taxes = taxes
previous_gross_price = gross_price + rebate
rebate_in_percent_of_gross = (BigDecimal.new("100.0") / previous_gross_price) * rebate
tax_reduction = (previous_taxes / BigDecimal.new("100.0")) * rebate_in_percent_of_gross
else
tax_reduction = BigDecimal.new("0.0")
end
return tax_reduction
end
def has_rebate?
!rebate.blank? and rebate > BigDecimal.new("0.0")
end
def products
self.lines.collect(&:product).compact
end
def suppliers
products.collect(&:supplier).uniq
end
def lines_by_supplier(supplier)
supplier_lines = []
lines.each do |line|
supplier_lines << line if !line.product.blank? and line.product.supplier == supplier
end
return supplier_lines
end
# Unfortunate duplication introduced by the splitting of Invoices from Documents.
# must be refactored.
def notification_email_addresses
emails = []
if self.billing_address.email.blank? and self.shipping_address.email.blank? and !self.user.nil?
emails << self.user.email
elsif self.shipping_address.nil? and !self.billing_address.email.blank?
emails << self.billing_address.email
else
if (!self.user.nil? and !self.user.email.blank?)
emails << self.user.email
end
emails << self.billing_address.email unless self.billing_address.email.blank?
emails << self.shipping_address.email unless self.shipping_address.email.blank?
end
return emails.uniq
end
# ActiveRecord before_* and after_* callbacks
def assign_uuid
self.uuid = UUIDTools::UUID.random_create.to_s
self.document_number ||= Numerator.get_number
end
end
| 24.216 | 99 | 0.700694 |
bb71a55447a6bd2443e1c861126d8b4ca6e1da09 | 4,325 | require_relative "../../test_helper"
class Test::AdminUi::Login::TestInvite < Minitest::Capybara::Test
include Capybara::Screenshot::MiniTestPlugin
include ApiUmbrellaTestHelpers::AdminAuth
include ApiUmbrellaTestHelpers::Setup
include ApiUmbrellaTestHelpers::DelayedJob
def setup
super
setup_server
Admin.delete_all
response = Typhoeus.delete("http://127.0.0.1:#{$config["mailhog"]["api_port"]}/api/v1/messages")
assert_response_code(200, response)
end
def test_defaults_to_sending_invite_for_new_accounts
admin_login
# Create admin
visit "/admin/#/admins/new"
assert_text("Add Admin")
fill_in "Email", :with => "#{unique_test_id}@example.com"
assert_equal(true, find_field("Send invite email", :visible => :all).checked?)
check "Superuser"
click_button "Save"
assert_text("Successfully saved the admin")
# Logout
::Capybara.reset_session!
# Find admin record
admin = Admin.where(:username => "#{unique_test_id.downcase}@example.com").first
assert(admin)
# Find sent email
messages = delayed_job_sent_messages
assert_equal(1, messages.length)
message = messages.first
# To
assert_equal(["#{unique_test_id.downcase}@example.com"], message["Content"]["Headers"]["To"])
# Subject
assert_equal(["API Umbrella Admin Access"], message["Content"]["Headers"]["Subject"])
# Password reset URL in body
assert_match(%r{http://localhost/admins/password/edit\?invite=true&reset_password_token=[^" ]+}, message["_mime_parts"]["text/html; charset=UTF-8"]["Body"])
assert_match(%r{http://localhost/admins/password/edit\?invite=true&reset_password_token=[^" ]+}, message["_mime_parts"]["text/plain; charset=UTF-8"]["Body"])
# Follow link to reset URL
reset_url = message["_mime_parts"]["text/plain; charset=UTF-8"]["Body"].match(%r{/admins/password/edit\?invite=true&reset_password_token=[^" ]+})[0]
visit reset_url
fill_in "New Password", :with => "password123456"
fill_in "Confirm New Password", :with => "password123456"
click_button "Change My Password"
# Ensure the user gets logged in.
assert_logged_in(admin)
end
def test_invites_can_be_skipped_for_new_users
admin_login
# Create admin
visit "/admin/#/admins/new"
assert_text("Add Admin")
fill_in "Email", :with => "#{unique_test_id}@example.com"
label_uncheck "Send invite email"
check "Superuser"
click_button "Save"
assert_text("Successfully saved the admin")
# Find admin record
admin = Admin.where(:username => "#{unique_test_id.downcase}@example.com").first
assert(admin)
# No email
assert_equal(0, delayed_job_sent_messages.length)
end
def test_invites_can_be_resent
admin_login
admin = FactoryBot.create(:admin)
assert_nil(admin.notes)
# Ensure edits don't resend invites by default.
visit "/admin/#/admins/#{admin.id}/edit"
assert_text("Edit Admin")
assert_field("Email", :with => admin.email)
fill_in "Notes", :with => "Foo"
assert_equal(false, find_field("Resend invite email", :visible => :all).checked?)
click_button "Save"
assert_text("Successfully saved the admin")
page.execute_script("window.PNotifyRemoveAll()")
admin.reload
assert_equal("Foo", admin.notes)
assert_equal(0, delayed_job_sent_messages.length)
# Force the invite to be resent.
visit "/admin/#/admins/#{admin.id}/edit"
assert_text("Edit Admin")
assert_field("Email", :with => admin.email)
fill_in "Notes", :with => "Bar"
assert_equal(false, find_field("Resend invite email", :visible => :all).checked?)
label_check "Resend invite email"
click_button "Save"
assert_text("Successfully saved the admin")
page.execute_script("window.PNotifyRemoveAll()")
admin.reload
assert_equal("Bar", admin.notes)
messages = delayed_job_sent_messages
assert_equal(1, messages.length)
message = messages.first
assert_equal(["API Umbrella Admin Access"], message["Content"]["Headers"]["Subject"])
admin.update(:current_sign_in_at => Time.now.utc)
visit "/admin/#/admins/#{admin.id}/edit"
assert_text("Edit Admin")
assert_field("Email", :with => admin.email)
refute_field("Resend invite email", :visible => :all)
end
end
| 34.055118 | 164 | 0.696416 |
ff05fc9c470b1b167037159cd093634c1b36affd | 2,180 | class Jenkins < Formula
desc "Extendable open source continuous integration server"
homepage "https://jenkins.io/"
url "http://mirrors.jenkins.io/war/2.224/jenkins.war"
sha256 "39ea55b2cca655827291c152943b9639249242e5e0a9cc1ef17db790e28b7ae4"
head do
url "https://github.com/jenkinsci/jenkins.git"
depends_on "maven" => :build
end
bottle :unneeded
depends_on :java => "1.8"
def install
if build.head?
system "mvn", "clean", "install", "-pl", "war", "-am", "-DskipTests"
else
system "jar", "xvf", "jenkins.war"
end
libexec.install Dir["**/jenkins.war", "**/jenkins-cli.jar"]
bin.write_jar_script libexec/"jenkins.war", "jenkins", :java_version => "1.8"
bin.write_jar_script libexec/"jenkins-cli.jar", "jenkins-cli", :java_version => "1.8"
end
def caveats; <<~EOS
Note: When using launchctl the port will be 8080.
EOS
end
plist_options :manual => "jenkins"
def plist; <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>/usr/libexec/java_home</string>
<string>-v</string>
<string>1.8</string>
<string>--exec</string>
<string>java</string>
<string>-Dmail.smtp.starttls.enable=true</string>
<string>-jar</string>
<string>#{opt_libexec}/jenkins.war</string>
<string>--httpListenAddress=127.0.0.1</string>
<string>--httpPort=8080</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
EOS
end
test do
ENV["JENKINS_HOME"] = testpath
ENV.prepend "_JAVA_OPTIONS", "-Djava.io.tmpdir=#{testpath}"
pid = fork do
exec "#{bin}/jenkins"
end
sleep 60
begin
assert_match /Welcome to Jenkins!|Unlock Jenkins|Authentication required/, shell_output("curl localhost:8080/")
ensure
Process.kill("SIGINT", pid)
Process.wait(pid)
end
end
end
| 28.311688 | 117 | 0.616055 |
e937dc612c67e75a7a5da30a775729db9216b869 | 3,508 | # frozen_string_literal: true
class PathHelperTest
include JekyllAdmin::PathHelper
attr_accessor :params, :request_payload, :namespace
def initialize(params = {}, request_payload = {}, namespace = nil)
@params = params
@request_payload = request_payload
@namespace = namespace
end
def collection
JekyllAdmin.site.collections["puppies"] if namespace == "collections"
end
end
RSpec.describe JekyllAdmin::PathHelper do
let(:path) { "page" }
let(:ext) { "md" }
let(:splat) { ["/"] }
let(:params) { { "path" => path, "ext" => ext, "splat" => splat } }
let(:request_payload) { {} }
let(:site_source) { fixture_path("site") }
let(:namespace) { "pages" }
let(:subject) do
PathHelperTest.new(params, request_payload, namespace)
end
context "sanitization" do
let(:relative_path) { "/foo/bar" }
let(:path) { "#{site_source}/foo/bar" }
it "sanitizes a normal path" do
expect(subject.sanitized_path("foo/bar")).to eql(path)
expect(subject.sanitized_relative_path("foo/bar")).to eql(relative_path)
end
it "sanitizes a relative path" do
expect(subject.sanitized_path("../foo/bar")).to eql(path)
expect(subject.sanitized_relative_path("../foo/bar")).to eql(relative_path)
end
it "sanitizes an absolute path" do
expect(subject.sanitized_path(path)).to eql(path)
expect(subject.sanitized_relative_path(path)).to eql(relative_path)
end
end
it "returns the filename" do
expect(subject.filename).to eql("page.md")
end
it "returns the relative path" do
expect(subject.relative_path).to eql("/page.md")
end
context "write path" do
context "when the file isn't renamed" do
it "returns the write path" do
expect(subject.write_path).to eql("#{site_source}/page.md")
expect(subject.relative_write_path).to eql("/page.md")
end
it "knows it's not renamed" do
expect(subject).to_not be_renamed
end
end
context "when the file is renamed" do
let(:request_payload) { { "path" => "renamed.md" } }
it "returns the write path" do
expect(subject.write_path).to eql("#{site_source}/renamed.md")
expect(subject.relative_write_path).to eql("/renamed.md")
end
it "knows it's renamed" do
expect(subject).to be_renamed
end
end
end
it "knows the directory path" do
expect(subject.send(:directory_path)).to eql("#{site_source}/")
end
context "subdir" do
let(:splat) { ["foo"] }
it "knows the directory path" do
expect(subject.send(:directory_path)).to eql("#{site_source}/foo")
end
it "returns the path" do
expect(subject.path).to eql("#{site_source}/foo/page.md")
end
it "returns the relative path" do
expect(subject.relative_path).to eql("/foo/page.md")
end
it "returns the write path" do
expect(subject.write_path).to eql("#{site_source}/foo/page.md")
end
end
context "collections" do
let(:namespace) { "collections" }
it "knows the directory path" do
expect(subject.send(:directory_path)).to eql("#{site_source}/_puppies")
end
it "returns the path" do
expect(subject.path).to eql("#{site_source}/_puppies/page.md")
end
it "returns the relative path" do
expect(subject.relative_path).to eql("/_puppies/page.md")
end
it "returns the write path" do
expect(subject.write_path).to eql("#{site_source}/_puppies/page.md")
end
end
end
| 27.40625 | 81 | 0.654504 |
e2a9dfaac64d36da4c576130710475c2977d0522 | 1,138 | module ApplicationHelper
def admin_types
%w(AdminUser)
end
def active?(path)
"active" if current_page?(path)
end
def employee?
current_user.try(:type) == 'Employee'
end
def admin?
current_user.try(:type) == 'AdminUser'
end
def flash_message_manager
msg = flash[:notice] || flash[:alert] || flash[:error]
notify(msg).html_safe if msg
end
def notify(msg, btn_msg = 'Ok')
javascript_tag %Q[notify("#{msg}", "#{btn_msg}")]
end
def status_label(s)
badge = case s.downcase
when 'submitted', 'pending' then 'blue-red'
when 'approved', 'confirmed' then 'green-blue'
when 'rejected' then 'red-purple'
else 'red-purple'
end
content_tag(:span, s, class: "badge-custom badge-custom-#{badge}")
end
def svg_tag(f, svg_class="inine", width: nil, height: nil)
f = f.then { |x| x.end_with?('.svg') ? x : "#{x}.svg" }
width = width ? "#{width}px" : "100%"
height = height ? "#{height}px" : "100%"
<<~EOF.html_safe
<div class="#{svg_class}" style="width: #{width} ; height: #{height}%">
#{IO.read("#{Rails.root}/app/assets/glyphicons/inline-glyphicons/#{f}")}
</div>
EOF
end
end
| 22.313725 | 76 | 0.639719 |
4a757c4d6663628bbe2477a32307ffb23ab0f96d | 1,932 | # Encoding: utf-8
#
# This is auto-generated code, changes will be overwritten.
#
# Copyright:: Copyright 2021, Google Inc. All Rights Reserved.
# License:: Licensed under the Apache License, Version 2.0.
#
# Code generated by AdsCommon library 1.0.2 on 2021-02-12 12:58:55.
require 'ads_common/savon_service'
require 'ad_manager_api/v202102/ad_exclusion_rule_service_registry'
module AdManagerApi; module V202102; module AdExclusionRuleService
class AdExclusionRuleService < AdsCommon::SavonService
def initialize(config, endpoint)
namespace = 'https://www.google.com/apis/ads/publisher/v202102'
super(config, endpoint, namespace, :v202102)
end
def create_ad_exclusion_rules(*args, &block)
return execute_action('create_ad_exclusion_rules', args, &block)
end
def create_ad_exclusion_rules_to_xml(*args)
return get_soap_xml('create_ad_exclusion_rules', args)
end
def get_ad_exclusion_rules_by_statement(*args, &block)
return execute_action('get_ad_exclusion_rules_by_statement', args, &block)
end
def get_ad_exclusion_rules_by_statement_to_xml(*args)
return get_soap_xml('get_ad_exclusion_rules_by_statement', args)
end
def perform_ad_exclusion_rule_action(*args, &block)
return execute_action('perform_ad_exclusion_rule_action', args, &block)
end
def perform_ad_exclusion_rule_action_to_xml(*args)
return get_soap_xml('perform_ad_exclusion_rule_action', args)
end
def update_ad_exclusion_rules(*args, &block)
return execute_action('update_ad_exclusion_rules', args, &block)
end
def update_ad_exclusion_rules_to_xml(*args)
return get_soap_xml('update_ad_exclusion_rules', args)
end
private
def get_service_registry()
return AdExclusionRuleServiceRegistry
end
def get_module()
return AdManagerApi::V202102::AdExclusionRuleService
end
end
end; end; end
| 30.666667 | 80 | 0.755176 |
3327bb3f24d96475e1774f3708eea45843d0d70f | 439 | require File.dirname(__FILE__) + '/../../spec_helper'
describe "Rubinius::LookupTable#entries" do
before :each do
@lt = Rubinius::LookupTable.new(:a => 1, :b => 2, :c => 3)
end
it "returns an Array of the entries in the LookupTable" do
entries = @lt.entries.sort { |a, b| a.key.to_s <=> b.key.to_s }
entries.collect { |e| e.key }.should == [:a, :b, :c]
entries.collect { |e| e.value }.should == [1, 2, 3]
end
end
| 31.357143 | 67 | 0.605923 |
abff1f2bc24d55c4757dcdd2632c9dc53a42954d | 4,618 | class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :omniauthable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
# Make sure we get the preference built after the user saves
after_create :build_preferences
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :about, :github, :facebook, :twitter, :linkedin, :skype, :screenhero, :google_plus, :legal_agreement, :provider, :uid
validates_uniqueness_of :username,:email
validates_presence_of :legal_agreement, :message => "Don't forget the legal stuff!", :on => :create
validates :username, :length => { :in => 4..20 }
# basic associations
has_many :cal_events, :foreign_key => :creator_id
has_one :user_pref
# associates the user to the content he'd like to pair on
has_many :content_activations, :dependent => :destroy
has_many :content_buckets, :through => :content_activations
# associates the user with the lessons he's completed so far
has_many :lesson_completions, :foreign_key => :student_id
has_many :completed_lessons, :through => :lesson_completions, :source => :lesson
# Return all users sorted by who has completed a lesson
# most recently
# NOTE: The order clause will break if not on Postgres because
# NULLS LAST is PG-specific apparently
def self.by_latest_completion
User.where.not(:last_sign_in_at => nil)
.joins("LEFT OUTER JOIN lesson_completions ON lesson_completions.student_id = users.id")
.select("max(lesson_completions.created_at) as latest_completion_date, users.*")
.group("users.id")
.order("latest_completion_date desc NULLS LAST")
end
def completed_lesson?(lesson)
self.completed_lessons.include?(lesson)
end
def latest_completed_lesson
lc = self.latest_lesson_completion
Lesson.find(lc.lesson_id) unless lc.nil?
end
def latest_lesson_completion
self.lesson_completions.order(:created_at => :desc).first
end
include Authentication::ActiveRecordHelpers #check in domain/authentication/active_record_helpers.rb
# Create a completely new user from our auth package
# Returns that user
def self.from_omniauth(auth)
#puts "\n\n\n\n\n\n\n #{auth} \n\n\n\n\n\n\n\n"
where(auth.slice(:provider, :uid)).first_or_create do |user|
user.provider = auth['provider']
user.uid = auth['uid']
user.username = auth['info']['nickname']
user.email = auth['info']['email']
end
end
# Assumes an existing user does not have omniauth
# Adds auth, saves, and returns the user
def add_omniauth(auth)
self.provider ||= auth['provider']
self.uid ||= auth['uid']
self.save
self
end
def self.new_with_session(params, session)
if session["devise.user_attributes"]
new(session["devise.user_attributes"], without_protection: true) do |user|
user.attributes = params
user.valid?
end
else
super
end
end
def password_required?
super && provider.blank?
end
def update_with_password(params, *options)
if encrypted_password.blank?
update_attributes(params, *options)
else
super
end
end
# Overwrite Devise method to allow users who registered before confirmation was required
# to continue using the site without being forced to confirm their email.
def active_for_authentication?
super && (!confirmation_required? || confirmed? || confirmation_period_valid?) || reg_before_conf?
end
# Overwrite Devise method to send welcome email to new users with confirmation token
# Users who registered before confirmation was required receive normal confirmation email
def send_confirmation_instructions
unless @raw_confirmation_token
generate_confirmation_token!
end
if self.reg_before_conf == true
opts = pending_reconfirmation? ? { to: unconfirmed_email } : { }
send_devise_notification(:confirmation_instructions, @raw_confirmation_token, opts)
else # new user
send_welcome_email(@raw_confirmation_token)
end
end
protected
def build_preferences
self.create_user_pref
end
def send_welcome_email(token)
begin
@token = token
UserMailer.send_welcome_email_to(self, token).deliver!
rescue Exception => e
puts "Error sending welcome email!"
puts e.message
end
end
end
| 33.955882 | 203 | 0.719359 |
393b16bdaa141c47e06b16465382f766443cb3fa | 2,454 | # frozen_string_literal: true
require 'rails_helper'
RSpec::Matchers.define_negated_matcher :not_change, :change
RSpec.describe PushNotificationsService do
before do
@user = FactoryBot.create :user
@subs_attributes = FactoryBot.attributes_for :subscription
@subs_attributes[:user_id] = @user.id
@subs_attributes[:message] = {
title: 'Testing',
body: 'Test'
}
end
describe 'when an exception occurs' do
it 'should not throw an error if the webpush subscription is invalid' do
# Webpush::InvalidSubscription requires an object, not a hash :(
error = OpenStruct.new(body: 404)
ex = Webpush::InvalidSubscription.new(error, 'body')
allow(Webpush).to receive(:payload_send).and_raise(ex)
expect do
response = PushNotificationsService.call(@user.id, @subs_attributes)
expect(response).to be(false)
end.to_not raise_error
end
it 'should delete the subscription if the subscription is invalid' do
error = OpenStruct.new(body: 404)
ex = Webpush::InvalidSubscription.new(error, 'body')
allow(Webpush).to receive(:payload_send).and_raise(ex)
expect do
response = PushNotificationsService.call(@user.id, @subs_attributes)
expect(response).to be(false)
end.to change(Subscription, :count)
end
it 'should not error with no vapid keys' do
ENV['VAPID_PUBLIC_KEY'] = nil
ENV['VAPID_PRIVATE_KEY'] = nil
expect do
response = PushNotificationsService.call(@user.id, @subs_attributes)
expect(response).to be(false)
end.to_not raise_error
end
end
describe 'when there are no exceptions' do
it 'should perform an analytics event successfully' do
ENV['VAPID_PUBLIC_KEY'] = 'ADn'
ENV['VAPID_PRIVATE_KEY'] = 'ADg'
allow(Webpush).to receive(:payload_send)
expect do
response = PushNotificationsService.call(@user.id, @subs_attributes)
expect(response).to be(true)
end.to_not raise_error
expect(Webpush).to have_received(:payload_send).with(
message: @message,
endpoint: @endpoint,
p256dh: @key,
auth: @auth,
vapid: {
subject: 'mailto:[email protected]',
public_key: ENV['VAPID_PUBLIC_KEY'],
private_key: ENV['VAPID_PRIVATE_KEY']
},
ssl_timeout: 5,
open_timeout: 5,
read_timeout: 5
)
end
end
end
| 30.675 | 76 | 0.661369 |
33849e6d1f30858e5698bb1598ec7024585d2313 | 3,400 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::ApiManagement::Mgmt::V2019_01_01
module Models
#
# Operation request details.
#
class RequestContract
include MsRestAzure
# @return [String] Operation request description.
attr_accessor :description
# @return [Array<ParameterContract>] Collection of operation request
# query parameters.
attr_accessor :query_parameters
# @return [Array<ParameterContract>] Collection of operation request
# headers.
attr_accessor :headers
# @return [Array<RepresentationContract>] Collection of operation request
# representations.
attr_accessor :representations
#
# Mapper for RequestContract class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'RequestContract',
type: {
name: 'Composite',
class_name: 'RequestContract',
model_properties: {
description: {
client_side_validation: true,
required: false,
serialized_name: 'description',
type: {
name: 'String'
}
},
query_parameters: {
client_side_validation: true,
required: false,
serialized_name: 'queryParameters',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ParameterContractElementType',
type: {
name: 'Composite',
class_name: 'ParameterContract'
}
}
}
},
headers: {
client_side_validation: true,
required: false,
serialized_name: 'headers',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ParameterContractElementType',
type: {
name: 'Composite',
class_name: 'ParameterContract'
}
}
}
},
representations: {
client_side_validation: true,
required: false,
serialized_name: 'representations',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'RepresentationContractElementType',
type: {
name: 'Composite',
class_name: 'RepresentationContract'
}
}
}
}
}
}
}
end
end
end
end
| 30.909091 | 79 | 0.472647 |
ac064ecea8dafa972eb8d62858dc8615a0e32003 | 608 | cask 'discord-ptb' do
version '0.0.17'
sha256 '5cb05ca8dc03cda80bef46d01e8b324faa2c1342bb12a3b25d0afe5e7d4553e1'
url "https://cdn-ptb.discordapp.com/apps/osx/#{version}/DiscordPTB.dmg"
name 'Discord PTB'
homepage 'https://discordapp.com'
license :gratis
app 'Discord PTB.app'
zap delete: [
'~/Library/Preferences/com.hnc.DiscordPTB.plist',
'~/Library/Saved Application State/com.hnc.DiscordPTB.savedState',
'~/Library/Caches/com.hnc.DiscordPTB',
'~/Library/Application Support/com.hnc.DiscordPTB.ShipIt',
]
end
| 32 | 82 | 0.659539 |
91b9f8ff7ce5f31bfd60ed526505cd000ee12740 | 3,656 | module ET1
module Test
module RefundSections
class FormSelect < SitePrism::Section
def set(value)
field.select(value)
end
def get
value = field.value
option = options.find { |v| v.value == value }
option ? option.text : ''
end
delegate disabled?: :field
element :field, 'select'
element :label, 'label'
element :error, '.error'
elements :options, 'option'
end
class FormInput < SitePrism::Section
delegate set: :field
element :field, 'input'
element :label, 'label'
element :error, '.error'
end
class FormTextArea < SitePrism::Section
delegate set: :field
def get
field.value
end
element :field, 'textarea'
element :label, 'label'
element :error, '.error'
end
class FormBoolean < SitePrism::Section
element :field, 'input'
element :label, 'label'
element :error, '.error'
def set(value)
choose(value)
end
end
class FormRadioButtons < SitePrism::Section
element :field, 'input'
element :label, 'label'
element :error, '.error'
def set(value)
choose(value)
end
end
class FormDate < SitePrism::Section
element :day, :field, 'Day'
element :month, :field, 'Month'
element :year, :field, 'Year'
element :label, 'label'
element :error, '.error'
def set(value)
(day_value, month_value, year_value) = value.split("/")
day.set(day_value)
month.set(month_value)
year.set(year_value)
end
end
class FormPaymentDate < SitePrism::Section
ALL_MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'].freeze
element :unknown, :field, 'Don\'t know'
element :month, :field, 'Month'
element :year, :field, 'Year'
element :disabled_unknown, :field, 'Don\'t know', disabled: true
element :disabled_month, :field, 'Month', disabled: true
element :disabled_year, :field, 'Year', disabled: true
element :label, 'label'
element :error, '.error'
def set(value)
check("Don't know") && return if [:dont_know, :unknown, 'Don\'t know'].include?(value)
uncheck("Don't know")
(month_value, year_value) = value.split(" ")
year.select(year_value)
month.select(month_value)
end
def disabled?
[disabled_month, disabled_year, disabled_unknown].all?(&:present?)
end
def assert_months_dropdown_contains_exactly(months)
ALL_MONTHS.each do |month_text|
should_be_disabled = !months.include?(month_text)
month.find(:xpath, xpath_for_option(text: month_text, disabled: should_be_disabled))
end
end
def years_dropdown_containing_exactly(years)
xpath = XPath.generate do |x|
x.descendant(:select)[x.string.n.is(years.join(' '))]
end
find(:xpath, xpath, exact: true, visible: true)
end
private
def xpath_for_option(text:, disabled:)
XPath.generate do |x|
if disabled
x.descendant(:option)[x.string.n.is(text).and(x.attr(:disabled))]
else
x.descendant(:option)[x.string.n.is(text).and(:'not(@disabled)')]
end
end
end
end
end
end
end
| 30.214876 | 150 | 0.559628 |
4adeac676a82e2cb41d28e1c2ee9ac6a8edfc156 | 2,477 | require 'spec_helper'
describe HeatReviewController do
before do
@competition = FactoryBot.create(:timed_competition, uses_lane_assignments: true)
director = FactoryBot.create(:user)
director.add_role(:director, @competition.event)
sign_in director
@reg = FactoryBot.create(:registrant)
@competitor = FactoryBot.create(:event_competitor, competition: @competition)
@competitor.members.first.update_attribute(:registrant_id, @reg.id)
@lane_assignment = FactoryBot.create(:lane_assignment, competition: @competition, competitor: @competitor)
end
describe "GET index" do
before { get :index, params: { competition_id: @competition.id } }
it "assigns @max_heat" do
assert_select "a", text: "Heat 1"
end
end
describe "GET show" do
before { get :show, params: { competition_id: @competition.id, heat: @lane_assignment.heat } }
it do
expect(response).to be_successful
end
end
describe "POST import_lif" do
describe "with valid params" do
let(:test_file_name) { fixture_path + "/test2.lif" }
let(:test_file) { Rack::Test::UploadedFile.new(test_file_name, "text/plain") }
it "calls the creator" do
allow_any_instance_of(Importers::HeatLaneLifImporter).to receive(:process).and_return(true)
post :import_lif, params: { heat: 1, competition_id: @competition.id, file: test_file }
expect(flash[:notice]).to match(/Successfully imported/)
end
end
describe "with invalid params" do
describe "when the file is missing" do
def do_action
post :import_lif, params: { heat: 1, competition_id: @competition.id, file: nil }
end
it "returns an error" do
do_action
assert_match(/Please specify a file/, flash[:alert])
end
end
end
end
describe "POST approve_heat" do
describe "with valid params" do
let(:test_file) { "stubbed" }
it "calls the creator" do
post :approve_heat, params: { heat: 1, competition_id: @competition.id }
expect(flash[:notice]).to match(/Added Heat/)
end
end
end
describe "DELETE #destroy" do
let!(:result) { FactoryBot.create(:heat_lane_result, competition: @competition) }
it "removes all heat lane rsults" do
expect do
delete :destroy, params: { competition_id: @competition.id, heat: result.heat }
end.to change(HeatLaneResult, :count).by(-1)
end
end
end
| 30.9625 | 110 | 0.670973 |
bbe85279152458a8536b756f325f66965fdb6e5e | 551 | module Copperegg
module Apm
module Generators
class InitGenerator < Rails::Generators::Base
source_root File.expand_path("../templates", __FILE__)
desc "Creates an initializer file at config/initializers/copperegg_apm_config.rb"
def create_initializer
template "config.rb", "#{Rails.root}/config/initializers/copperegg_apm_config.rb", :verbose => true
end
private
def instrument_key
@instrument_key = ask("Enter your app key:")
end
end
end
end
end
| 26.238095 | 109 | 0.655172 |
1ca1f356b7a745f43fcde10c22e2c85d77f2e97a | 2,016 | #
# Copyright 2006-2008 Appcelerator, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require File.dirname(__FILE__) + '/python_config.rb'
include Appcelerator
class DeployAppEnginePythonPlugin < Appcelerator::Plugin
def plugin_registered
CommandRegistry.registerCommand('deploy:project',
'deploy this project to the Google App Engine', [
],[
{
:name=>:args,
:display=>'--args=...',
:help=>'additional arguments to pass to the App Engine deploy command',
:default=>nil,
:value=>true
}
],
nil,
:project) do |args,options|
port = options[:port]
args = options[:args]
project_dir = Dir.pwd
cmd_name = 'appcfg.py'
config = PythonConfig.new
if config.on_windows
path = ENV['PATH']
path.match(/;([^;]*google_appengine[^;]*)/)
cmd_path = File.join($1,cmd_name)
run_cmd = "#{config.python} \"#{cmd_path}\""
else
run_cmd = cmd_name
end
cmd = "#{run_cmd} update \"#{project_dir}\" #{args}"
puts cmd if OPTIONS[:verbose]
event = {:project_dir=>project_dir ,:service=>'appengine'}
PluginManager.dispatchEvents('deploy_project',event) do
system(cmd)
if $?.exitstatus == 127
puts 'The "appcfg.py" command was not found. Please check that the Google App Engine is installed and that the "appcfg.py" command is on your PATH.'
end
end
end
end
end
| 30.545455 | 158 | 0.637401 |
ff41cd9ae432492f11e253bdc8121d8875ee1fd4 | 194 | #!/usr/bin/env ruby
$:.push File.expand_path("../lib", __FILE__)
require 'readline-ng'
reader = ReadlineNG::Reader.new
loop do
line = reader.get_line
reader.puts_above("Got #{line}")
end
| 16.166667 | 44 | 0.695876 |
1da499143877af9664b959d4318c93fbf77682f4 | 150 | module Steps
module Conviction
class CompensationUnableToTellController < Steps::ConvictionStepController
def show; end
end
end
end
| 18.75 | 78 | 0.76 |
1d7b9ecbcd4177fc336775a503e6fb84ca4934a4 | 2,116 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_deliveries = false
config.action_mailer.delivery_method = :smtp
config.action_mailer.default :charset => "utf-8"
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:authentication => "plain",
:enable_starttls_auto => true,
:user_name => ENV["GMAIL_USERNAME"],
:password => ENV["GMAIL_PASSWORD"]
}
config.action_mailer.default_url_options = { :host => 'localhost' }
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
config.active_storage.service = :local
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
| 37.785714 | 85 | 0.75189 |
282b4ff43c04408e4771775869ff8d82206c18c0 | 355 | class AddCoordinatesToZone < ActiveRecord::Migration[5.1]
def change
add_column :zones, :north, :decimal, {:precision=>10, :scale=>6}
add_column :zones, :south, :decimal, {:precision=>10, :scale=>6}
add_column :zones, :east, :decimal, {:precision=>10, :scale=>6}
add_column :zones, :west, :decimal, {:precision=>10, :scale=>6}
end
end
| 39.444444 | 68 | 0.667606 |
3383e030974561bd80218e893bd9d624c3371605 | 1,876 | #encoding:UTF-8
# Window_EquipItem
#==============================================================================
# ** Window_EquipItem
#------------------------------------------------------------------------------
# This window displays choices when opting to change equipment on the
# equipment screen.
#==============================================================================
class Window_EquipItem < Window_Item
#--------------------------------------------------------------------------
# * Object Initialization
# x : sindow X coordinate
# y : sindow Y corrdinate
# width : sindow width
# height : sindow height
# actor : actor
# equip_type : equip region (0-4)
#--------------------------------------------------------------------------
def initialize(x, y, width, height, actor, equip_type)
@actor = actor
if equip_type == 1 and actor.two_swords_style
equip_type = 0 # Change shield to weapon
end
@equip_type = equip_type
super(x, y, width, height)
end
#--------------------------------------------------------------------------
# * Whether to include item in list
# item : item
#--------------------------------------------------------------------------
def include?(item)
return true if item == nil
if @equip_type == 0
return false unless item.is_a?(RPG::Weapon)
else
return false unless item.is_a?(RPG::Armor)
return false unless item.kind == @equip_type - 1
end
return @actor.equippable?(item)
end
#--------------------------------------------------------------------------
# * Whether to display item in enabled state
# item : item
#--------------------------------------------------------------------------
def enable?(item)
return true
end
end
| 37.52 | 79 | 0.385394 |
7a185e124c875a5ccf4b054a5cfb827cedb39312 | 141 | require "json"
require "money"
require "coinbase/version"
require "coinbase/client"
require "coinbase/oauth_client"
require "coinbase/rates"
| 20.142857 | 31 | 0.801418 |
032067880950812431523458c8f04bab1e3b78ed | 1,644 | module ActionView
module Helpers
module FormTagHelper
# Add option to label_tag to suffix/prefix a string to the content
def label_tag_with_modifiers(name = nil, content_or_options = nil, options = nil, &block)
# text to suffix
if content_or_options && content_or_options.is_a?(Hash)
suffix = content_or_options.delete("suffix") if content_or_options.keys.include?("suffix")
suffix = content_or_options.delete(:suffix) if content_or_options.keys.include?(:suffix)
elsif options && options.is_a?(Hash)
suffix = options.delete("suffix") if options.keys.include?("suffix")
suffix = options.delete(:suffix) if options.keys.include?(:suffix)
end
suffix ||= LabelBuilder.suffix
# text to prefix
if content_or_options && content_or_options.is_a?(Hash)
prefix = content_or_options.delete("prefix") if content_or_options.keys.include?("prefix")
prefix = content_or_options.delete(:prefix) if content_or_options.keys.include?(:prefix)
elsif options && options.is_a?(Hash)
prefix = options.delete("prefix") if options.keys.include?("prefix")
prefix = options.delete(:prefix) if options.keys.include?(:prefix)
end
prefix ||= LabelBuilder.prefix
html = label_tag_without_modifiers(
name,
content_or_options,
options,
&block
)
html.gsub(
/(<label for=".*">)(.*)(<\/label>)/,
'\1'+prefix+'\2'+suffix+'\3'
)
end
alias_method_chain :label_tag, :modifiers
end
end
end
| 40.097561 | 100 | 0.632603 |
213958ce75d6d1bec0a5324873b9812d2930dbd5 | 22,526 | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Layout::FirstArgumentIndentation, :config do
let(:cop_config) do
{ 'EnforcedStyle' => style }
end
let(:other_cops) do
{
'Layout/IndentationWidth' => {
'Width' => indentation_width
}
}
end
shared_examples 'common behavior' do
context 'when IndentationWidth:Width is 2' do
let(:indentation_width) { 2 }
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects an over-indented first argument on an alphanumeric method name' do
expect_offense(<<~RUBY)
self.run(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
self.run(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects an over-indented first argument on a pipe method name' do
expect_offense(<<~RUBY)
self.|(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
self.|(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects an over-indented first argument on a plus sign method name' do
expect_offense(<<~RUBY)
self.+(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
self.+(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects an under-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects lines ' \
'affected by another offense' do
expect_offense(<<~RUBY)
foo(
bar(
^^^^ Indent the first argument one step more than the start of the previous line.
7
^ Bad indentation of the first argument.
)
)
RUBY
# The first `)` Will be corrected by IndentationConsistency.
expect_correction(<<~RUBY, loop: false)
foo(
bar(
7
)
)
RUBY
end
context 'when using safe navigation operator' do
it 'registers an offense and corrects an under-indented 1st argument' do
expect_offense(<<~RUBY)
receiver&.run(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
receiver&.run(
:foo,
bar: 3
)
RUBY
end
end
context 'for assignment' do
it 'accepts a correctly indented first argument and does not care ' \
'about the second argument' do
expect_no_offenses(<<~RUBY)
x = run(
:foo,
bar: 3
)
RUBY
end
context 'with line break' do
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
x =
run(
:foo)
RUBY
end
it 'registers an offense and corrects ' \
'an under-indented first argument' do
expect_offense(<<~RUBY)
@x =
run(
:foo)
^^^^ Indent the first argument one step more than the start of the previous line.
RUBY
expect_correction(<<~RUBY)
@x =
run(
:foo)
RUBY
end
end
end
it 'accepts a first argument that is not preceded by a line break' do
expect_no_offenses(<<~RUBY)
run :foo,
bar: 3
RUBY
end
context 'when the receiver contains a line break' do
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
puts x.
merge(
b: 2
)
RUBY
end
it 'registers an offense and corrects ' \
'an over-indented first argument' do
expect_offense(<<~RUBY)
puts x.
merge(
b: 2
^^^^ Indent the first argument one step more than the start of the previous line.
)
RUBY
expect_correction(<<~RUBY)
puts x.
merge(
b: 2
)
RUBY
end
it 'accepts a correctly indented first argument preceded by an ' \
'empty line' do
expect_no_offenses(<<~RUBY)
puts x.
merge(
b: 2
)
RUBY
end
context 'when preceded by a comment line' do
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
puts x.
merge( # EOL comment
# comment
b: 2
)
RUBY
end
it 'registers an offense and corrects ' \
'an under-indented first argument' do
expect_offense(<<~RUBY)
puts x.
merge(
# comment
b: 2
^^^^ Indent the first argument one step more than the start of the previous line (not counting the comment).
)
RUBY
expect_correction(<<~RUBY)
puts x.
merge(
# comment
b: 2
)
RUBY
end
end
end
it 'accepts method calls with no arguments' do
expect_no_offenses(<<~RUBY)
run()
run_again
RUBY
end
it 'accepts operator calls' do
expect_no_offenses(<<~RUBY)
params = default_cfg.keys - %w(Description) -
cfg.keys
RUBY
end
it 'does not view []= as an outer method call' do
expect_no_offenses(<<~RUBY)
@subject_results[subject] = original.update(
mutation_results: (dup << mutation_result),
tests: test_result.tests
)
RUBY
end
it 'does not view chained call as an outer method call' do
expect_no_offenses(<<~'RUBY')
A = Regexp.union(
/[A-Za-z_][A-Za-z\d_]*[!?=]?/,
*AST::Types::OPERATOR_METHODS.map(&:to_s)
).freeze
RUBY
end
end
context 'when IndentationWidth:Width is 4' do
let(:indentation_width) { 4 }
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3)
RUBY
end
end
context 'when indentation width is overridden for this cop only' do
let(:cop_config) do
{
'EnforcedStyle' => style,
'IndentationWidth' => 4
}
end
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
run(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3)
RUBY
end
end
end
context 'when EnforcedStyle is special_for_inner_method_call' do
let(:style) { 'special_for_inner_method_call' }
let(:indentation_width) { 2 }
include_examples 'common behavior'
context 'for method calls within method calls' do
context 'with outer parentheses' do
it 'registers an offense and corrects ' \
'an over-indented first argument' do
expect_offense(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
^^^^^^ Indent the first argument one step more than `defaults.merge(`.
RUBY
expect_correction(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
RUBY
end
end
context 'without outer parentheses' do
it 'accepts a first argument with special indentation' do
expect_no_offenses(<<~RUBY)
run :foo, defaults.merge(
bar: 3)
RUBY
end
end
end
end
context 'when EnforcedStyle is ' \
'special_for_inner_method_call_in_parentheses' do
let(:style) { 'special_for_inner_method_call_in_parentheses' }
let(:indentation_width) { 2 }
include_examples 'common behavior'
context 'for method calls within method calls' do
context 'with outer parentheses' do
it 'registers an offense and corrects ' \
'an over-indented first argument' do
expect_offense(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
^^^^^^ Indent the first argument one step more than `defaults.merge(`.
RUBY
expect_correction(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
RUBY
end
it 'registers an offense and corrects ' \
'an under-indented first argument' do
expect_offense(<<~RUBY)
run(:foo, defaults.
merge(
bar: 3))
^^^^^^ Indent the first argument one step more than the start of the previous line.
RUBY
expect_correction(<<~RUBY)
run(:foo, defaults.
merge(
bar: 3))
RUBY
end
it 'accepts a correctly indented first argument in interpolation' do
expect_no_offenses(<<~'RUBY')
puts %(
<p>
#{Array(
42
)}
</p>
)
RUBY
end
it 'accepts a correctly indented first argument with fullwidth ' \
'characters' do
expect_no_offenses(<<~RUBY)
puts('Ruby', f(
a))
RUBY
end
end
context 'without outer parentheses' do
it 'accepts a first argument with consistent style indentation' do
expect_no_offenses(<<~RUBY)
run :foo, defaults.merge(
bar: 3)
RUBY
end
end
end
end
context 'when EnforcedStyle is consistent' do
let(:style) { 'consistent' }
let(:indentation_width) { 2 }
include_examples 'common behavior'
context 'for method calls within method calls' do
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
^^^^^^ Indent the first argument one step more than the start of the previous line.
RUBY
expect_correction(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
RUBY
end
it 'accepts first argument indented relative to previous line' do
expect_no_offenses(<<~RUBY)
@diagnostics.process(Diagnostic.new(
:error, :token, { :token => name }, location))
RUBY
end
end
end
context 'when EnforcedStyle is consistent_relative_to_receiver' do
let(:style) { 'consistent_relative_to_receiver' }
context 'when IndentationWidth:Width is 2' do
let(:indentation_width) { 2 }
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than `run(`.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects an under-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than `run(`.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects lines affected by other offenses' do
expect_offense(<<~RUBY)
foo(
bar(
^^^^ Indent the first argument one step more than `foo(`.
7
^ Bad indentation of the first argument.
)
)
RUBY
# The first `)` Will be corrected by IndentationConsistency.
expect_correction(<<~RUBY, loop: false)
foo(
bar(
7
)
)
RUBY
end
context 'for assignment' do
it 'register an offense and corrects a correctly indented first ' \
'argument and does not care about the second argument' do
expect_offense(<<~RUBY)
x = run(
:foo,
^^^^ Indent the first argument one step more than `run(`.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
x = run(
:foo,
bar: 3
)
RUBY
end
context 'with line break' do
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
x =
run(
:foo)
RUBY
end
it 'registers an offense and corrects ' \
'an under-indented first argument' do
expect_offense(<<~RUBY)
@x =
run(
:foo)
^^^^ Indent the first argument one step more than `run(`.
RUBY
expect_correction(<<~RUBY)
@x =
run(
:foo)
RUBY
end
end
end
it 'accepts a first argument that is not preceded by a line break' do
expect_no_offenses(<<~RUBY)
run :foo,
bar: 3
RUBY
end
it 'does not register an offense when argument has expected indent width and ' \
'the method is preceded by splat' do
expect_no_offenses(<<~RUBY)
[
item,
*do_something(
arg)
]
RUBY
end
it 'does not register an offense when argument has expected indent width and ' \
'the method is preceded by double splat' do
expect_no_offenses(<<~RUBY)
[
item,
**do_something(
arg)
]
RUBY
end
context 'when the receiver contains a line break' do
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
puts x.
merge(
b: 2
)
RUBY
end
it 'registers an offense and corrects an over-indented 1st argument' do
expect_offense(<<~RUBY)
puts x.
merge(
b: 2
^^^^ Indent the first argument one step more than the start of the previous line.
)
RUBY
expect_correction(<<~RUBY)
puts x.
merge(
b: 2
)
RUBY
end
it 'accepts a correctly indented first argument preceded by an ' \
'empty line' do
expect_no_offenses(<<~RUBY)
puts x.
merge(
b: 2
)
RUBY
end
context 'when preceded by a comment line' do
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
puts x.
merge( # EOL comment
# comment
b: 2
)
RUBY
end
it 'registers an offense and corrects ' \
'an under-indented first argument' do
expect_offense(<<~RUBY)
puts x.
merge(
# comment
b: 2
^^^^ Indent the first argument one step more than the start of the previous line (not counting the comment).
)
RUBY
expect_correction(<<~RUBY)
puts x.
merge(
# comment
b: 2
)
RUBY
end
end
end
it 'accepts method calls with no arguments' do
expect_no_offenses(<<~RUBY)
run()
run_again
RUBY
end
it 'accepts operator calls' do
expect_no_offenses(<<~RUBY)
params = default_cfg.keys - %w(Description) -
cfg.keys
RUBY
end
it 'does not view []= as an outer method call' do
expect_no_offenses(<<~RUBY)
@subject_results[subject] = original.update(
mutation_results: (dup << mutation_result),
tests: test_result.tests
)
RUBY
end
it 'does not view chained call as an outer method call' do
expect_no_offenses(<<~'RUBY')
A = Regexp.union(
/[A-Za-z_][A-Za-z\d_]*[!?=]?/,
*AST::Types::OPERATOR_METHODS.map(&:to_s)
).freeze
RUBY
end
end
context 'when IndentationWidth:Width is 4' do
let(:indentation_width) { 4 }
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than `run(`.
bar: 3)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3)
RUBY
end
end
context 'when indentation width is overridden for this cop only' do
let(:indentation_width) { nil }
let(:cop_config) do
{
'EnforcedStyle' => style,
'IndentationWidth' => 4
}
end
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
run(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than `run(`.
bar: 3)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3)
RUBY
end
end
context 'for method calls within method calls' do
let(:indentation_width) { 2 }
context 'with outer parentheses' do
it 'registers an offense and corrects an over-indented 1st argument' do
expect_offense(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
^^^^^^ Indent the first argument one step more than `defaults.merge(`.
RUBY
expect_correction(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
RUBY
end
it 'indents all relative to the receiver' do
expect_no_offenses(<<~RUBY)
foo = run(
:foo, defaults.merge(
bar: 3)
)
RUBY
expect_no_offenses(<<~RUBY)
MyClass.my_method(a_hash.merge(
hello: :world,
some: :hash,
goes: :here
), other_arg)
RUBY
expect_no_offenses(<<~RUBY)
foo = bar * run(
:foo, defaults.merge(
bar: 3)
)
RUBY
end
end
context 'without outer parentheses' do
it 'accepts a first argument with special indentation' do
expect_no_offenses(<<~RUBY)
run :foo, defaults.merge(
bar: 3)
RUBY
end
it 'indents all relative to the receiver' do
expect_no_offenses(<<~RUBY)
foo = run :foo, defaults.merge(
bar: 3)
RUBY
expect_no_offenses(<<~RUBY)
foo = bar * run(
:foo, defaults.merge(
bar: 3))
RUBY
end
end
end
end
end
| 26.752969 | 124 | 0.474252 |
87b0f7f6d8fffc2ccd590da50f0f3fda563aeb7e | 429 | require 'spec_helper'
require 'rspec/sidekiq_examples'
describe AlleApi::Job::UpdateVersionKey do
it { should be_a AlleApi::Job::Base }
it_is_an 'unique job', 15.seconds
it '#perform triggers version update via Versions helper' do
versions = stub
AlleApi::Helper::Versions.expects(:new).returns(versions)
versions.expects(:update).with(:version_key)
AlleApi::Job::UpdateVersionKey.new.perform
end
end
| 25.235294 | 62 | 0.74359 |
5d04c0c257c2fc9c8af937a38359d11d188e31f1 | 9,514 | # frozen_string_literal: true
require 'uri'
require 'testing_helper'
require 'redis_client/cluster/node'
class RedisClient
class Cluster
class Node
class TestConfig < Minitest::Test
def test_connection_prelude
[
{ params: { scale_read: true }, want: [%w[HELLO 3], %w[READONLY]] },
{ params: { scale_read: false }, want: [%w[HELLO 3]] },
{ params: {}, want: [%w[HELLO 3]] }
].each_with_index do |c, idx|
got = ::RedisClient::Cluster::Node::Config.new(**c[:params]).connection_prelude
assert_equal(c[:want], got, "Case: #{idx}")
end
end
end
end
class TestNode < Minitest::Test
def test_load_info
[
{ params: { options: TEST_NODE_OPTIONS, kwargs: {} }, want: { size: TEST_NODE_OPTIONS.size } },
{ params: { options: { '127.0.0.1:11211' => { host: '127.0.0.1', port: 11_211 } }, kwargs: {} }, want: { error: ::RedisClient::Cluster::InitialSetupError } },
{ params: { options: {}, kwargs: {} }, want: { error: ::RedisClient::Cluster::InitialSetupError } }
].each_with_index do |c, idx|
msg = "Case: #{idx}"
got = -> { ::RedisClient::Cluster::Node.load_info(c[:params][:options], **c[:params][:kwargs]) }
if c[:want].key?(:error)
assert_raises(c[:want][:error], msg, &got)
else
assert_equal(c[:want][:size], got.call.size, msg)
end
end
end
def test_parse_node_info
info = <<~INFO
07c37dfeb235213a872192d90877d0cd55635b91 127.0.0.1:30004@31004 slave e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca 0 1426238317239 4 connected
67ed2db8d677e59ec4a4cefb06858cf2a1a89fa1 127.0.0.1:30002@31002 master - 0 1426238316232 2 connected 5461-10922
292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f 127.0.0.1:30003@31003 master - 0 1426238318243 3 connected 10923-16383
6ec23923021cf3ffec47632106199cb7f496ce01 127.0.0.1:30005@31005 slave 67ed2db8d677e59ec4a4cefb06858cf2a1a89fa1 0 1426238316232 5 connected
824fe116063bc5fcf9f4ffd895bc17aee7731ac3 127.0.0.1:30006@31006 slave 292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f 0 1426238317741 6 connected
e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca 127.0.0.1:30001@31001 myself,master - 0 0 1 connected 0-5460
INFO
want = [
{ id: '07c37dfeb235213a872192d90877d0cd55635b91', node_key: '127.0.0.1:30004', role: 'slave',
primary_id: 'e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca', ping_sent: '0', pong_recv: '1426238317239',
config_epoch: '4', link_state: 'connected', slots: [] },
{ id: '67ed2db8d677e59ec4a4cefb06858cf2a1a89fa1', node_key: '127.0.0.1:30002', role: 'master',
primary_id: '-', ping_sent: '0', pong_recv: '1426238316232',
config_epoch: '2', link_state: 'connected', slots: [[5461, 10_922]] },
{ id: '292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f', node_key: '127.0.0.1:30003', role: 'master',
primary_id: '-', ping_sent: '0', pong_recv: '1426238318243',
config_epoch: '3', link_state: 'connected', slots: [[10_923, 16_383]] },
{ id: '6ec23923021cf3ffec47632106199cb7f496ce01', node_key: '127.0.0.1:30005', role: 'slave',
primary_id: '67ed2db8d677e59ec4a4cefb06858cf2a1a89fa1', ping_sent: '0', pong_recv: '1426238316232',
config_epoch: '5', link_state: 'connected', slots: [] },
{ id: '824fe116063bc5fcf9f4ffd895bc17aee7731ac3', node_key: '127.0.0.1:30006', role: 'slave',
primary_id: '292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f', ping_sent: '0', pong_recv: '1426238317741',
config_epoch: '6', link_state: 'connected', slots: [] },
{ id: 'e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca', node_key: '127.0.0.1:30001', role: 'master',
primary_id: '-', ping_sent: '0', pong_recv: '0', config_epoch: '1', link_state: 'connected', slots: [[0, 5460]] }
]
assert_equal(want, ::RedisClient::Cluster::Node.send(:parse_node_info, info), 'Case: success: continuous slots')
info = <<~INFO
07c37dfeb235213a872192d90877d0cd55635b91 127.0.0.1:30004@31004 slave e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca 0 1426238317239 4 connected
67ed2db8d677e59ec4a4cefb06858cf2a1a89fa1 127.0.0.1:30002@31002 master - 0 1426238316232 2 connected 3001,5461-7000,7002-10922
292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f 127.0.0.1:30003@31003 master - 0 1426238318243 3 connected 7001,10923-15000,15002-16383
6ec23923021cf3ffec47632106199cb7f496ce01 127.0.0.1:30005@31005 slave 67ed2db8d677e59ec4a4cefb06858cf2a1a89fa1 0 1426238316232 5 connected
824fe116063bc5fcf9f4ffd895bc17aee7731ac3 127.0.0.1:30006@31006 slave 292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f 0 1426238317741 6 connected
e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca 127.0.0.1:30001@31001 myself,master - 0 0 1 connected 0-3000,3002-5460,15001
INFO
want = [
{ id: '07c37dfeb235213a872192d90877d0cd55635b91', node_key: '127.0.0.1:30004', role: 'slave',
primary_id: 'e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca', ping_sent: '0', pong_recv: '1426238317239',
config_epoch: '4', link_state: 'connected', slots: [] },
{ id: '67ed2db8d677e59ec4a4cefb06858cf2a1a89fa1', node_key: '127.0.0.1:30002', role: 'master',
primary_id: '-', ping_sent: '0', pong_recv: '1426238316232',
config_epoch: '2', link_state: 'connected', slots: [[3001, 3001], [5461, 7000], [7002, 10_922]] },
{ id: '292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f', node_key: '127.0.0.1:30003', role: 'master',
primary_id: '-', ping_sent: '0', pong_recv: '1426238318243',
config_epoch: '3', link_state: 'connected', slots: [[7001, 7001], [10_923, 15_000], [15_002, 16_383]] },
{ id: '6ec23923021cf3ffec47632106199cb7f496ce01', node_key: '127.0.0.1:30005', role: 'slave',
primary_id: '67ed2db8d677e59ec4a4cefb06858cf2a1a89fa1', ping_sent: '0', pong_recv: '1426238316232',
config_epoch: '5', link_state: 'connected', slots: [] },
{ id: '824fe116063bc5fcf9f4ffd895bc17aee7731ac3', node_key: '127.0.0.1:30006', role: 'slave',
primary_id: '292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f', ping_sent: '0', pong_recv: '1426238317741',
config_epoch: '6', link_state: 'connected', slots: [] },
{ id: 'e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca', node_key: '127.0.0.1:30001', role: 'master',
primary_id: '-', ping_sent: '0', pong_recv: '0', config_epoch: '1', link_state: 'connected', slots: [[0, 3000], [3002, 5460], [15_001, 15_001]] }
]
assert_equal(want, ::RedisClient::Cluster::Node.send(:parse_node_info, info), 'Case: success: discrete slots')
info = <<~INFO
07c37dfeb235213a872192d90877d0cd55635b91 127.0.0.1:30004@31004 slave e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca 0 1426238317239 4 disconnected
67ed2db8d677e59ec4a4cefb06858cf2a1a89fa1 127.0.0.1:30002@31002 master - 0 1426238316232 2 disconnected 5461-10922
292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f 127.0.0.1:30003@31003 master - 0 1426238318243 3 disconnected 10923-16383
6ec23923021cf3ffec47632106199cb7f496ce01 127.0.0.1:30005@31005 slave 67ed2db8d677e59ec4a4cefb06858cf2a1a89fa1 0 1426238316232 5 disconnected
824fe116063bc5fcf9f4ffd895bc17aee7731ac3 127.0.0.1:30006@31006 slave 292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f 0 1426238317741 6 disconnected
e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca 127.0.0.1:30001@31001 myself,master - 0 0 1 disconnected 0-5460
INFO
assert_empty(::RedisClient::Cluster::Node.send(:parse_node_info, info), 'Case: failure: link state')
info = <<~INFO
07c37dfeb235213a872192d90877d0cd55635b91 127.0.0.1:30004@31004 fail?,slave e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca 0 1426238317239 4 connected
67ed2db8d677e59ec4a4cefb06858cf2a1a89fa1 127.0.0.1:30002@31002 fail,master - 0 1426238316232 2 connected 5461-10922
292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f 127.0.0.1:30003@31003 master,handshake - 0 1426238318243 3 connected 10923-16383
6ec23923021cf3ffec47632106199cb7f496ce01 127.0.0.1:30005@31005 noaddr,slave 67ed2db8d677e59ec4a4cefb06858cf2a1a89fa1 0 1426238316232 5 connected
824fe116063bc5fcf9f4ffd895bc17aee7731ac3 127.0.0.1:30006@31006 noflags 292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f 0 1426238317741 6 connected
e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca 127.0.0.1:30001@31001 myself,fail,master - 0 0 1 connected 0-5460
INFO
assert_empty(::RedisClient::Cluster::Node.send(:parse_node_info, info), 'Case: failure: flags')
end
def test_inspect
skip('TODO')
end
def test_enumerable
skip('TODO')
end
def test_find_by
skip('TODO')
end
def test_call_all
skip('TODO')
end
def test_call_primary
skip('TODO')
end
def test_call_replica
skip('TODO')
end
def test_scale_reading_clients
skip('TODO')
end
def test_slot_exists?
skip('TODO')
end
def test_find_node_key_of_primary
skip('TODO')
end
def test_find_node_key_of_replica
skip('TODO')
end
def test_update_slot
skip('TODO')
end
end
end
end
| 54.99422 | 168 | 0.673849 |
61446cde36fd95633d0cceec5d9ada8aa6d4479b | 9,559 | module ActiveRecord
module Aggregations # :nodoc:
def self.included(base)
base.extend(ClassMethods)
end
def clear_aggregation_cache #:nodoc:
self.class.reflect_on_all_aggregations.to_a.each do |assoc|
instance_variable_set "@#{assoc.name}", nil
end unless self.new_record?
end
# Active Record implements aggregation through a macro-like class method called +composed_of+ for representing attributes
# as value objects. It expresses relationships like "Account [is] composed of Money [among other things]" or "Person [is]
# composed of [an] address". Each call to the macro adds a description of how the value objects are created from the
# attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object)
# and how it can be turned back into attributes (when the entity is saved to the database). Example:
#
# class Customer < ActiveRecord::Base
# composed_of :balance, :class_name => "Money", :mapping => %w(balance amount)
# composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
# end
#
# The customer class now has the following methods to manipulate the value objects:
# * <tt>Customer#balance, Customer#balance=(money)</tt>
# * <tt>Customer#address, Customer#address=(address)</tt>
#
# These methods will operate with value objects like the ones described below:
#
# class Money
# include Comparable
# attr_reader :amount, :currency
# EXCHANGE_RATES = { "USD_TO_DKK" => 6 }
#
# def initialize(amount, currency = "USD")
# @amount, @currency = amount, currency
# end
#
# def exchange_to(other_currency)
# exchanged_amount = (amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor
# Money.new(exchanged_amount, other_currency)
# end
#
# def ==(other_money)
# amount == other_money.amount && currency == other_money.currency
# end
#
# def <=>(other_money)
# if currency == other_money.currency
# amount <=> amount
# else
# amount <=> other_money.exchange_to(currency).amount
# end
# end
# end
#
# class Address
# attr_reader :street, :city
# def initialize(street, city)
# @street, @city = street, city
# end
#
# def close_to?(other_address)
# city == other_address.city
# end
#
# def ==(other_address)
# city == other_address.city && street == other_address.street
# end
# end
#
# Now it's possible to access attributes from the database through the value objects instead. If you choose to name the
# composition the same as the attribute's name, it will be the only way to access that attribute. That's the case with our
# +balance+ attribute. You interact with the value objects just like you would any other attribute, though:
#
# customer.balance = Money.new(20) # sets the Money value object and the attribute
# customer.balance # => Money value object
# customer.balance.exchanged_to("DKK") # => Money.new(120, "DKK")
# customer.balance > Money.new(10) # => true
# customer.balance == Money.new(20) # => true
# customer.balance < Money.new(5) # => false
#
# Value objects can also be composed of multiple attributes, such as the case of Address. The order of the mappings will
# determine the order of the parameters. Example:
#
# customer.address_street = "Hyancintvej"
# customer.address_city = "Copenhagen"
# customer.address # => Address.new("Hyancintvej", "Copenhagen")
# customer.address = Address.new("May Street", "Chicago")
# customer.address_street # => "May Street"
# customer.address_city # => "Chicago"
#
# == Writing value objects
#
# Value objects are immutable and interchangeable objects that represent a given value, such as a +Money+ object representing
# $5. Two +Money+ objects both representing $5 should be equal (through methods such as == and <=> from +Comparable+ if ranking
# makes sense). This is unlike entity objects where equality is determined by identity. An entity class such as +Customer+ can
# easily have two different objects that both have an address on Hyancintvej. Entity identity is determined by object or
# relational unique identifiers (such as primary keys). Normal <tt>ActiveRecord::Base</tt> classes are entity objects.
#
# It's also important to treat the value objects as immutable. Don't allow the +Money+ object to have its amount changed after
# creation. Create a new +Money+ object with the new value instead. This is exemplified by the <tt>Money#exchanged_to</tt> method that
# returns a new value object instead of changing its own values. Active Record won't persist value objects that have been
# changed through means other than the writer method.
#
# The immutable requirement is enforced by Active Record by freezing any object assigned as a value object. Attempting to
# change it afterwards will result in a <tt>ActiveSupport::FrozenObjectError</tt>.
#
# Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not keeping value objects
# immutable on http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable
#
# == Finding records by a value object
#
# Once a +composed_of+ relationship is specified for a model, records can be loaded from the database by specifying an instance
# of the value object in the conditions hash. The following example finds all customers with +balance_amount+ equal to 20 and
# +balance_currency+ equal to "USD":
#
# Customer.find(:all, :conditions => {:balance => Money.new(20, "USD")})
#
module ClassMethods
# Adds reader and writer methods for manipulating a value object:
# <tt>composed_of :address</tt> adds <tt>address</tt> and <tt>address=(new_address)</tt> methods.
#
# Options are:
# * <tt>:class_name</tt> - specify the class name of the association. Use it only if that name can't be inferred
# from the part id. So <tt>composed_of :address</tt> will by default be linked to the +Address+ class, but
# if the real class name is +CompanyAddress+, you'll have to specify it with this option.
# * <tt>:mapping</tt> - specifies a number of mapping arrays (attribute, parameter) that bind an attribute name
# to a constructor parameter on the value class.
# * <tt>:allow_nil</tt> - specifies that the aggregate object will not be instantiated when all mapped
# attributes are +nil+. Setting the aggregate class to +nil+ has the effect of writing +nil+ to all mapped attributes.
# This defaults to +false+.
#
# An optional block can be passed to convert the argument that is passed to the writer method into an instance of
# <tt>:class_name</tt>. The block will only be called if the argument is not already an instance of <tt>:class_name</tt>.
#
# Option examples:
# composed_of :temperature, :mapping => %w(reading celsius)
# composed_of(:balance, :class_name => "Money", :mapping => %w(balance amount)) {|balance| balance.to_money }
# composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
# composed_of :gps_location
# composed_of :gps_location, :allow_nil => true
#
def composed_of(part_id, options = {}, &block)
options.assert_valid_keys(:class_name, :mapping, :allow_nil)
name = part_id.id2name
class_name = options[:class_name] || name.camelize
mapping = options[:mapping] || [ name, name ]
mapping = [ mapping ] unless mapping.first.is_a?(Array)
allow_nil = options[:allow_nil] || false
reader_method(name, class_name, mapping, allow_nil)
writer_method(name, class_name, mapping, allow_nil, block)
create_reflection(:composed_of, part_id, options, self)
end
private
def reader_method(name, class_name, mapping, allow_nil)
module_eval do
define_method(name) do |*args|
force_reload = args.first || false
if (instance_variable_get("@#{name}").nil? || force_reload) && (!allow_nil || mapping.any? {|pair| !read_attribute(pair.first).nil? })
instance_variable_set("@#{name}", class_name.constantize.new(*mapping.collect {|pair| read_attribute(pair.first)}))
end
instance_variable_get("@#{name}")
end
end
end
def writer_method(name, class_name, mapping, allow_nil, conversion)
module_eval do
define_method("#{name}=") do |part|
if part.nil? && allow_nil
mapping.each { |pair| self[pair.first] = nil }
instance_variable_set("@#{name}", nil)
else
part = conversion.call(part) unless part.is_a?(class_name.constantize) || conversion.nil?
mapping.each { |pair| self[pair.first] = part.send(pair.last) }
instance_variable_set("@#{name}", part.freeze)
end
end
end
end
end
end
end
| 50.310526 | 148 | 0.64693 |
4ad588363034401e0333554f93cbc968a39b33d6 | 1,878 | Pod::Spec.new do |spec|
spec.name = 'URLImage'
spec.version = '2.1.11'
spec.summary = 'SwiftUI Image view that displays an image downloaded from URL.'
spec.description = <<-DESC
URLImage is a SwiftUI view that displays an image downloaded from provided URL. URLImage manages downloading remote image and caching it locally, both in memory and on disk, for you.
DESC
spec.homepage = 'https://github.com/dmytro-anokhin/url-image'
spec.license = 'MIT'
spec.author = { 'Dmytro Anokhin' => '[email protected]' }
spec.source = { :git => 'https://github.com/dmytro-anokhin/url-image.git', :tag => "#{spec.version}" }
spec.source_files = 'Sources', 'Sources/**/*.{swift}'
spec.exclude_files = 'Tests'
spec.swift_versions = '5.3'
spec.platforms = { :ios => '13.0', :tvos => '13.0', :osx => '10.15', :watchos => '6.0' }
spec.subspec 'RemoteContentView' do |ss|
ss.source_files = 'Dependencies/Sources/RemoteContentView/**/*.{swift}'
end
spec.subspec 'ImageDecoder' do |ss|
ss.source_files = 'Dependencies/Sources/ImageDecoder/**/*.{swift}'
end
spec.subspec 'FileIndex' do |ss|
ss.source_files = 'Dependencies/Sources/FileIndex/**/*.{swift}'
ss.dependency 'URLImage/Log'
ss.dependency 'URLImage/PlainDatabase'
ss.dependency 'URLImage/Common'
end
spec.subspec 'PlainDatabase' do |ss|
ss.source_files = 'Dependencies/Sources/PlainDatabase/**/*.{swift}'
end
spec.subspec 'DownloadManager' do |ss|
ss.source_files = 'Dependencies/Sources/DownloadManager/**/*.{swift}'
ss.dependency 'URLImage/Log'
end
spec.subspec 'Common' do |ss|
ss.source_files = 'Dependencies/Sources/Common/**/*.{swift}'
end
spec.subspec 'Log' do |ss|
ss.source_files = 'Dependencies/Sources/Log/**/*.{swift}'
end
end
| 32.37931 | 184 | 0.660809 |
91a675ea8fc1a0559758053db2cd0e28865bb1cc | 2,072 | require_relative 'test_helper'
class ActiveRecordTest < Minitest::Test
describe 'ActiveRecord' do
before do
# Use a mock logger that just keeps the last logged entry in an instance variable
SemanticLogger.default_level = :trace
SemanticLogger.backtrace_level = nil
@mock_logger = MockLogger.new
@appender = SemanticLogger.add_appender(logger: @mock_logger, formatter: :raw)
@logger = SemanticLogger['Test']
@hash = {session_id: 'HSSKLEU@JDK767', tracking_number: 12_345}
assert_equal [], SemanticLogger.tags
assert_equal 65_535, SemanticLogger.backtrace_level_index
end
after do
SemanticLogger.remove_appender(@appender)
end
describe 'logs' do
it 'sql' do
Sample.first
SemanticLogger.flush
actual = @mock_logger.message
assert actual[:message].include?('Sample'), actual[:message]
assert actual[:payload], actual
assert actual[:payload][:sql], actual[:payload]
end
it 'single bind value' do
Sample.where(name: 'Jack').first
SemanticLogger.flush
actual = @mock_logger.message
assert payload = actual[:payload], -> { actual.ai }
assert payload[:sql], -> { actual.ai }
assert binds = payload[:binds], -> { actual.ai }
assert_equal 'Jack', binds[:name], -> { actual.ai }
assert_equal 1, binds[:limit], -> { actual.ai } if Rails.version.to_f >= 5.0
end
it 'multiple bind values' do
Sample.where(age: 2..21).first
SemanticLogger.flush
actual = @mock_logger.message
assert payload = actual[:payload], -> { actual.ai }
assert payload[:sql], -> { actual.ai }
if Rails.version.to_f >= 5.0
assert binds = payload[:binds], -> { actual.ai }
assert_equal [2, 21], binds[:age], -> { actual.ai }
assert_equal 1, binds[:limit], -> { actual.ai }
end
end
end
end
end
| 31.876923 | 105 | 0.593147 |
1d0bce9af54e581cd58a5a90f582832f02b48f75 | 186 | require File.dirname(__FILE__) + '/../../spec_helper'
describe "Tuple#first" do
it "returns the first element" do
t = Tuple[:foo, :bar, :baz]
t.first.should == :foo
end
end
| 20.666667 | 53 | 0.639785 |
7914ae3504ed5eb8678103f930f972a80d6d0a15 | 1,362 | RSpec.describe PerseidsStatus::Emailer do
let(:json) { Factory.json }
let(:email) { '[email protected]' }
let(:server) { 'your.smtp.server' }
let(:port) { 25 }
let(:domain) { 'mail.from.domain' }
let(:mailer) { double }
let(:message) do
"From: Perseids Status <[email protected]>\n" \
"To: <[email protected]>\n" \
"Subject: Perseids Status\n\n" \
"fruit/pear doesn't match: ok -> diff\n" \
"vegetable/onion doesn't match: ok -> wc\n"
end
subject(:emailer) { PerseidsStatus::Emailer.new(json, email, server, port, domain) }
before do
allow(Net::SMTP).to receive(:start).with(
'your.smtp.server',
25,
'mail.from.domain',
).and_yield(mailer)
end
describe '#send!' do
it 'sends an email' do
expect(mailer).to receive(:send_message).with(message, '[email protected]', email)
emailer.send!
end
context 'there are no diffs from the previous' do
let(:json) { Factory.json_fixture_json }
it 'does not send email' do
expect(mailer).to_not receive(:send_message)
emailer.send!
end
end
context 'there are fewer than two elements in the json' do
let(:json) { Factory.json.first(1) }
it 'does not send email' do
expect(mailer).to_not receive(:send_message)
emailer.send!
end
end
end
end
| 25.222222 | 90 | 0.62188 |
91df1b0d98f8e58c0f58412f8cecb332a0a467bd | 1,853 | # frozen_string_literal: true
# See https://docs.gitlab.com/ee/development/migration_style_guide.html
# for more information on how to write migrations for GitLab.
class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
include Gitlab::Database::MigrationHelpers
# Set this constant to true if this migration requires downtime.
DOWNTIME = false
# When a migration requires downtime you **must** uncomment the following
# constant and define a short and easy to understand explanation as to why the
# migration requires downtime.
# DOWNTIME_REASON = ''
# When using the methods "add_concurrent_index", "remove_concurrent_index" or
# "add_column_with_default" you must disable the use of transactions
# as these methods can not run in an existing transaction.
# When using "add_concurrent_index" or "remove_concurrent_index" methods make sure
# that either of them is the _only_ method called in the migration,
# any other changes should go in a separate migration.
# This ensures that upon failure _only_ the index creation or removing fails
# and can be retried or reverted easily.
#
# To disable transactions uncomment the following line and remove these
# comments:
# disable_ddl_transaction!
def change
create_table :<%= table_name %> do |t|
<% attributes.each do |attribute| -%>
<% if attribute.password_digest? -%>
t.string :password_digest<%= attribute.inject_options %>
<% else -%>
t.<%= attribute.type %> :<%= attribute.name %><%= attribute.inject_options %>
<% end -%>
<% end -%>
<% if options[:timestamps] %>
t.timestamps null: false
<% end -%>
end
<% attributes_with_index.each do |attribute| -%>
add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>
<% end -%>
end
end
| 38.604167 | 107 | 0.724231 |
e248d14a718b5fdc0841b202e35fe007f3f1dcbc | 14,454 | # frozen_string_literal: true
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
# Devise will use the `secret_key_base` as its `secret_key`
# by default. You can change it below and use your own secret key.
# config.secret_key = '0bf299f6e589d339869a4dff0f7d9409ec1a4d8377bace1b5b27fc870eed994973c80c09bfa82689467707e8656037c88679a7dc7ab6adf560028ad71d002c23'
# ==> Controller configuration
# Configure the parent class to the devise controllers.
# config.parent_controller = 'DeviseController'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = '[email protected]'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# Configure the parent class responsible to send e-mails.
# config.parent_mailer = 'ActionMailer::Base'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
config.authentication_keys = [:name]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [:email]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [:email]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If 401 status code should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# When false, Devise will not attempt to reload routes on eager load.
# This can reduce the time taken to boot the app but if your application
# requires the Devise mappings to be loaded during boot time the application
# won't boot properly.
# config.reload_routes = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 11. If
# using other algorithms, it sets how many times you want the password to be hashed.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# algorithm), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 11
# Set up a pepper to generate the hashed password.
# config.pepper = '1adcb86dae33975d6f27678267fda6400d84de2c40c3b9a664bc3ec08999411133bd6fb337cd4602fbb6d956db448b948753393deec828369e814cf281b296a6'
# Send a notification to the original email when the user's email is changed.
# config.send_email_changed_notification = false
# Send a notification email when the user's password is changed.
# config.send_password_change_notification = false
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day.
# You can also set it to nil, which will allow the user to access the website
# without confirming their account.
# Default is 0.days, meaning the user cannot access the website without
# confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [:email]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = true
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 6..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [:email]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = true
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [:email]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# When set to false, does not sign a user in automatically after their password is
# reset. Defaults to true, so a user is signed in automatically after a reset.
# config.sign_in_after_reset_password = true
# ==> Configuration for :encryptable
# Allow you to use another hashing or encryption algorithm besides bcrypt (default).
# You can use :sha1, :sha512 or algorithms from others authentication tools as
# :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
# for default behavior) and :restful_authentication_sha1 (then you should set
# stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using OmniAuth, Devise cannot automatically set OmniAuth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
# ==> Turbolinks configuration
# If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly:
#
# ActiveSupport.on_load(:devise_failure_app) do
# include Turbolinks::Controller
# end
# ==> Configuration for :registerable
# When set to false, does not sign a user in automatically after their password is
# changed. Defaults to true, so a user is signed in automatically after changing a password.
# config.sign_in_after_change_password = true
end
| 48.18 | 154 | 0.751349 |
01af15caecf593d787220ddc907c4d313bb2ed3f | 277 |
# 管理本地缓存的Source列表
class SourceManager
# 得到本地所有的日报类Source
def daily_sources
[]
end
# 得到本地所有的RSS类Source
def rss_sources
[]
end
# 将一个js router对象添加到列表中并持久化
def add_daily_source(s)
end
# 将一个rss router对象添加到列表中并持久化
def add_rss_source(r)
end
end | 11.08 | 29 | 0.707581 |
bbbf68cc52305845a4944632a9396d303f546371 | 868 | require "spec_helper"
describe EmergenciesController do
describe "routing" do
it "routes to #index" do
get("/emergencies").should route_to("emergencies#index")
end
it "routes to #new" do
get("/emergencies/new").should route_to("emergencies#new")
end
it "routes to #show" do
get("/emergencies/1").should route_to("emergencies#show", :id => "1")
end
it "routes to #edit" do
get("/emergencies/1/edit").should route_to("emergencies#edit", :id => "1")
end
it "routes to #create" do
post("/emergencies").should route_to("emergencies#create")
end
it "routes to #update" do
put("/emergencies/1").should route_to("emergencies#update", :id => "1")
end
it "routes to #destroy" do
delete("/emergencies/1").should route_to("emergencies#destroy", :id => "1")
end
end
end
| 24.111111 | 81 | 0.630184 |
1cd400e4dfa45f54aa0cc63d5aa12bc30ba7f551 | 4,398 | # frozen_string_literal: true
class GroupPolicy < BasePolicy
include FindGroupProjects
desc "Group is public"
with_options scope: :subject, score: 0
condition(:public_group) { @subject.public? }
with_score 0
condition(:logged_in_viewable) { @user && @subject.internal? && [email protected]? }
condition(:has_access) { access_level != GroupMember::NO_ACCESS }
condition(:guest) { access_level >= GroupMember::GUEST }
condition(:developer) { access_level >= GroupMember::DEVELOPER }
condition(:owner) { access_level >= GroupMember::OWNER }
condition(:maintainer) { access_level >= GroupMember::MAINTAINER }
condition(:reporter) { access_level >= GroupMember::REPORTER }
condition(:has_parent, scope: :subject) { @subject.has_parent? }
condition(:share_with_group_locked, scope: :subject) { @subject.share_with_group_lock? }
condition(:parent_share_with_group_locked, scope: :subject) { @subject.parent&.share_with_group_lock? }
condition(:can_change_parent_share_with_group_lock) { can?(:change_share_with_group_lock, @subject.parent) }
condition(:has_projects) do
group_projects_for(user: @user, group: @subject).any?
end
with_options scope: :subject, score: 0
condition(:request_access_enabled) { @subject.request_access_enabled }
condition(:create_projects_disabled) do
@subject.project_creation_level == ::Gitlab::Access::NO_ONE_PROJECT_ACCESS
end
condition(:developer_maintainer_access) do
@subject.project_creation_level == ::Gitlab::Access::DEVELOPER_MAINTAINER_PROJECT_ACCESS
end
condition(:maintainer_can_create_group) do
@subject.subgroup_creation_level == ::Gitlab::Access::MAINTAINER_SUBGROUP_ACCESS
end
rule { public_group }.policy do
enable :read_group
enable :read_package
end
rule { logged_in_viewable }.enable :read_group
rule { guest }.policy do
enable :read_group
enable :upload_file
end
rule { admin }.policy do
enable :read_group
enable :update_max_artifacts_size
end
rule { has_projects }.policy do
enable :read_group
end
rule { can?(:read_group) }.policy do
enable :read_milestone
enable :read_list
enable :read_label
end
rule { has_access }.enable :read_namespace
rule { developer }.policy do
enable :admin_milestone
enable :read_package
end
rule { reporter }.policy do
enable :read_container_image
enable :admin_label
enable :admin_list
enable :admin_issue
end
rule { maintainer }.policy do
enable :create_projects
enable :admin_pipeline
enable :admin_build
enable :read_cluster
enable :add_cluster
enable :create_cluster
enable :update_cluster
enable :admin_cluster
end
rule { owner }.policy do
enable :admin_group
enable :admin_namespace
enable :admin_group_member
enable :change_visibility_level
enable :set_note_created_at
enable :set_emails_disabled
end
rule { can?(:read_nested_project_resources) }.policy do
enable :read_group_activity
enable :read_group_issues
enable :read_group_boards
enable :read_group_labels
enable :read_group_milestones
enable :read_group_merge_requests
end
rule { can?(:read_cross_project) & can?(:read_group) }.policy do
enable :read_nested_project_resources
end
rule { owner }.enable :create_subgroup
rule { maintainer & maintainer_can_create_group }.enable :create_subgroup
rule { public_group | logged_in_viewable }.enable :view_globally
rule { default }.enable(:request_access)
rule { ~request_access_enabled }.prevent :request_access
rule { ~can?(:view_globally) }.prevent :request_access
rule { has_access }.prevent :request_access
rule { owner & (~share_with_group_locked | ~has_parent | ~parent_share_with_group_locked | can_change_parent_share_with_group_lock) }.enable :change_share_with_group_lock
rule { developer & developer_maintainer_access }.enable :create_projects
rule { create_projects_disabled }.prevent :create_projects
rule { owner | admin }.enable :read_statistics
rule { maintainer & can?(:create_projects) }.enable :transfer_projects
def access_level
return GroupMember::NO_ACCESS if @user.nil?
@access_level ||= lookup_access_level!
end
def lookup_access_level!
@subject.max_member_access_for_user(@user)
end
end
GroupPolicy.prepend_if_ee('EE::GroupPolicy')
| 28.934211 | 172 | 0.745566 |
e9ce76345ac592f0e872e0016f4931f143714fdd | 1,223 | #
# Concern that helps with getting an exclusive lease for running a block
# of code.
#
# `#try_obtain_lease` takes a block which will be run if it was able to
# obtain the lease. Implement `#lease_timeout` to configure the timeout
# for the exclusive lease. Optionally override `#lease_key` to set the
# lease key, it defaults to the class name with underscores.
#
module ExclusiveLeaseGuard
extend ActiveSupport::Concern
def try_obtain_lease
lease = exclusive_lease.try_obtain
unless lease
log_error('Cannot obtain an exclusive lease. There must be another instance already in execution.')
return
end
begin
yield lease
ensure
release_lease(lease)
end
end
def exclusive_lease
@lease ||= Gitlab::ExclusiveLease.new(lease_key, timeout: lease_timeout)
end
def lease_key
@lease_key ||= self.class.name.underscore
end
def lease_timeout
raise NotImplementedError,
"#{self.class.name} does not implement #{__method__}"
end
def release_lease(uuid)
Gitlab::ExclusiveLease.cancel(lease_key, uuid)
end
def renew_lease!
exclusive_lease.renew
end
def log_error(message, extra_args = {})
logger.error(message)
end
end
| 23.075472 | 105 | 0.721995 |
1aeea20138bc1d6c897bb46b20f2c8f930fa81d0 | 794 | class Srtp < Formula
homepage "https://github.com/cisco/libsrtp"
url "https://github.com/cisco/libsrtp/archive/v1.5.2.tar.gz"
sha256 "86e1efe353397c0751f6bdd709794143bd1b76494412860f16ff2b6d9c304eda"
head "https://github.com/cisco/libsrtp.git"
bottle do
cellar :any
sha256 "d9309ae800135653a7825673ca9f524aad5159e57f7c54d29ba1fbbb75d139f8" => :yosemite
sha256 "3c7eff0e7a306b87513d9ced345b940ca12bb22a8b95045d932b21576d526cea" => :mavericks
sha256 "47880688a74a1e15056b831f46addf25a80bc4ce278f5c473a2764590a040e2a" => :mountain_lion
end
def install
system "./configure", "--disable-debug",
"--prefix=#{prefix}"
system "make", "shared_library"
system "make", "install" # Can't go in parallel of building the dylib
end
end
| 36.090909 | 95 | 0.740554 |
1dd8763eac0462617a998487b730013a8dfa8245 | 2,147 | # This handles CRUD operations for teachers
class TeachersController < ApplicationController
before_action :set_teacher, only: %i[show edit update destroy students]
# GET /teachers
# GET /teachers.json
def index
@teachers = Teacher.all
end
# GET /teachers/1.json
def show
respond_to do |format|
format.html { redirect_to Teacher }
format.json { render :show }
end
end
# GET /teachers/new
def new
@teacher = Teacher.new
end
# GET /teachers/1/edit
def edit; end
# POST /teachers
# POST /teachers.json
def create
@teacher = Teacher.new(teacher_params)
respond_to do |format|
if @teacher.save
format.html { redirect_to Teacher, notice: 'Teacher was successfully created.' }
format.json { render :show, status: :created, location: @teacher }
else
format.html { render :new }
format.json { render json: @teacher.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /teachers/1
# PATCH/PUT /teachers/1.json
def update
respond_to do |format|
if @teacher.update(teacher_params)
format.html { redirect_to Teacher, notice: 'Teacher was successfully updated.' }
format.json { render :show, status: :ok, location: @teacher }
else
format.html { render :edit }
format.json { render json: @teacher.errors, status: :unprocessable_entity }
end
end
end
# DELETE /teachers/1
# DELETE /teachers/1.json
def destroy
@teacher.destroy
respond_to do |format|
format.html { redirect_to teachers_url, notice: 'Teacher was successfully destroyed.' }
format.json { head :no_content }
end
end
# GET /teachers/1/students
def students
@students = @teacher.students.order(:name).includes(lesson_part: :lesson).all
end
private
# Use callbacks to share common setup or constraints between actions.
def set_teacher
@teacher = Teacher.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def teacher_params
params.require(:teacher).permit(:name)
end
end
| 25.559524 | 93 | 0.673032 |
ac5bd0e21f177c54db104cc3f55ddf38a8842510 | 4,620 | # frozen_string_literal: true
require 'bunny'
require 'ostruct'
class EventMailer
def initialize(events, exchanges, keychain)
@exchanges = exchanges
@keychain = keychain
@events = events
Kernel.at_exit { unlisten }
end
def call
listen
end
private
def listen
unlisten
@bunny_session = Bunny::Session.new(rabbitmq_credentials).tap(&:start)
@bunny_channel = @bunny_session.channel
queue = @bunny_channel.queue('', auto_delete: true, durable: true)
@events.each do |event|
exchange = @bunny_channel.direct(@exchanges[event[:exchange].to_sym][:name])
queue.bind(exchange, routing_key: event[:key])
end
Rails.logger.info { 'Listening for events.' }
queue.subscribe(manual_ack: true, block: true, &method(:handle_message))
end
def unlisten
if @bunny_session || @bunny_channel
Rails.logger.info { 'No longer listening for events.' }
end
@bunny_channel&.work_pool&.kill
@bunny_session&.stop
ensure
@bunny_channel = nil
@bunny_session = nil
end
def algorithm_verification_options(signer)
{ algorithms: @keychain[signer][:algorithm] }
end
def jwt_public_key(signer)
OpenSSL::PKey.read(Base64.urlsafe_decode64(@keychain[signer][:value]))
end
def rabbitmq_credentials
if Barong::App.config.event_api_rabbitmq_url.present?
Barong::App.config.event_api_rabbitmq_url
else
{
host: Barong::App.config.event_api_rabbitmq_host,
port: Barong::App.config.event_api_rabbitmq_port,
username: Barong::App.config.event_api_rabbitmq_username,
password: Barong::App.config.event_api_rabbitmq_password
}
end
end
def handle_message(delivery_info, _metadata, payload)
exchange = @exchanges.select { |_, ex| ex[:name] == delivery_info[:exchange] }
exchange_id = exchange.keys.first.to_s
signer = exchange[exchange_id.to_sym][:signer]
result = verify_jwt(payload, signer.to_sym)
raise "Failed to verify signature from #{signer}." \
unless result[:verified].include?(signer.to_sym)
config = @events.select do |event|
event[:key] == delivery_info[:routing_key] &&
event[:exchange] == exchange_id
end.first
event = result[:payload].fetch(:event)
obj = JSON.parse(event.to_json, object_class: OpenStruct)
user = User.includes(:profiles).find_by(uid: obj.record.user.uid)
language = user.language.to_sym
unless config[:templates].key?(language)
Rails.logger.error { "Language #{language} is not supported. Skipping." }
return
end
if config[:expression].present? && skip_event(event, config[:expression])
Rails.logger.info { "Event #{obj.name} skipped" }
return
end
params = {
subject: config[:templates][language][:subject],
template_name: config[:templates][language][:template_path],
record: obj.record,
changes: obj.changes,
user: user
}
Postmaster.process_payload(params).deliver_now
@bunny_channel.acknowledge(delivery_info.delivery_tag, false)
rescue StandardError => e
Rails.logger.error { e.inspect }
raise e if is_db_connection_error?(e)
end
def verify_jwt(payload, signer)
options = algorithm_verification_options(signer)
JWT::Multisig.verify_jwt JSON.parse(payload), { signer => jwt_public_key(signer) },
options.compact
end
def skip_event(event, expression)
# valid operators: and / or / not
operator = expression.keys.first.downcase
# { field_name: field_value }
values = expression[operator]
# return array of boolean [false, true]
res = values.keys.map do |field_name|
safe_dig(event, field_name.to_s.split('.')) == values[field_name]
end
# all? works as AND operator, any? works as OR operator
return false if (operator == :and && res.all?) || (operator == :or && res.any?) ||
(operator == :not && !res.all?)
return true if operator == :not && res.all?
true
end
def is_db_connection_error?(exception)
exception.is_a?(Mysql2::Error::ConnectionError) || exception.cause.is_a?(Mysql2::Error)
end
def safe_dig(hash, keypath, default = nil)
stringified_hash = JSON.parse(hash.to_json)
stringified_keypath = keypath.map(&:to_s)
stringified_keypath.reduce(stringified_hash) do |accessible, key|
return default unless accessible.is_a? Hash
return default unless accessible.key? key
accessible[key]
end
end
class << self
def call(*args)
new(*args).call
end
end
end
| 28 | 91 | 0.675758 |
399a9df764c65da00d25752a30403c9eb457fb89 | 2,207 | require 'puppet/provider/package'
Puppet::Type.type(:package).provide :pkg, :parent => Puppet::Provider::Package do
desc "OpenSolaris image packaging system. See pkg(5) for more information"
commands :pkg => "/usr/bin/pkg"
confine :operatingsystem => :solaris
#defaultfor [:operatingsystem => :solaris, :kernelrelease => "5.11"]
def self.instances
packages = []
pkg(:list, '-H').each_line do |line|
# now turn each returned line into a package object
if hash = parse_line(line.chomp)
packages << new(hash)
end
end
packages
end
self::REGEX = /^(\S+)(?:\s+\(.*?\))?\s+(\S+)\s+(\S+)\s+\S+$/
self::FIELDS = [:name, :version, :status]
def self.parse_line(line)
hash = {}
if match = self::REGEX.match(line)
self::FIELDS.zip(match.captures) { |field,value|
hash[field] = value
}
hash[:provider] = self.name
if hash[:status] == "installed"
hash[:ensure] = :present
else
hash[:ensure] = :absent
end
else
warning "Failed to match 'pkg list' line #{line.inspect}"
return nil
end
hash
end
# return the version of the package
# TODO deal with multiple publishers
def latest
version = nil
pkg(:list, "-Ha", @resource[:name]).each_line do |line|
v = parse_line(line.chomp)[:status]
case v
when "known"
return v
when "installed"
version = v
else
Puppet.warn "unknown package state for #{@resource[:name]}: #{v}"
end
end
version
end
# install the package
def install
pkg :install, @resource[:name]
end
# uninstall the package
def uninstall
pkg :uninstall, '-r', @resource[:name]
end
# update the package to the latest version available
def update
self.install
end
# list a specific package
def query
begin
output = pkg(:list, "-H", @resource[:name])
rescue Puppet::ExecutionFailure
# pkg returns 1 if the package is not found.
return {:ensure => :absent, :name => @resource[:name]}
end
hash = self.class.parse_line(output.chomp) || {:ensure => :absent, :name => @resource[:name]}
hash
end
end
| 22.752577 | 97 | 0.603534 |
26c7308acb5341c8701b18b73a4519465ac29ae8 | 51,055 | # WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
require 'seahorse/client/plugins/content_length.rb'
require 'aws-sdk-core/plugins/credentials_configuration.rb'
require 'aws-sdk-core/plugins/logging.rb'
require 'aws-sdk-core/plugins/param_converter.rb'
require 'aws-sdk-core/plugins/param_validator.rb'
require 'aws-sdk-core/plugins/user_agent.rb'
require 'aws-sdk-core/plugins/helpful_socket_errors.rb'
require 'aws-sdk-core/plugins/retry_errors.rb'
require 'aws-sdk-core/plugins/global_configuration.rb'
require 'aws-sdk-core/plugins/regional_endpoint.rb'
require 'aws-sdk-core/plugins/response_paging.rb'
require 'aws-sdk-core/plugins/stub_responses.rb'
require 'aws-sdk-core/plugins/idempotency_token.rb'
require 'aws-sdk-core/plugins/jsonvalue_converter.rb'
require 'aws-sdk-core/plugins/signature_v4.rb'
require 'aws-sdk-core/plugins/protocols/json_rpc.rb'
Aws::Plugins::GlobalConfiguration.add_identifier(:servicediscovery)
module Aws::ServiceDiscovery
class Client < Seahorse::Client::Base
include Aws::ClientStubs
@identifier = :servicediscovery
set_api(ClientApi::API)
add_plugin(Seahorse::Client::Plugins::ContentLength)
add_plugin(Aws::Plugins::CredentialsConfiguration)
add_plugin(Aws::Plugins::Logging)
add_plugin(Aws::Plugins::ParamConverter)
add_plugin(Aws::Plugins::ParamValidator)
add_plugin(Aws::Plugins::UserAgent)
add_plugin(Aws::Plugins::HelpfulSocketErrors)
add_plugin(Aws::Plugins::RetryErrors)
add_plugin(Aws::Plugins::GlobalConfiguration)
add_plugin(Aws::Plugins::RegionalEndpoint)
add_plugin(Aws::Plugins::ResponsePaging)
add_plugin(Aws::Plugins::StubResponses)
add_plugin(Aws::Plugins::IdempotencyToken)
add_plugin(Aws::Plugins::JsonvalueConverter)
add_plugin(Aws::Plugins::SignatureV4)
add_plugin(Aws::Plugins::Protocols::JsonRpc)
# @option options [required, Aws::CredentialProvider] :credentials
# Your AWS credentials. This can be an instance of any one of the
# following classes:
#
# * `Aws::Credentials` - Used for configuring static, non-refreshing
# credentials.
#
# * `Aws::InstanceProfileCredentials` - Used for loading credentials
# from an EC2 IMDS on an EC2 instance.
#
# * `Aws::SharedCredentials` - Used for loading credentials from a
# shared file, such as `~/.aws/config`.
#
# * `Aws::AssumeRoleCredentials` - Used when you need to assume a role.
#
# When `:credentials` are not configured directly, the following
# locations will be searched for credentials:
#
# * `Aws.config[:credentials]`
# * The `:access_key_id`, `:secret_access_key`, and `:session_token` options.
# * ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']
# * `~/.aws/credentials`
# * `~/.aws/config`
# * EC2 IMDS instance profile - When used by default, the timeouts are
# very aggressive. Construct and pass an instance of
# `Aws::InstanceProfileCredentails` to enable retries and extended
# timeouts.
#
# @option options [required, String] :region
# The AWS region to connect to. The configured `:region` is
# used to determine the service `:endpoint`. When not passed,
# a default `:region` is search for in the following locations:
#
# * `Aws.config[:region]`
# * `ENV['AWS_REGION']`
# * `ENV['AMAZON_REGION']`
# * `ENV['AWS_DEFAULT_REGION']`
# * `~/.aws/credentials`
# * `~/.aws/config`
#
# @option options [String] :access_key_id
#
# @option options [Boolean] :convert_params (true)
# When `true`, an attempt is made to coerce request parameters into
# the required types.
#
# @option options [String] :endpoint
# The client endpoint is normally constructed from the `:region`
# option. You should only configure an `:endpoint` when connecting
# to test endpoints. This should be avalid HTTP(S) URI.
#
# @option options [Aws::Log::Formatter] :log_formatter (Aws::Log::Formatter.default)
# The log formatter.
#
# @option options [Symbol] :log_level (:info)
# The log level to send messages to the `:logger` at.
#
# @option options [Logger] :logger
# The Logger instance to send log messages to. If this option
# is not set, logging will be disabled.
#
# @option options [String] :profile ("default")
# Used when loading credentials from the shared credentials file
# at HOME/.aws/credentials. When not specified, 'default' is used.
#
# @option options [Integer] :retry_limit (3)
# The maximum number of times to retry failed requests. Only
# ~ 500 level server errors and certain ~ 400 level client errors
# are retried. Generally, these are throttling errors, data
# checksum errors, networking errors, timeout errors and auth
# errors from expired credentials.
#
# @option options [String] :secret_access_key
#
# @option options [String] :session_token
#
# @option options [Boolean] :simple_json (false)
# Disables request parameter conversion, validation, and formatting.
# Also disable response data type conversions. This option is useful
# when you want to ensure the highest level of performance by
# avoiding overhead of walking request parameters and response data
# structures.
#
# When `:simple_json` is enabled, the request parameters hash must
# be formatted exactly as the DynamoDB API expects.
#
# @option options [Boolean] :stub_responses (false)
# Causes the client to return stubbed responses. By default
# fake responses are generated and returned. You can specify
# the response data to return or errors to raise by calling
# {ClientStubs#stub_responses}. See {ClientStubs} for more information.
#
# ** Please note ** When response stubbing is enabled, no HTTP
# requests are made, and retries are disabled.
#
# @option options [Boolean] :validate_params (true)
# When `true`, request parameters are validated before
# sending the request.
#
def initialize(*args)
super
end
# @!group API Operations
# Creates a private namespace based on DNS, which will be visible only
# inside a specified Amazon VPC. The namespace defines your service
# naming scheme. For example, if you name your namespace `example.com`
# and name your service `backend`, the resulting DNS name for the
# service will be `backend.example.com`. For the current limit on the
# number of namespaces that you can create using the same AWS account,
# see [Limits on Auto Naming][1] in the *Route 53 Developer Guide*.
#
#
#
# [1]: http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html#limits-api-entities-autonaming
#
# @option params [required, String] :name
# The name that you want to assign to this namespace. When you create a
# namespace, Amazon Route 53 automatically creates a hosted zone that
# has the same name as the namespace.
#
# @option params [String] :creator_request_id
# A unique string that identifies the request and that allows failed
# `CreatePrivateDnsNamespace` requests to be retried without the risk of
# executing the operation twice. `CreatorRequestId` can be any unique
# string, for example, a date/time stamp.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @option params [String] :description
# A description for the namespace.
#
# @option params [required, String] :vpc
# The ID of the Amazon VPC that you want to associate the namespace
# with.
#
# @return [Types::CreatePrivateDnsNamespaceResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreatePrivateDnsNamespaceResponse#operation_id #operation_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_private_dns_namespace({
# name: "NamespaceName", # required
# creator_request_id: "ResourceId",
# description: "ResourceDescription",
# vpc: "ResourceId", # required
# })
#
# @example Response structure
#
# resp.operation_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreatePrivateDnsNamespace AWS API Documentation
#
# @overload create_private_dns_namespace(params = {})
# @param [Hash] params ({})
def create_private_dns_namespace(params = {}, options = {})
req = build_request(:create_private_dns_namespace, params)
req.send_request(options)
end
# Creates a public namespace based on DNS, which will be visible on the
# internet. The namespace defines your service naming scheme. For
# example, if you name your namespace `example.com` and name your
# service `backend`, the resulting DNS name for the service will be
# `backend.example.com`. For the current limit on the number of
# namespaces that you can create using the same AWS account, see [Limits
# on Auto Naming][1] in the *Route 53 Developer Guide*.
#
#
#
# [1]: http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html#limits-api-entities-autonaming
#
# @option params [required, String] :name
# The name that you want to assign to this namespace.
#
# @option params [String] :creator_request_id
# A unique string that identifies the request and that allows failed
# `CreatePublicDnsNamespace` requests to be retried without the risk of
# executing the operation twice. `CreatorRequestId` can be any unique
# string, for example, a date/time stamp.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @option params [String] :description
# A description for the namespace.
#
# @return [Types::CreatePublicDnsNamespaceResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreatePublicDnsNamespaceResponse#operation_id #operation_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_public_dns_namespace({
# name: "NamespaceName", # required
# creator_request_id: "ResourceId",
# description: "ResourceDescription",
# })
#
# @example Response structure
#
# resp.operation_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreatePublicDnsNamespace AWS API Documentation
#
# @overload create_public_dns_namespace(params = {})
# @param [Hash] params ({})
def create_public_dns_namespace(params = {}, options = {})
req = build_request(:create_public_dns_namespace, params)
req.send_request(options)
end
# Creates a service, which defines the configuration for the following
# entities:
#
# * Up to three records (A, AAAA, and SRV) or one CNAME record
#
# * Optionally, a health check
#
# After you create the service, you can submit a RegisterInstance
# request, and Amazon Route 53 uses the values in the configuration to
# create the specified entities.
#
# For the current limit on the number of instances that you can register
# using the same namespace and using the same service, see [Limits on
# Auto Naming][1] in the *Route 53 Developer Guide*.
#
#
#
# [1]: http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html#limits-api-entities-autonaming
#
# @option params [required, String] :name
# The name that you want to assign to the service.
#
# @option params [String] :creator_request_id
# A unique string that identifies the request and that allows failed
# `CreateService` requests to be retried without the risk of executing
# the operation twice. `CreatorRequestId` can be any unique string, for
# example, a date/time stamp.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @option params [String] :description
# A description for the service.
#
# @option params [required, Types::DnsConfig] :dns_config
# A complex type that contains information about the records that you
# want Route 53 to create when you register an instance.
#
# @option params [Types::HealthCheckConfig] :health_check_config
# *Public DNS namespaces only.* A complex type that contains settings
# for an optional health check. If you specify settings for a health
# check, Route 53 associates the health check with all the records that
# you specify in `DnsConfig`.
#
# For information about the charges for health checks, see [Route 53
# Pricing][1].
#
#
#
# [1]: http://aws.amazon.com/route53/pricing
#
# @option params [Types::HealthCheckCustomConfig] :health_check_custom_config
#
# @return [Types::CreateServiceResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateServiceResponse#service #service} => Types::Service
#
# @example Request syntax with placeholder values
#
# resp = client.create_service({
# name: "ServiceName", # required
# creator_request_id: "ResourceId",
# description: "ResourceDescription",
# dns_config: { # required
# namespace_id: "ResourceId", # required
# routing_policy: "MULTIVALUE", # accepts MULTIVALUE, WEIGHTED
# dns_records: [ # required
# {
# type: "SRV", # required, accepts SRV, A, AAAA, CNAME
# ttl: 1, # required
# },
# ],
# },
# health_check_config: {
# type: "HTTP", # accepts HTTP, HTTPS, TCP
# resource_path: "ResourcePath",
# failure_threshold: 1,
# },
# health_check_custom_config: {
# failure_threshold: 1,
# },
# })
#
# @example Response structure
#
# resp.service.id #=> String
# resp.service.arn #=> String
# resp.service.name #=> String
# resp.service.description #=> String
# resp.service.instance_count #=> Integer
# resp.service.dns_config.namespace_id #=> String
# resp.service.dns_config.routing_policy #=> String, one of "MULTIVALUE", "WEIGHTED"
# resp.service.dns_config.dns_records #=> Array
# resp.service.dns_config.dns_records[0].type #=> String, one of "SRV", "A", "AAAA", "CNAME"
# resp.service.dns_config.dns_records[0].ttl #=> Integer
# resp.service.health_check_config.type #=> String, one of "HTTP", "HTTPS", "TCP"
# resp.service.health_check_config.resource_path #=> String
# resp.service.health_check_config.failure_threshold #=> Integer
# resp.service.health_check_custom_config.failure_threshold #=> Integer
# resp.service.create_date #=> Time
# resp.service.creator_request_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreateService AWS API Documentation
#
# @overload create_service(params = {})
# @param [Hash] params ({})
def create_service(params = {}, options = {})
req = build_request(:create_service, params)
req.send_request(options)
end
# Deletes a namespace from the current account. If the namespace still
# contains one or more services, the request fails.
#
# @option params [required, String] :id
# The ID of the namespace that you want to delete.
#
# @return [Types::DeleteNamespaceResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DeleteNamespaceResponse#operation_id #operation_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.delete_namespace({
# id: "ResourceId", # required
# })
#
# @example Response structure
#
# resp.operation_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DeleteNamespace AWS API Documentation
#
# @overload delete_namespace(params = {})
# @param [Hash] params ({})
def delete_namespace(params = {}, options = {})
req = build_request(:delete_namespace, params)
req.send_request(options)
end
# Deletes a specified service. If the service still contains one or more
# registered instances, the request fails.
#
# @option params [required, String] :id
# The ID of the service that you want to delete.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_service({
# id: "ResourceId", # required
# })
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DeleteService AWS API Documentation
#
# @overload delete_service(params = {})
# @param [Hash] params ({})
def delete_service(params = {}, options = {})
req = build_request(:delete_service, params)
req.send_request(options)
end
# Deletes the records and the health check, if any, that Amazon Route 53
# created for the specified instance.
#
# @option params [required, String] :service_id
# The ID of the service that the instance is associated with.
#
# @option params [required, String] :instance_id
# The value that you specified for `Id` in the RegisterInstance request.
#
# @return [Types::DeregisterInstanceResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DeregisterInstanceResponse#operation_id #operation_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.deregister_instance({
# service_id: "ResourceId", # required
# instance_id: "ResourceId", # required
# })
#
# @example Response structure
#
# resp.operation_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DeregisterInstance AWS API Documentation
#
# @overload deregister_instance(params = {})
# @param [Hash] params ({})
def deregister_instance(params = {}, options = {})
req = build_request(:deregister_instance, params)
req.send_request(options)
end
# Gets information about a specified instance.
#
# @option params [required, String] :service_id
# The ID of the service that the instance is associated with.
#
# @option params [required, String] :instance_id
# The ID of the instance that you want to get information about.
#
# @return [Types::GetInstanceResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetInstanceResponse#instance #instance} => Types::Instance
#
# @example Request syntax with placeholder values
#
# resp = client.get_instance({
# service_id: "ResourceId", # required
# instance_id: "ResourceId", # required
# })
#
# @example Response structure
#
# resp.instance.id #=> String
# resp.instance.creator_request_id #=> String
# resp.instance.attributes #=> Hash
# resp.instance.attributes["AttrKey"] #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetInstance AWS API Documentation
#
# @overload get_instance(params = {})
# @param [Hash] params ({})
def get_instance(params = {}, options = {})
req = build_request(:get_instance, params)
req.send_request(options)
end
# Gets the current health status (`Healthy`, `Unhealthy`, or `Unknown`)
# of one or more instances that are associated with a specified service.
#
# <note markdown="1"> There is a brief delay between when you register an instance and when
# the health status for the instance is available.
#
# </note>
#
# @option params [required, String] :service_id
# The ID of the service that the instance is associated with.
#
# @option params [Array<String>] :instances
# An array that contains the IDs of all the instances that you want to
# get the health status for.
#
# If you omit `Instances`, Amazon Route 53 returns the health status for
# all the instances that are associated with the specified service.
#
# <note markdown="1"> To get the IDs for the instances that you've registered by using a
# specified service, submit a ListInstances request.
#
# </note>
#
# @option params [Integer] :max_results
# The maximum number of instances that you want Route 53 to return in
# the response to a `GetInstancesHealthStatus` request. If you don't
# specify a value for `MaxResults`, Route 53 returns up to 100
# instances.
#
# @option params [String] :next_token
# For the first `GetInstancesHealthStatus` request, omit this value.
#
# If more than `MaxResults` instances match the specified criteria, you
# can submit another `GetInstancesHealthStatus` request to get the next
# group of results. Specify the value of `NextToken` from the previous
# response in the next request.
#
# @return [Types::GetInstancesHealthStatusResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetInstancesHealthStatusResponse#status #status} => Hash<String,String>
# * {Types::GetInstancesHealthStatusResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_instances_health_status({
# service_id: "ResourceId", # required
# instances: ["ResourceId"],
# max_results: 1,
# next_token: "NextToken",
# })
#
# @example Response structure
#
# resp.status #=> Hash
# resp.status["ResourceId"] #=> String, one of "HEALTHY", "UNHEALTHY", "UNKNOWN"
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetInstancesHealthStatus AWS API Documentation
#
# @overload get_instances_health_status(params = {})
# @param [Hash] params ({})
def get_instances_health_status(params = {}, options = {})
req = build_request(:get_instances_health_status, params)
req.send_request(options)
end
# Gets information about a namespace.
#
# @option params [required, String] :id
# The ID of the namespace that you want to get information about.
#
# @return [Types::GetNamespaceResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetNamespaceResponse#namespace #namespace} => Types::Namespace
#
# @example Request syntax with placeholder values
#
# resp = client.get_namespace({
# id: "ResourceId", # required
# })
#
# @example Response structure
#
# resp.namespace.id #=> String
# resp.namespace.arn #=> String
# resp.namespace.name #=> String
# resp.namespace.type #=> String, one of "DNS_PUBLIC", "DNS_PRIVATE"
# resp.namespace.description #=> String
# resp.namespace.service_count #=> Integer
# resp.namespace.properties.dns_properties.hosted_zone_id #=> String
# resp.namespace.create_date #=> Time
# resp.namespace.creator_request_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetNamespace AWS API Documentation
#
# @overload get_namespace(params = {})
# @param [Hash] params ({})
def get_namespace(params = {}, options = {})
req = build_request(:get_namespace, params)
req.send_request(options)
end
# Gets information about any operation that returns an operation ID in
# the response, such as a `CreateService` request.
#
# <note markdown="1"> To get a list of operations that match specified criteria, see
# ListOperations.
#
# </note>
#
# @option params [required, String] :operation_id
# The ID of the operation that you want to get more information about.
#
# @return [Types::GetOperationResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetOperationResponse#operation #operation} => Types::Operation
#
# @example Request syntax with placeholder values
#
# resp = client.get_operation({
# operation_id: "ResourceId", # required
# })
#
# @example Response structure
#
# resp.operation.id #=> String
# resp.operation.type #=> String, one of "CREATE_NAMESPACE", "DELETE_NAMESPACE", "UPDATE_SERVICE", "REGISTER_INSTANCE", "DEREGISTER_INSTANCE"
# resp.operation.status #=> String, one of "SUBMITTED", "PENDING", "SUCCESS", "FAIL"
# resp.operation.error_message #=> String
# resp.operation.error_code #=> String
# resp.operation.create_date #=> Time
# resp.operation.update_date #=> Time
# resp.operation.targets #=> Hash
# resp.operation.targets["OperationTargetType"] #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetOperation AWS API Documentation
#
# @overload get_operation(params = {})
# @param [Hash] params ({})
def get_operation(params = {}, options = {})
req = build_request(:get_operation, params)
req.send_request(options)
end
# Gets the settings for a specified service.
#
# @option params [required, String] :id
# The ID of the service that you want to get settings for.
#
# @return [Types::GetServiceResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetServiceResponse#service #service} => Types::Service
#
# @example Request syntax with placeholder values
#
# resp = client.get_service({
# id: "ResourceId", # required
# })
#
# @example Response structure
#
# resp.service.id #=> String
# resp.service.arn #=> String
# resp.service.name #=> String
# resp.service.description #=> String
# resp.service.instance_count #=> Integer
# resp.service.dns_config.namespace_id #=> String
# resp.service.dns_config.routing_policy #=> String, one of "MULTIVALUE", "WEIGHTED"
# resp.service.dns_config.dns_records #=> Array
# resp.service.dns_config.dns_records[0].type #=> String, one of "SRV", "A", "AAAA", "CNAME"
# resp.service.dns_config.dns_records[0].ttl #=> Integer
# resp.service.health_check_config.type #=> String, one of "HTTP", "HTTPS", "TCP"
# resp.service.health_check_config.resource_path #=> String
# resp.service.health_check_config.failure_threshold #=> Integer
# resp.service.health_check_custom_config.failure_threshold #=> Integer
# resp.service.create_date #=> Time
# resp.service.creator_request_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetService AWS API Documentation
#
# @overload get_service(params = {})
# @param [Hash] params ({})
def get_service(params = {}, options = {})
req = build_request(:get_service, params)
req.send_request(options)
end
# Lists summary information about the instances that you registered by
# using a specified service.
#
# @option params [required, String] :service_id
# The ID of the service that you want to list instances for.
#
# @option params [String] :next_token
# For the first `ListInstances` request, omit this value.
#
# If more than `MaxResults` instances match the specified criteria, you
# can submit another `ListInstances` request to get the next group of
# results. Specify the value of `NextToken` from the previous response
# in the next request.
#
# @option params [Integer] :max_results
# The maximum number of instances that you want Amazon Route 53 to
# return in the response to a `ListInstances` request. If you don't
# specify a value for `MaxResults`, Route 53 returns up to 100
# instances.
#
# @return [Types::ListInstancesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListInstancesResponse#instances #instances} => Array<Types::InstanceSummary>
# * {Types::ListInstancesResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.list_instances({
# service_id: "ResourceId", # required
# next_token: "NextToken",
# max_results: 1,
# })
#
# @example Response structure
#
# resp.instances #=> Array
# resp.instances[0].id #=> String
# resp.instances[0].attributes #=> Hash
# resp.instances[0].attributes["AttrKey"] #=> String
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListInstances AWS API Documentation
#
# @overload list_instances(params = {})
# @param [Hash] params ({})
def list_instances(params = {}, options = {})
req = build_request(:list_instances, params)
req.send_request(options)
end
# Lists summary information about the namespaces that were created by
# the current AWS account.
#
# @option params [String] :next_token
# For the first `ListNamespaces` request, omit this value.
#
# If the response contains `NextToken`, submit another `ListNamespaces`
# request to get the next group of results. Specify the value of
# `NextToken` from the previous response in the next request.
#
# <note markdown="1"> Route 53 gets `MaxResults` namespaces and then filters them based on
# the specified criteria. It's possible that no namespaces in the first
# `MaxResults` namespaces matched the specified criteria but that
# subsequent groups of `MaxResults` namespaces do contain namespaces
# that match the criteria.
#
# </note>
#
# @option params [Integer] :max_results
# The maximum number of namespaces that you want Amazon Route 53 to
# return in the response to a `ListNamespaces` request. If you don't
# specify a value for `MaxResults`, Route 53 returns up to 100
# namespaces.
#
# @option params [Array<Types::NamespaceFilter>] :filters
# A complex type that contains specifications for the namespaces that
# you want to list.
#
# If you specify more than one filter, a namespace must match all
# filters to be returned by `ListNamespaces`.
#
# @return [Types::ListNamespacesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListNamespacesResponse#namespaces #namespaces} => Array<Types::NamespaceSummary>
# * {Types::ListNamespacesResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.list_namespaces({
# next_token: "NextToken",
# max_results: 1,
# filters: [
# {
# name: "TYPE", # required, accepts TYPE
# values: ["FilterValue"], # required
# condition: "EQ", # accepts EQ, IN, BETWEEN
# },
# ],
# })
#
# @example Response structure
#
# resp.namespaces #=> Array
# resp.namespaces[0].id #=> String
# resp.namespaces[0].arn #=> String
# resp.namespaces[0].name #=> String
# resp.namespaces[0].type #=> String, one of "DNS_PUBLIC", "DNS_PRIVATE"
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListNamespaces AWS API Documentation
#
# @overload list_namespaces(params = {})
# @param [Hash] params ({})
def list_namespaces(params = {}, options = {})
req = build_request(:list_namespaces, params)
req.send_request(options)
end
# Lists operations that match the criteria that you specify.
#
# @option params [String] :next_token
# For the first `ListOperations` request, omit this value.
#
# If the response contains `NextToken`, submit another `ListOperations`
# request to get the next group of results. Specify the value of
# `NextToken` from the previous response in the next request.
#
# <note markdown="1"> Route 53 gets `MaxResults` operations and then filters them based on
# the specified criteria. It's possible that no operations in the first
# `MaxResults` operations matched the specified criteria but that
# subsequent groups of `MaxResults` operations do contain operations
# that match the criteria.
#
# </note>
#
# @option params [Integer] :max_results
# The maximum number of items that you want Amazon Route 53 to return in
# the response to a `ListOperations` request. If you don't specify a
# value for `MaxResults`, Route 53 returns up to 100 operations.
#
# @option params [Array<Types::OperationFilter>] :filters
# A complex type that contains specifications for the operations that
# you want to list, for example, operations that you started between a
# specified start date and end date.
#
# If you specify more than one filter, an operation must match all
# filters to be returned by `ListOperations`.
#
# @return [Types::ListOperationsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListOperationsResponse#operations #operations} => Array<Types::OperationSummary>
# * {Types::ListOperationsResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.list_operations({
# next_token: "NextToken",
# max_results: 1,
# filters: [
# {
# name: "NAMESPACE_ID", # required, accepts NAMESPACE_ID, SERVICE_ID, STATUS, TYPE, UPDATE_DATE
# values: ["FilterValue"], # required
# condition: "EQ", # accepts EQ, IN, BETWEEN
# },
# ],
# })
#
# @example Response structure
#
# resp.operations #=> Array
# resp.operations[0].id #=> String
# resp.operations[0].status #=> String, one of "SUBMITTED", "PENDING", "SUCCESS", "FAIL"
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListOperations AWS API Documentation
#
# @overload list_operations(params = {})
# @param [Hash] params ({})
def list_operations(params = {}, options = {})
req = build_request(:list_operations, params)
req.send_request(options)
end
# Lists summary information for all the services that are associated
# with one or more specified namespaces.
#
# @option params [String] :next_token
# For the first `ListServices` request, omit this value.
#
# If the response contains `NextToken`, submit another `ListServices`
# request to get the next group of results. Specify the value of
# `NextToken` from the previous response in the next request.
#
# <note markdown="1"> Route 53 gets `MaxResults` services and then filters them based on the
# specified criteria. It's possible that no services in the first
# `MaxResults` services matched the specified criteria but that
# subsequent groups of `MaxResults` services do contain services that
# match the criteria.
#
# </note>
#
# @option params [Integer] :max_results
# The maximum number of services that you want Amazon Route 53 to return
# in the response to a `ListServices` request. If you don't specify a
# value for `MaxResults`, Route 53 returns up to 100 services.
#
# @option params [Array<Types::ServiceFilter>] :filters
# A complex type that contains specifications for the namespaces that
# you want to list services for.
#
# If you specify more than one filter, an operation must match all
# filters to be returned by `ListServices`.
#
# @return [Types::ListServicesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListServicesResponse#services #services} => Array<Types::ServiceSummary>
# * {Types::ListServicesResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.list_services({
# next_token: "NextToken",
# max_results: 1,
# filters: [
# {
# name: "NAMESPACE_ID", # required, accepts NAMESPACE_ID
# values: ["FilterValue"], # required
# condition: "EQ", # accepts EQ, IN, BETWEEN
# },
# ],
# })
#
# @example Response structure
#
# resp.services #=> Array
# resp.services[0].id #=> String
# resp.services[0].arn #=> String
# resp.services[0].name #=> String
# resp.services[0].description #=> String
# resp.services[0].instance_count #=> Integer
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListServices AWS API Documentation
#
# @overload list_services(params = {})
# @param [Hash] params ({})
def list_services(params = {}, options = {})
req = build_request(:list_services, params)
req.send_request(options)
end
# Creates or updates one or more records and optionally a health check
# based on the settings in a specified service. When you submit a
# `RegisterInstance` request, Amazon Route 53 does the following:
#
# * For each DNS record that you define in the service specified by
# `ServiceId`, creates or updates a record in the hosted zone that is
# associated with the corresponding namespace
#
# * If the service includes `HealthCheckConfig`, creates or updates a
# health check based on the settings in the health check configuration
#
# * Associates the health check, if any, with each of the records
#
# One `RegisterInstance` request must complete before you can submit
# another request and specify the same service ID and instance ID.
#
# For more information, see CreateService.
#
# When Route 53 receives a DNS query for the specified DNS name, it
# returns the applicable value:
#
# * **If the health check is healthy**\: returns all the records
#
# * **If the health check is unhealthy**\: returns the applicable value
# for the last healthy instance
#
# * **If you didn't specify a health check configuration**\: returns
# all the records
#
# For the current limit on the number of instances that you can register
# using the same namespace and using the same service, see [Limits on
# Auto Naming][1] in the *Route 53 Developer Guide*.
#
#
#
# [1]: http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html#limits-api-entities-autonaming
#
# @option params [required, String] :service_id
# The ID of the service that you want to use for settings for the
# records and health check that Route 53 will create.
#
# @option params [required, String] :instance_id
# An identifier that you want to associate with the instance. Note the
# following:
#
# * If the service that is specified by `ServiceId` includes settings
# for an SRV record, the value of `InstanceId` is automatically
# included as part of the value for the SRV record. For more
# information, see DnsRecord$Type.
#
# * You can use this value to update an existing instance.
#
# * To register a new instance, you must specify a value that is unique
# among instances that you register by using the same service.
#
# * If you specify an existing `InstanceId` and `ServiceId`, Route 53
# updates the existing records. If there's also an existing health
# check, Route 53 deletes the old health check and creates a new one.
#
# <note markdown="1"> The health check isn't deleted immediately, so it will still appear
# for a while if you submit a `ListHealthChecks` request, for example.
#
# </note>
#
# @option params [String] :creator_request_id
# A unique string that identifies the request and that allows failed
# `RegisterInstance` requests to be retried without the risk of
# executing the operation twice. You must use a unique
# `CreatorRequestId` string every time you submit a `RegisterInstance`
# request if you're registering additional instances for the same
# namespace and service. `CreatorRequestId` can be any unique string,
# for example, a date/time stamp.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @option params [required, Hash<String,String>] :attributes
# A string map that contains the following information for the service
# that you specify in `ServiceId`\:
#
# * The attributes that apply to the records that are defined in the
# service.
#
# * For each attribute, the applicable value.
#
# Supported attribute keys include the following:
#
# **AWS\_ALIAS\_DNS\_NAME**
#
# ****
#
# If you want Route 53 to create an alias record that routes traffic to
# an Elastic Load Balancing load balancer, specify the DNS name that is
# associated with the load balancer. For information about how to get
# the DNS name, see "DNSName" in the topic [AliasTarget][1].
#
# Note the following:
#
# * The configuration for the service that is specified by `ServiceId`
# must include settings for an A record, an AAAA record, or both.
#
# * In the service that is specified by `ServiceId`, the value of
# `RoutingPolicy` must be `WEIGHTED`.
#
# * If the service that is specified by `ServiceId` includes
# `HealthCheckConfig` settings, Route 53 will create the health check,
# but it won't associate the health check with the alias record.
#
# * Auto naming currently doesn't support creating alias records that
# route traffic to AWS resources other than ELB load balancers.
#
# * If you specify a value for `AWS_ALIAS_DNS_NAME`, don't specify
# values for any of the `AWS_INSTANCE` attributes.
#
# **AWS\_INSTANCE\_CNAME**
#
# If the service configuration includes a CNAME record, the domain name
# that you want Route 53 to return in response to DNS queries, for
# example, `example.com`.
#
# This value is required if the service specified by `ServiceId`
# includes settings for an CNAME record.
#
# **AWS\_INSTANCE\_IPV4**
#
# If the service configuration includes an A record, the IPv4 address
# that you want Route 53 to return in response to DNS queries, for
# example, `192.0.2.44`.
#
# This value is required if the service specified by `ServiceId`
# includes settings for an A record. If the service includes settings
# for an SRV record, you must specify a value for `AWS_INSTANCE_IPV4`,
# `AWS_INSTANCE_IPV6`, or both.
#
# **AWS\_INSTANCE\_IPV6**
#
# If the service configuration includes an AAAA record, the IPv6 address
# that you want Route 53 to return in response to DNS queries, for
# example, `2001:0db8:85a3:0000:0000:abcd:0001:2345`.
#
# This value is required if the service specified by `ServiceId`
# includes settings for an AAAA record. If the service includes settings
# for an SRV record, you must specify a value for `AWS_INSTANCE_IPV4`,
# `AWS_INSTANCE_IPV6`, or both.
#
# **AWS\_INSTANCE\_PORT**
#
# If the service includes an SRV record, the value that you want Route
# 53 to return for the port.
#
# If the service includes `HealthCheckConfig`, the port on the endpoint
# that you want Route 53 to send requests to.
#
# This value is required if you specified settings for an SRV record
# when you created the service.
#
#
#
# [1]: http://docs.aws.amazon.com/http:/docs.aws.amazon.com/Route53/latest/APIReference/API_AliasTarget.html
#
# @return [Types::RegisterInstanceResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::RegisterInstanceResponse#operation_id #operation_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.register_instance({
# service_id: "ResourceId", # required
# instance_id: "ResourceId", # required
# creator_request_id: "ResourceId",
# attributes: { # required
# "AttrKey" => "AttrValue",
# },
# })
#
# @example Response structure
#
# resp.operation_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/RegisterInstance AWS API Documentation
#
# @overload register_instance(params = {})
# @param [Hash] params ({})
def register_instance(params = {}, options = {})
req = build_request(:register_instance, params)
req.send_request(options)
end
# @option params [required, String] :service_id
#
# @option params [required, String] :instance_id
#
# @option params [required, String] :status
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.update_instance_custom_health_status({
# service_id: "ResourceId", # required
# instance_id: "ResourceId", # required
# status: "HEALTHY", # required, accepts HEALTHY, UNHEALTHY
# })
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/UpdateInstanceCustomHealthStatus AWS API Documentation
#
# @overload update_instance_custom_health_status(params = {})
# @param [Hash] params ({})
def update_instance_custom_health_status(params = {}, options = {})
req = build_request(:update_instance_custom_health_status, params)
req.send_request(options)
end
# Submits a request to perform the following operations:
#
# * Add or delete `DnsRecords` configurations
#
# * Update the TTL setting for existing `DnsRecords` configurations
#
# * Add, update, or delete `HealthCheckConfig` for a specified service
#
# You must specify all `DnsRecords` configurations (and, optionally,
# `HealthCheckConfig`) that you want to appear in the updated service.
# Any current configurations that don't appear in an `UpdateService`
# request are deleted.
#
# When you update the TTL setting for a service, Amazon Route 53 also
# updates the corresponding settings in all the records and health
# checks that were created by using the specified service.
#
# @option params [required, String] :id
# The ID of the service that you want to update.
#
# @option params [required, Types::ServiceChange] :service
# A complex type that contains the new settings for the service.
#
# @return [Types::UpdateServiceResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateServiceResponse#operation_id #operation_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.update_service({
# id: "ResourceId", # required
# service: { # required
# description: "ResourceDescription",
# dns_config: { # required
# dns_records: [ # required
# {
# type: "SRV", # required, accepts SRV, A, AAAA, CNAME
# ttl: 1, # required
# },
# ],
# },
# health_check_config: {
# type: "HTTP", # accepts HTTP, HTTPS, TCP
# resource_path: "ResourcePath",
# failure_threshold: 1,
# },
# },
# })
#
# @example Response structure
#
# resp.operation_id #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/UpdateService AWS API Documentation
#
# @overload update_service(params = {})
# @param [Hash] params ({})
def update_service(params = {}, options = {})
req = build_request(:update_service, params)
req.send_request(options)
end
# @!endgroup
# @param params ({})
# @api private
def build_request(operation_name, params = {})
handlers = @handlers.for(operation_name)
context = Seahorse::Client::RequestContext.new(
operation_name: operation_name,
operation: config.api.operation(operation_name),
client: self,
params: params,
config: config)
context[:gem_name] = 'aws-sdk-servicediscovery'
context[:gem_version] = '1.2.0'
Seahorse::Client::Request.new(handlers, context)
end
# @api private
# @deprecated
def waiter_names
[]
end
class << self
# @api private
attr_reader :identifier
# @api private
def errors_module
Errors
end
end
end
end
| 40.876701 | 152 | 0.656488 |
913f5a7bcf3c43ea4da3eb3be80a100a62c1cc8d | 4,003 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Issues Feed' do
describe 'GET /issues' do
let_it_be_with_reload(:user) do
user = create(:user, email: '[email protected]')
public_email = create(:email, :confirmed, user: user, email: '[email protected]')
user.update!(public_email: public_email.email)
user
end
let_it_be(:assignee) do
user = create(:user, email: '[email protected]')
public_email = create(:email, :confirmed, user: user, email: '[email protected]')
user.update!(public_email: public_email.email)
user
end
let_it_be(:group) { create(:group) }
let_it_be(:project) { create(:project) }
let_it_be(:issue) { create(:issue, author: user, assignees: [assignee], project: project, due_date: Date.today) }
let_it_be(:issuable) { issue } # "alias" for shared examples
before_all do
project.add_developer(user)
group.add_developer(user)
end
RSpec.shared_examples 'an authenticated issue atom feed' do
it 'renders atom feed with additional issue information' do
expect(body).to have_selector('title', text: "#{project.name} issues")
expect(body).to have_selector('due_date', text: issue.due_date)
end
end
context 'when authenticated' do
before do
sign_in user
visit project_issues_path(project, :atom)
end
it_behaves_like 'an authenticated issuable atom feed'
it_behaves_like 'an authenticated issue atom feed'
end
context 'when authenticated via personal access token' do
before do
personal_access_token = create(:personal_access_token, user: user)
visit project_issues_path(project, :atom,
private_token: personal_access_token.token)
end
it_behaves_like 'an authenticated issuable atom feed'
it_behaves_like 'an authenticated issue atom feed'
end
context 'when authenticated via feed token' do
before do
visit project_issues_path(project, :atom,
feed_token: user.feed_token)
end
it_behaves_like 'an authenticated issuable atom feed'
it_behaves_like 'an authenticated issue atom feed'
end
context 'when not authenticated' do
before do
visit project_issues_path(project, :atom)
end
context 'and the project is private' do
it 'redirects to login page' do
expect(page).to have_current_path(new_user_session_path)
end
end
context 'and the project is public' do
let_it_be(:project) { create(:project, :public) }
let_it_be(:issue) { create(:issue, author: user, assignees: [assignee], project: project, due_date: Date.today) }
let_it_be(:issuable) { issue } # "alias" for shared examples
it_behaves_like 'an authenticated issuable atom feed'
it_behaves_like 'an authenticated issue atom feed'
end
end
it "renders atom feed with url parameters for project issues" do
visit project_issues_path(project, :atom, feed_token: user.feed_token, state: 'opened', assignee_id: user.id)
link = find('link[type="application/atom+xml"]')
params = CGI.parse(URI.parse(link[:href]).query)
expect(params).to include('feed_token' => [user.feed_token])
expect(params).to include('state' => ['opened'])
expect(params).to include('assignee_id' => [user.id.to_s])
end
it "renders atom feed with url parameters for group issues" do
visit issues_group_path(group, :atom, feed_token: user.feed_token, state: 'opened', assignee_id: user.id)
link = find('link[type="application/atom+xml"]')
params = CGI.parse(URI.parse(link[:href]).query)
expect(params).to include('feed_token' => [user.feed_token])
expect(params).to include('state' => ['opened'])
expect(params).to include('assignee_id' => [user.id.to_s])
end
end
end
| 35.114035 | 121 | 0.664502 |
01368910a046865c56902048ef282dc721bfa252 | 460 | require 'rails_helper'
# Specs in this file have access to a helper object that includes
# the Stats::FtwitterHelper. For example:
#
# describe Stats::FtwitterHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# expect(helper.concat_strings("this","that")).to eq("this that")
# end
# end
# end
RSpec.describe Stats::FtwitterHelper, type: :helper do
pending "add some examples to (or delete) #{__FILE__}"
end
| 28.75 | 71 | 0.71087 |
6ae1337ee2f6d8b029edb398df303edb8c168cc0 | 13,310 | # frozen_string_literal: true
require 'rails_helper'
require Rails.root.join 'spec/models/concerns/assignment_handler_spec.rb'
require Rails.root.join 'spec/models/concerns/round_robin_handler_spec.rb'
RSpec.describe Conversation, type: :model do
describe 'associations' do
it { is_expected.to belong_to(:account) }
it { is_expected.to belong_to(:inbox) }
end
describe 'concerns' do
it_behaves_like 'assignment_handler'
it_behaves_like 'round_robin_handler'
end
describe '.before_create' do
let(:conversation) { build(:conversation, display_id: nil) }
before do
conversation.save
conversation.reload
end
it 'runs before_create callbacks' do
expect(conversation.display_id).to eq(1)
end
it 'creates a UUID for every conversation automatically' do
uuid_pattern = /[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}$/i
expect(conversation.uuid).to match(uuid_pattern)
end
end
describe '.after_create' do
let(:account) { create(:account) }
let(:agent) { create(:user, email: '[email protected]', account: account) }
let(:inbox) { create(:inbox, account: account) }
let(:conversation) do
create(
:conversation,
account: account,
contact: create(:contact, account: account),
inbox: inbox,
assignee: nil
)
end
before do
allow(Rails.configuration.dispatcher).to receive(:dispatch)
end
it 'runs after_create callbacks' do
# send_events
expect(Rails.configuration.dispatcher).to have_received(:dispatch)
.with(described_class::CONVERSATION_CREATED, kind_of(Time), conversation: conversation)
end
it 'queues AutoResolveConversationsJob post creation if auto resolve duration present' do
account.update(auto_resolve_duration: 30)
expect do
create(
:conversation,
account: account,
contact: create(:contact, account: account),
inbox: inbox,
assignee: nil
)
end.to have_enqueued_job(AutoResolveConversationsJob)
end
end
describe '.after_update' do
let(:account) { create(:account) }
let(:conversation) do
create(:conversation, status: 'open', account: account, assignee: old_assignee)
end
let(:old_assignee) do
create(:user, email: '[email protected]', account: account, role: :agent)
end
let(:new_assignee) do
create(:user, email: '[email protected]', account: account, role: :agent)
end
let(:assignment_mailer) { double(deliver: true) }
let(:label) { create(:label, account: account) }
before do
conversation
new_assignee
allow(Rails.configuration.dispatcher).to receive(:dispatch)
Current.user = old_assignee
conversation.update(
status: :resolved,
contact_last_seen_at: Time.now,
assignee: new_assignee,
label_list: [label.title]
)
end
it 'runs after_update callbacks' do
# notify_status_change
expect(Rails.configuration.dispatcher).to have_received(:dispatch)
.with(described_class::CONVERSATION_RESOLVED, kind_of(Time), conversation: conversation)
expect(Rails.configuration.dispatcher).to have_received(:dispatch)
.with(described_class::CONVERSATION_READ, kind_of(Time), conversation: conversation)
expect(Rails.configuration.dispatcher).to have_received(:dispatch)
.with(described_class::ASSIGNEE_CHANGED, kind_of(Time), conversation: conversation)
end
it 'creates conversation activities' do
# create_activity
expect(conversation.messages.pluck(:content)).to include("Conversation was marked resolved by #{old_assignee.name}")
expect(conversation.messages.pluck(:content)).to include("Assigned to #{new_assignee.name} by #{old_assignee.name}")
expect(conversation.messages.pluck(:content)).to include("#{old_assignee.name} added #{label.title}")
end
it 'adds a message for system auto resolution if marked resolved by system' do
account.update(auto_resolve_duration: 40)
conversation2 = create(:conversation, status: 'open', account: account, assignee: old_assignee)
Current.user = nil
conversation2.update(status: :resolved)
system_resolved_message = "Conversation was marked resolved by system due to #{account.auto_resolve_duration} days of inactivity"
expect(conversation2.messages.pluck(:content)).to include(system_resolved_message)
end
it 'does not trigger AutoResolutionJob if conversation reopened and account does not have auto resolve duration' do
expect { conversation.update(status: :open) }
.not_to have_enqueued_job(AutoResolveConversationsJob).with(conversation.id)
end
it 'does trigger AutoResolutionJob if conversation reopened and account has auto resolve duration' do
account.update(auto_resolve_duration: 40)
expect { conversation.reload.update(status: :open) }
.to have_enqueued_job(AutoResolveConversationsJob).with(conversation.id)
end
end
describe '#update_labels' do
let(:account) { create(:account) }
let(:conversation) { create(:conversation, account: account) }
let(:agent) do
create(:user, email: '[email protected]', account: account, role: :agent)
end
let(:first_label) { create(:label, account: account) }
let(:second_label) { create(:label, account: account) }
let(:third_label) { create(:label, account: account) }
let(:fourth_label) { create(:label, account: account) }
before do
conversation
Current.user = agent
first_label
second_label
third_label
fourth_label
end
it 'adds one label to conversation' do
labels = [first_label].map(&:title)
expect(conversation.update_labels(labels)).to eq(true)
expect(conversation.label_list).to match_array(labels)
expect(conversation.messages.pluck(:content)).to include("#{agent.name} added #{labels.join(', ')}")
end
it 'adds and removes previously added labels' do
labels = [first_label, fourth_label].map(&:title)
expect(conversation.update_labels(labels)).to eq(true)
expect(conversation.label_list).to match_array(labels)
expect(conversation.messages.pluck(:content)).to include("#{agent.name} added #{labels.join(', ')}")
updated_labels = [second_label, third_label].map(&:title)
expect(conversation.update_labels(updated_labels)).to eq(true)
expect(conversation.label_list).to match_array(updated_labels)
expect(conversation.messages.pluck(:content)).to include("#{agent.name} added #{updated_labels.join(', ')}")
expect(conversation.messages.pluck(:content)).to include("#{agent.name} removed #{labels.join(', ')}")
end
end
describe '#toggle_status' do
subject(:toggle_status) { conversation.toggle_status }
let(:conversation) { create(:conversation, status: :open) }
it 'toggles conversation status' do
expect(toggle_status).to eq(true)
expect(conversation.reload.status).to eq('resolved')
end
end
describe '#mute!' do
subject(:mute!) { conversation.mute! }
let(:user) do
create(:user, email: '[email protected]', account: create(:account), role: :agent)
end
let(:conversation) { create(:conversation) }
before { Current.user = user }
it 'marks conversation as resolved' do
mute!
expect(conversation.reload.resolved?).to eq(true)
end
it 'marks conversation as muted in redis' do
mute!
expect(Redis::Alfred.get(conversation.send(:mute_key))).not_to eq(nil)
end
it 'creates mute message' do
mute!
expect(conversation.messages.pluck(:content)).to include("#{user.name} has muted the conversation")
end
end
describe '#unmute!' do
subject(:unmute!) { conversation.unmute! }
let(:user) do
create(:user, email: '[email protected]', account: create(:account), role: :agent)
end
let(:conversation) { create(:conversation).tap(&:mute!) }
before { Current.user = user }
it 'does not change conversation status' do
expect { unmute! }.not_to(change { conversation.reload.status })
end
it 'marks conversation as muted in redis' do
expect { unmute! }
.to change { Redis::Alfred.get(conversation.send(:mute_key)) }
.to nil
end
it 'creates unmute message' do
unmute!
expect(conversation.messages.pluck(:content)).to include("#{user.name} has unmuted the conversation")
end
end
describe '#muted?' do
subject(:muted?) { conversation.muted? }
let(:conversation) { create(:conversation) }
it 'return true if conversation is muted' do
conversation.mute!
expect(muted?).to eq(true)
end
it 'returns false if conversation is not muted' do
expect(muted?).to eq(false)
end
end
describe 'unread_messages' do
subject(:unread_messages) { conversation.unread_messages }
let(:conversation) { create(:conversation, agent_last_seen_at: 1.hour.ago) }
let(:message_params) do
{
conversation: conversation,
account: conversation.account,
inbox: conversation.inbox,
sender: conversation.assignee
}
end
let!(:message) do
create(:message, created_at: 1.minute.ago, **message_params)
end
before do
create(:message, created_at: 1.month.ago, **message_params)
end
it 'returns unread messages' do
expect(unread_messages).to include(message)
end
end
describe 'unread_incoming_messages' do
subject(:unread_incoming_messages) { conversation.unread_incoming_messages }
let(:conversation) { create(:conversation, agent_last_seen_at: 1.hour.ago) }
let(:message_params) do
{
conversation: conversation,
account: conversation.account,
inbox: conversation.inbox,
sender: conversation.assignee,
created_at: 1.minute.ago
}
end
let!(:message) do
create(:message, message_type: :incoming, **message_params)
end
before do
create(:message, message_type: :outgoing, **message_params)
end
it 'returns unread incoming messages' do
expect(unread_incoming_messages).to contain_exactly(message)
end
end
describe '#push_event_data' do
subject(:push_event_data) { conversation.push_event_data }
let(:conversation) { create(:conversation) }
let(:expected_data) do
{
additional_attributes: {},
meta: {
sender: conversation.contact.push_event_data,
assignee: conversation.assignee
},
id: conversation.display_id,
messages: [],
inbox_id: conversation.inbox_id,
status: conversation.status,
contact_inbox: conversation.contact_inbox,
timestamp: conversation.last_activity_at.to_i,
can_reply: true,
channel: 'Channel::WebWidget',
contact_last_seen_at: conversation.contact_last_seen_at.to_i,
agent_last_seen_at: conversation.agent_last_seen_at.to_i,
unread_count: 0
}
end
it 'returns push event payload' do
expect(push_event_data).to eq(expected_data)
end
end
describe '#botinbox: when conversation created inside inbox with agent bot' do
let!(:bot_inbox) { create(:agent_bot_inbox) }
let(:conversation) { create(:conversation, inbox: bot_inbox.inbox) }
it 'returns conversation status as bot' do
expect(conversation.status).to eq('bot')
end
end
describe '#botintegration: when conversation created in inbox with dialogflow integration' do
let(:hook) { create(:integrations_hook, app_id: 'dialogflow') }
let(:conversation) { create(:conversation, inbox: hook.inbox) }
it 'returns conversation status as bot' do
expect(conversation.status).to eq('bot')
end
end
describe '#can_reply?' do
describe 'on channels without 24 hour restriction' do
let(:conversation) { create(:conversation) }
it 'returns true' do
expect(conversation.can_reply?).to eq true
end
end
describe 'on channels with 24 hour restriction' do
let!(:facebook_channel) { create(:channel_facebook_page) }
let!(:facebook_inbox) { create(:inbox, channel: facebook_channel, account: facebook_channel.account) }
let!(:conversation) { create(:conversation, inbox: facebook_inbox, account: facebook_channel.account) }
it 'returns false if there are no incoming messages' do
expect(conversation.can_reply?).to eq false
end
it 'return false if last incoming message is outside of 24 hour window' do
create(
:message,
account: conversation.account,
inbox: facebook_inbox,
conversation: conversation,
created_at: Time.now - 25.hours
)
expect(conversation.can_reply?).to eq false
end
it 'return true if last incoming message is inside 24 hour window' do
create(
:message,
account: conversation.account,
inbox: facebook_inbox,
conversation: conversation
)
expect(conversation.can_reply?).to eq true
end
end
end
end
| 33.027295 | 135 | 0.67731 |
ed41d8065be84db5b4748664f2371d45ab3a9af2 | 8,224 | require 'yaml'
require 'fileutils'
require UNITY_ROOT+'/auto/unity_test_summary'
require UNITY_ROOT+'/auto/generate_test_runner'
require UNITY_ROOT+'/auto/colour_reporter'
module RakefileHelpers
C_EXTENSION = '.c'
def load_configuration(config_file)
$cfg_file = config_file
$cfg = YAML.load(File.read($cfg_file))
end
def configure_clean
CLEAN.include($cfg['compiler']['build_path'] + '*.*') unless $cfg['compiler']['build_path'].nil?
end
def configure_toolchain(config_file=DEFAULT_CONFIG_FILE)
config_file += '.yml' unless config_file =~ /\.yml$/
load_configuration(config_file)
configure_clean
end
def get_unit_test_files
path = $cfg['compiler']['unit_tests_path'] + 'Test*' + C_EXTENSION
path.gsub!(/\\/, '/')
FileList.new(path)
end
def get_local_include_dirs
include_dirs = $cfg['compiler']['includes']['items'].dup
include_dirs.delete_if {|dir| dir.is_a?(Array)}
return include_dirs
end
def extract_headers(filename)
includes = []
lines = File.readlines(filename)
lines.each do |line|
m = line.match(/^\s*#include\s+\"\s*(.+\.[hH])\s*\"/)
if not m.nil?
includes << m[1]
end
end
return includes
end
def find_source_file(header, paths)
paths.each do |dir|
src_file = dir + header.ext(C_EXTENSION)
if (File.exists?(src_file))
return src_file
end
end
return nil
end
def tackit(strings)
if strings.is_a?(Array)
result = "\"#{strings.join}\""
else
result = strings
end
return result
end
def squash(prefix, items)
result = ''
items.each { |item| result += " #{prefix}#{tackit(item)}" }
return result
end
def build_compiler_fields
command = tackit($cfg['compiler']['path'])
if $cfg['compiler']['defines']['items'].nil?
defines = ''
else
defines = squash($cfg['compiler']['defines']['prefix'], $cfg['compiler']['defines']['items'])
end
options = squash('', $cfg['compiler']['options'])
includes = squash($cfg['compiler']['includes']['prefix'], $cfg['compiler']['includes']['items'])
includes = includes.gsub(/\\ /, ' ').gsub(/\\\"/, '"').gsub(/\\$/, '') # Remove trailing slashes (for IAR)
return {:command => command, :defines => defines, :options => options, :includes => includes}
end
def compile(file, defines=[])
compiler = build_compiler_fields
cmd_str = "#{compiler[:command]}#{compiler[:defines]}#{compiler[:options]}#{compiler[:includes]} #{file} " +
"#{$cfg['compiler']['object_files']['prefix']}#{$cfg['compiler']['object_files']['destination']}"
obj_file = "#{File.basename(file, C_EXTENSION)}#{$cfg['compiler']['object_files']['extension']}"
execute(cmd_str + obj_file)
return obj_file
end
def build_linker_fields
command = tackit($cfg['linker']['path'])
if $cfg['linker']['options'].nil?
options = ''
else
options = squash('', $cfg['linker']['options'])
end
if ($cfg['linker']['includes'].nil? || $cfg['linker']['includes']['items'].nil?)
includes = ''
else
includes = squash($cfg['linker']['includes']['prefix'], $cfg['linker']['includes']['items'])
end
includes = includes.gsub(/\\ /, ' ').gsub(/\\\"/, '"').gsub(/\\$/, '') # Remove trailing slashes (for IAR)
return {:command => command, :options => options, :includes => includes}
end
def link_it(exe_name, obj_list)
linker = build_linker_fields
cmd_str = "#{linker[:command]}#{linker[:options]}#{linker[:includes]} " +
(obj_list.map{|obj|"#{$cfg['linker']['object_files']['path']}#{obj} "}).join +
$cfg['linker']['bin_files']['prefix'] + ' ' +
$cfg['linker']['bin_files']['destination'] +
exe_name + $cfg['linker']['bin_files']['extension']
execute(cmd_str)
end
def build_simulator_fields
return nil if $cfg['simulator'].nil?
if $cfg['simulator']['path'].nil?
command = ''
else
command = (tackit($cfg['simulator']['path']) + ' ')
end
if $cfg['simulator']['pre_support'].nil?
pre_support = ''
else
pre_support = squash('', $cfg['simulator']['pre_support'])
end
if $cfg['simulator']['post_support'].nil?
post_support = ''
else
post_support = squash('', $cfg['simulator']['post_support'])
end
return {:command => command, :pre_support => pre_support, :post_support => post_support}
end
def execute(command_string, verbose=true, raise_on_fail=true)
report command_string
output = `#{command_string}`.chomp
report(output) if (verbose && !output.nil? && (output.length > 0))
if (($?.exitstatus != 0) and (raise_on_fail))
raise "Command failed. (Returned #{$?.exitstatus})"
end
return output
end
def report_summary
summary = UnityTestSummary.new
summary.set_root_path(HERE)
results_glob = "#{$cfg['compiler']['build_path']}*.test*"
results_glob.gsub!(/\\/, '/')
results = Dir[results_glob]
summary.set_targets(results)
summary.run
fail_out "FAIL: There were failures" if (summary.failures > 0)
end
def run_tests(test_files)
report 'Running system tests...'
# Tack on TEST define for compiling unit tests
load_configuration($cfg_file)
test_defines = ['TEST']
$cfg['compiler']['defines']['items'] = [] if $cfg['compiler']['defines']['items'].nil?
$cfg['compiler']['defines']['items'] << 'TEST'
include_dirs = get_local_include_dirs
# Build and execute each unit test
test_files.each do |test|
obj_list = []
# Detect dependencies and build required required modules
extract_headers(test).each do |header|
# Compile corresponding source file if it exists
src_file = find_source_file(header, include_dirs)
if !src_file.nil?
obj_list << compile(src_file, test_defines)
end
end
# Build the test runner (generate if configured to do so)
test_base = File.basename(test, C_EXTENSION)
runner_name = test_base + '_Runner.c'
if $cfg['compiler']['runner_path'].nil?
runner_path = $cfg['compiler']['build_path'] + runner_name
test_gen = UnityTestRunnerGenerator.new($cfg_file)
test_gen.run(test, runner_path)
else
runner_path = $cfg['compiler']['runner_path'] + runner_name
end
obj_list << compile(runner_path, test_defines)
# Build the test module
obj_list << compile(test, test_defines)
# Link the test executable
link_it(test_base, obj_list)
# Execute unit test and generate results file
simulator = build_simulator_fields
executable = $cfg['linker']['bin_files']['destination'] + test_base + $cfg['linker']['bin_files']['extension']
if simulator.nil?
cmd_str = executable
else
cmd_str = "#{simulator[:command]} #{simulator[:pre_support]} #{executable} #{simulator[:post_support]}"
end
output = execute(cmd_str, true, false)
test_results = $cfg['compiler']['build_path'] + test_base
if output.match(/OK$/m).nil?
test_results += '.testfail'
else
test_results += '.testpass'
end
File.open(test_results, 'w') { |f| f.print output }
end
end
def build_application(main)
report "Building application..."
obj_list = []
load_configuration($cfg_file)
main_path = $cfg['compiler']['source_path'] + main + C_EXTENSION
# Detect dependencies and build required required modules
include_dirs = get_local_include_dirs
extract_headers(main_path).each do |header|
src_file = find_source_file(header, include_dirs)
if !src_file.nil?
obj_list << compile(src_file)
end
end
# Build the main source file
main_base = File.basename(main_path, C_EXTENSION)
obj_list << compile(main_path)
# Create the executable
link_it(main_base, obj_list)
end
def fail_out(msg)
puts msg
puts "Not returning exit code so continuous integration can pass"
# exit(-1) # Only removed to pass example_3, which has failing tests on purpose.
# Still fail if the build fails for any other reason.
end
end
| 31.752896 | 116 | 0.631688 |
e988b8f2b2964a653157bb558e1b95a2b4e0c2b8 | 2,637 | class Unbound < Formula
desc "Validating, recursive, caching DNS resolver"
homepage "https://www.unbound.net"
url "https://nlnetlabs.nl/downloads/unbound/unbound-1.10.0.tar.gz"
sha256 "152f486578242fe5c36e89995d0440b78d64c05123990aae16246b7f776ce955"
head "https://github.com/NLnetLabs/unbound.git"
bottle do
sha256 "d2d4d6d362feaafc5d10ea48abff32048527fd1c0fad152311354d58842cda5e" => :catalina
sha256 "f7373d641329d32e1a7cb94193691d9077e1932a73621f4b0f049e77cef670d2" => :mojave
sha256 "5bda37df0865426a3d254d2dcc27576bd009feddbb6609eba0e98c8dfbd480fb" => :high_sierra
sha256 "8f030ea8d0ad68451b87f663fbcc8249fa41faa728cb70f61139011e5936d362" => :x86_64_linux
end
depends_on "libevent"
depends_on "[email protected]"
uses_from_macos "expat"
def install
args = %W[
--prefix=#{prefix}
--sysconfdir=#{etc}
--enable-event-api
--enable-tfo-client
--enable-tfo-server
--with-libevent=#{Formula["libevent"].opt_prefix}
--with-ssl=#{Formula["[email protected]"].opt_prefix}
]
if OS.mac?
args << "--with-libexpat=#{MacOS.sdk_path}/usr" if MacOS.sdk_path_if_needed
else
args << "--with-libexpat=#{Formula["expat"].prefix}"
end
system "./configure", *args
inreplace "doc/example.conf", 'username: "unbound"', 'username: "@@HOMEBREW-UNBOUND-USER@@"'
system "make"
system "make", "install"
end
def post_install
conf = etc/"unbound/unbound.conf"
return unless conf.exist?
return unless conf.read.include?('username: "@@HOMEBREW-UNBOUND-USER@@"')
inreplace conf, 'username: "@@HOMEBREW-UNBOUND-USER@@"',
"username: \"#{ENV["USER"]}\""
end
plist_options :startup => true
def plist; <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>#{plist_name}</string>
<key>KeepAlive</key>
<true/>
<key>RunAtLoad</key>
<true/>
<key>ProgramArguments</key>
<array>
<string>#{opt_sbin}/unbound</string>
<string>-d</string>
<string>-c</string>
<string>#{etc}/unbound/unbound.conf</string>
</array>
<key>UserName</key>
<string>root</string>
<key>StandardErrorPath</key>
<string>/dev/null</string>
<key>StandardOutPath</key>
<string>/dev/null</string>
</dict>
</plist>
EOS
end
test do
system sbin/"unbound-control-setup", "-d", testpath
end
end
| 30.310345 | 106 | 0.640501 |
e26ee6fc48d8cdaed4fa53d2af8d0a0f7d61f217 | 393 | require "test_helper"
class TimeEntryTest < ActiveSupport::TestCase
setup do
@entry = time_entries(:one)
@entry_two = time_entries(:two)
end
test "real_duration works for running entries" do
@entry_two.update!(start_time: Time.new(2018, 3, 17, 20), running: true)
travel_to Time.new(2018, 3, 17, 21) do
assert_equal 60, @entry_two.real_duration
end
end
end
| 24.5625 | 76 | 0.70229 |
d5f40a0494737fc52ac574271a0b03562b48cb21 | 449 | module Zuora::Objects
class ProductRatePlan < Base
belongs_to :product
has_many :product_rate_plan_charges
validates_length_of :description, :maximum => 500, :allow_nil => true
validates_datetime_of :effective_start_date, :effective_end_date
validates_length_of :name, :maximum => 100, :allow_nil => true
define_attributes do
read_only :updated_by_id, :updated_date, :created_by_id, :created_date
end
end
end
| 29.933333 | 76 | 0.750557 |
087e8d01f5af947e608125b90ec98c6e0cdfca45 | 1,256 | cask 'xbox360-controller-driver' do
version '0.16.1'
sha256 '676ace81cd91da316433eae915c4755941864ee0ea20f331ed4c1fd952385fee'
url "https://github.com/360Controller/360Controller/releases/download/v#{version}/360ControllerInstall_#{version}.dmg"
appcast 'https://github.com/360Controller/360Controller/releases.atom',
checkpoint: '9aab5799b0f3b8983fa65f31c89326549a342f47b00421c0d0738351b6e217ad'
name 'TattieBogle Xbox 360 Controller Driver (with improvements)'
homepage 'https://github.com/360Controller/360Controller'
license :gpl
pkg 'Install360Controller.pkg'
uninstall pkgutil: 'com.mice.pkg.Xbox360controller',
launchctl: 'com.mice.360Daemon',
kext: [
'com.mice.Xbox360ControllerForceFeedback',
'com.mice.driver.Xbox360Controller',
'com.mice.driver.Wireless360Controller',
'com.mice.driver.WirelessGamingReceiver',
],
# Symlink to kext in /Library/Extensions is not removed
# during :pkgutil phase of uninstall, so we delete it here.
delete: '/System/Library/Extensions/360Controller.kext'
caveats do
reboot
end
end
| 41.866667 | 120 | 0.671178 |
bf80076203fc95618ac8d2273dfa3f9f9c1bbb90 | 6,693 | =begin
#Selling Partner API for Authorization
#The Selling Partner API for Authorization helps developers manage authorizations and check the specific permissions associated with a given authorization.
OpenAPI spec version: v1
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 3.0.26
=end
require 'date'
module AmzSpApi::AuthorizationApiModel
# A Login with Amazon (LWA) authorization code.
class AuthorizationCode
# A Login with Amazon (LWA) authorization code that can be exchanged for a refresh token and access token that authorize you to make calls to a Selling Partner API.
attr_accessor :authorization_code
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'authorization_code' => :'authorizationCode'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'authorization_code' => :'Object'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `AmzSpApi::AuthorizationApiModel::AuthorizationCode` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `AmzSpApi::AuthorizationApiModel::AuthorizationCode`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'authorization_code')
self.authorization_code = attributes[:'authorization_code']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
authorization_code == o.authorization_code
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[authorization_code].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
elsif attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
end
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :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 =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
AmzSpApi::AuthorizationApiModel.const_get(type).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)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end end
end
| 32.023923 | 228 | 0.641865 |
281615caf7ce9b58afe68b93345b282630798fbd | 1,637 | $LOAD_PATH.unshift 'lib'
require 'resque/plugins/meta/version'
Gem::Specification.new do |s|
s.name = "resque-meta"
s.version = Resque::Plugins::Meta::Version
s.date = Time.now.strftime('%Y-%m-%d')
s.summary = "A Resque plugin for storing job metadata."
s.homepage = "http://github.com/lmarlow/resque-meta"
s.email = "[email protected]"
s.authors = [ "Lee Marlow" ]
s.has_rdoc = false
s.files = %w( README.md Rakefile LICENSE )
s.files += Dir.glob("lib/**/*")
s.files += Dir.glob("test/**/*")
s.description = <<desc
A Resque plugin. If you want to be able to add metadata for a job
to track anything you want, extend it with this module.
For example:
require 'resque-meta'
class MyJob
extend Resque::Plugins::Meta
def self.perform(meta_id, *args)
heavy_lifting
end
end
meta0 = MyJob.enqueue('stuff')
meta0.enqueued_at # => 'Wed May 19 13:42:41 -0600 2010'
meta0.meta_id # => '03c9e1a045ad012dd20500264a19273c'
meta0['foo'] = 'bar' # => 'bar'
meta0.save
# later
meta1 = MyJob.get_meta('03c9e1a045ad012dd20500264a19273c')
meta1.job_class # => MyJob
meta1.enqueued_at # => 'Wed May 19 13:42:41 -0600 2010'
meta1['foo'] # => 'bar'
desc
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
s.add_runtime_dependency('resque', ["~> 1.8"])
else
s.add_dependency('resque', ["~> 1.8"])
end
end
| 29.232143 | 71 | 0.606597 |
7ad0787b642edbe2b5aee3a4b42fa7861f301985 | 132 | require File.dirname(__FILE__) + '/spec_helper'
describe "jabbit" do
it "should do nothing" do
true.should == true
end
end
| 16.5 | 47 | 0.69697 |
abb4a859584a7d1aa8cfe04120fa4f634a3bb664 | 2,919 | class Gjs < Formula
desc "JavaScript Bindings for GNOME"
homepage "https://wiki.gnome.org/Projects/Gjs"
url "https://download.gnome.org/sources/gjs/1.50/gjs-1.50.4.tar.xz"
sha256 "b336e8709347e3c94245f6cbc3465f9a49f3ae491a25f49f8a97268f5235b93a"
bottle do
sha256 "1ae796e16241d6279b1e544a6764849a18b34a8e606538163705468be9abcfcb" => :high_sierra
sha256 "08cc80f957768dff4345b5cc2cb4ddc582c3f91b650725f2843e1c4ebc9833d4" => :sierra
sha256 "a64eae5f4566c1d1f9e75841b7a4799a8bc83af8df322f825c1c7dbeabe0077d" => :el_capitan
end
depends_on "pkg-config" => :build
depends_on "[email protected]" => :build
depends_on "gobject-introspection"
depends_on "nspr"
depends_on "readline"
depends_on "gtk+3" => :recommended
needs :cxx11
resource "mozjs52" do
url "https://archive.mozilla.org/pub/firefox/releases/52.3.0esr/source/firefox-52.3.0esr.source.tar.xz"
sha256 "c16bc86d6cb8c2199ed1435ab80a9ae65f9324c820ea0eeb38bf89a97d253b5b"
end
def install
ENV.cxx11
ENV["_MACOSX_DEPLOYMENT_TARGET"] = ENV["MACOSX_DEPLOYMENT_TARGET"]
resource("mozjs52").stage do
inreplace "config/rules.mk", "-install_name $(_LOADER_PATH)/$(SHARED_LIBRARY) ", "-install_name #{lib}/$(SHARED_LIBRARY) "
inreplace "old-configure", "-Wl,-executable_path,${DIST}/bin", ""
mkdir("build") do
ENV["PYTHON"] = "python"
system "../js/src/configure", "--prefix=#{prefix}",
"--with-system-nspr",
"--with-system-zlib",
"--with-system-icu",
"--enable-readline",
"--enable-shared-js",
"--with-pthreads",
"--enable-optimize",
"--enable-pie",
"--enable-release",
"--without-intl-api"
system "make"
system "make", "install"
lib.install "./mozglue/build/libmozglue.dylib"
rm Dir["#{bin}/*"]
end
# headers were installed as softlinks, which is not acceptable
cd(include.to_s) do
`find . -type l`.chomp.split.each do |link|
header = File.readlink(link)
rm link
cp header, link
end
end
ENV.append_path "PKG_CONFIG_PATH", "#{lib}/pkgconfig"
# remove mozjs static lib
rm "#{lib}/libjs_static.ajs"
end
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--disable-silent-rules",
"--without-dbus-tests",
"--prefix=#{prefix}"
system "make", "install"
end
test do
(testpath/"test.js").write <<~EOS
#!/usr/bin/env gjs
const GLib = imports.gi.GLib;
EOS
system "#{bin}/gjs", "test.js"
end
end
| 36.037037 | 128 | 0.579651 |
1c53cbdeb80caf2bad166cd4a39f400a93915ea2 | 964 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v9/services/combined_audience_service.proto
require 'google/ads/google_ads/v9/resources/combined_audience_pb'
require 'google/api/annotations_pb'
require 'google/api/client_pb'
require 'google/api/field_behavior_pb'
require 'google/api/resource_pb'
require 'google/protobuf'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/ads/googleads/v9/services/combined_audience_service.proto", :syntax => :proto3) do
add_message "google.ads.googleads.v9.services.GetCombinedAudienceRequest" do
optional :resource_name, :string, 1
end
end
end
module Google
module Ads
module GoogleAds
module V9
module Services
GetCombinedAudienceRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v9.services.GetCombinedAudienceRequest").msgclass
end
end
end
end
end
| 32.133333 | 167 | 0.771784 |
e2a0cbbf65ecd57406c28eb403ec023752178441 | 175 | # frozen_string_literal: true
require 'coverage'
Coverage.start(branches: true)
load '/gem/spec/fixtures/sample.rb'
foo = Foo.new
foo.bar
foo.foo(false)
puts Coverage.result
| 17.5 | 35 | 0.777143 |
21fe379f6f23adebe0bdba140e7e81943fbcef68 | 2,994 | require 'concurrent'
module Hanami
module Model
# Default Error class
#
# @since 0.5.1
class Error < ::StandardError
# @api private
# @since 0.7.0
@__mapping__ = Concurrent::Map.new
# @api private
# @since 0.7.0
def self.for(exception)
mapping.fetch(exception.class, self).new(exception)
end
# @api private
# @since 0.7.0
def self.register(external, internal)
mapping.put_if_absent(external, internal)
end
# @api private
# @since 0.7.0
def self.mapping
@__mapping__
end
end
# Generic database error
#
# @since 0.7.0
class DatabaseError < Error
end
# Error for invalid raw command syntax
#
# @since 0.5.0
class InvalidCommandError < Error
# @since 0.5.0
# @api private
def initialize(message = 'Invalid command')
super
end
end
# Error for Constraint Violation
#
# @since 0.7.0
class ConstraintViolationError < Error
# @since 0.7.0
# @api private
def initialize(message = 'Constraint has been violated')
super
end
end
# Error for Unique Constraint Violation
#
# @since 0.6.1
class UniqueConstraintViolationError < ConstraintViolationError
# @since 0.6.1
# @api private
def initialize(message = 'Unique constraint has been violated')
super
end
end
# Error for Foreign Key Constraint Violation
#
# @since 0.6.1
class ForeignKeyConstraintViolationError < ConstraintViolationError
# @since 0.6.1
# @api private
def initialize(message = 'Foreign key constraint has been violated')
super
end
end
# Error for Not Null Constraint Violation
#
# @since 0.6.1
class NotNullConstraintViolationError < ConstraintViolationError
# @since 0.6.1
# @api private
def initialize(message = 'NOT NULL constraint has been violated')
super
end
end
# Error for Check Constraint Violation raised by Sequel
#
# @since 0.6.1
class CheckConstraintViolationError < ConstraintViolationError
# @since 0.6.1
# @api private
def initialize(message = 'Check constraint has been violated')
super
end
end
# Unknown database type error for repository auto-mapping
#
# @since 1.0.0
class UnknownDatabaseTypeError < Error
end
# Unknown primary key error
#
# @since 1.0.0
class MissingPrimaryKeyError < Error
end
# Unknown attribute error
#
# @since 1.2.0
class UnknownAttributeError < Error
end
# Unknown database adapter error
#
# @since 1.2.1
class UnknownDatabaseAdapterError < Error
def initialize(url)
super("Unknown database adapter for URL: #{url.inspect}. Please check your database configuration (hint: ENV['DATABASE_URL']).")
end
end
end
end
| 22.681818 | 136 | 0.616232 |
33130aa05b4d4ede9cf59de0e981f85829e52f9a | 1,073 | cask 'telegram' do
version '6.1.2.197946'
sha256 '8b91afceaa381146fee9a0b9dd37972bacd51cbdc71d9e126efd595c965b1256'
url "https://osx.telegram.org/updates/Telegram-#{version}.app.zip"
appcast 'https://osx.telegram.org/updates/versions.xml'
name 'Telegram for macOS'
homepage 'https://macos.telegram.org/'
auto_updates true
depends_on macos: '>= :el_capitan'
app 'Telegram.app'
zap trash: [
'~/Library/Application Scripts/ru.keepcoder.Telegram',
'~/Library/Application Scripts/ru.keepcoder.Telegram.TelegramShare',
'~/Library/Caches/ru.keepcoder.Telegram',
'~/Library/Containers/ru.keepcoder.Telegram',
'~/Library/Containers/ru.keepcoder.Telegram.TelegramShare',
'~/Library/Cookies/ru.keepcoder.Telegram.binarycookies',
'~/Library/Group Containers/*.ru.keepcoder.Telegram',
'~/Library/Preferences/ru.keepcoder.Telegram.plist',
'~/Library/Saved Application State/ru.keepcoder.Telegram.savedState',
]
end
| 39.740741 | 84 | 0.664492 |
d52a80c97e604cf44b21dfe84efd8ca425becc6c | 970 | # frozen_string_literal: true
module ActionText
# The RichText record holds the content produced by the Trix editor in a serialized +body+ attribute.
# It also holds all the references to the embedded files, which are stored using Active Storage.
# This record is then associated with the Active Record model the application desires to have
# rich text content using the +has_rich_text+ class method.
class RichText < Record
self.table_name = "action_text_rich_texts"
serialize :body, ActionText::Content
delegate :to_s, :nil?, to: :body
belongs_to :record, polymorphic: true, touch: true
has_many_attached :embeds
before_save do
self.embeds = body.attachables.grep(ActiveStorage::Blob).uniq if body.present?
end
def to_plain_text
body&.to_plain_text.to_s
end
delegate :blank?, :empty?, :present?, to: :to_plain_text
end
end
ActiveSupport.run_load_hooks :action_text_rich_text, ActionText::RichText
| 32.333333 | 103 | 0.745361 |
7a463bd4497c8860be147bda139604c9cc83397d | 1,818 | class ChinadnsC < Formula
desc "Port of ChinaDNS to C: fix irregularities with DNS in China"
homepage "https://github.com/shadowsocks/ChinaDNS"
url "https://github.com/shadowsocks/ChinaDNS/releases/download/1.3.2/chinadns-1.3.2.tar.gz"
sha256 "abfd433e98ac0f31b8a4bd725d369795181b0b6e8d1b29142f1bb3b73bbc7230"
license "GPL-3.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "8a5921a1eb32cce03417035e20ed9fc3c52569bbe3cc963f4a5d8dacd8a61bd4"
sha256 cellar: :any_skip_relocation, big_sur: "d15cde6788156aa67dffd280752d52f5aac1ef1e8f56c8e5864ce05b9c81647a"
sha256 cellar: :any_skip_relocation, catalina: "0c4820f0e5a12421b0e64c3cb993608560817a446b8747e7119838cb271b9044"
sha256 cellar: :any_skip_relocation, mojave: "61ccebe523d9e2417385c911beca6a01ee7d2810f1a665fca9a4f6a0e7b81623"
sha256 cellar: :any_skip_relocation, high_sierra: "5b0b51abe8a40dee4b1296e81da179aff05ba42befc869e06e081d7e6fc4e726"
sha256 cellar: :any_skip_relocation, sierra: "fa51351f3cdfb63fa672d2011c08ac8a1f9a260bcfaacb13e4657f39e721b96f"
sha256 cellar: :any_skip_relocation, el_capitan: "a620bce8421a9773233c51886c6845995569a1fda80e252efa86f6271c1d274c"
sha256 cellar: :any_skip_relocation, yosemite: "329351a4f82e4f871cbc2b384902b0c84040bd1df222970d67be7513bbead207"
sha256 cellar: :any_skip_relocation, x86_64_linux: "0ae6ba84c62433d9152027bd8ba7ed3d463db892624f07ec38955f5a986d080b" # linuxbrew-core
end
head do
url "https://github.com/shadowsocks/ChinaDNS.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
end
def install
system "./autogen.sh" if build.head?
system "./configure", "--prefix=#{prefix}"
system "make", "install"
end
test do
system "#{bin}/chinadns", "-h"
end
end
| 50.5 | 139 | 0.788779 |
5d48e0e06eabc1d405e5e2dc0ff5a99e0368be79 | 718 | require 'id_generator'
module Kaiju
class InvitationFactory
def self.new_project_invitation(project_id, inviter_id)
invitation = new_invitation(inviter_id)
invitation.project_id = project_id
invitation
end
def self.new_workspace_invitation(project_id, workspace_id, inviter_id)
invitation = new_project_invitation(project_id, inviter_id)
invitation.workspace_id = workspace_id
invitation
end
def self.new_invitation(inviter_id)
invitation = Invitation.new(IdGenerator.generate_id)
invitation.creation_date_time = Time.now.iso8601_precise
invitation.inviter_id = inviter_id
invitation.expire(1.day)
invitation
end
end
end
| 27.615385 | 75 | 0.745125 |
1833778d3482edd068efcfdcb7f2bc32529ed1a5 | 3,517 | # frozen_string_literal: true
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
if ENV['COVERAGE']
require 'simplecov'
require 'codeclimate-test-reporter'
SimpleCov.start('rails') do
add_filter '/spec'
add_filter '/.internal_test_app'
end
SimpleCov.command_name 'spec'
end
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../.internal_test_app/config/environment', __FILE__)
# Prevent database truncation if the environment is production
# abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
# Load EngineCart's test application.
require 'engine_cart'
EngineCart.load_application!
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
Dir[Hyrax::BatchIngest.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
ActiveRecord::Migrator.migrations_paths = File.expand_path('../../.internal_test_app/db/migrate')
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
ActiveJob::Base.queue_adapter = :test
RSpec.configure do |config|
# Define the fixture_path directory
config.fixture_path = "#{Hyrax::BatchIngest.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
# For feature specs, include BatchIngest url helpers.
# NOTE: for controller specs, put the following in the spec's describe block:
# routes { Hyrax::BatchIngest::Engine.routes }
config.include Hyrax::BatchIngest::Engine.routes.url_helpers, type: :feature
end
| 39.516854 | 99 | 0.750924 |
1cbb22a8592af26d5f4a0359f13c1a11bf878daa | 16,507 | #
# Install/distribution utility functions
# $Id: utils.rb,v 1.5 2004/01/18 19:15:18 deveiant Exp $
#
# Copyright (c) 2001-2004, The FaerieMUD Consortium.
#
# This is free software. You may use, modify, and/or redistribute this
# software under the terms of the Perl Artistic License. (See
# http://language.perl.com/misc/Artistic.html)
#
BEGIN {
require 'find'
begin
require 'readline'
include Readline
rescue LoadError => e
$stderr.puts "Faking readline..."
def readline( prompt )
$stderr.print prompt.chomp
return $stdin.gets.chomp
end
end
}
class File
Win32Exts = %w{.exe .com .bat}
def self::which( prog, path=ENV['PATH'] )
path.split(File::PATH_SEPARATOR).each {|dir|
# If running under Windows, look for prog + extensions
if File::ALT_SEPARATOR
ext = Win32Exts.find_all {|ext|
f = File::join(dir, prog+ext)
File::executable?(f) && !File::directory?(f)
}
ext.each {|f|
f = File::join( dir, prog + f ).gsub(%r:/:,'\\')
if block_given? then yield( f ) else return f end
}
else
f = File::join( dir, prog )
if File::executable?( f ) && ! File::directory?( f )
if block_given? then yield(f) else return f end
end
end
}
end
end
module UtilityFunctions
# The list of regexen that eliminate files from the MANIFEST
ANTIMANIFEST = [
/makedist\.rb/,
/\bCVS\b/,
/~$/,
/^#/,
%r{docs/html},
%r{docs/man},
/\bTEMPLATE\.\w+\.tpl\b/,
/\.cvsignore/,
/\.s?o$/,
]
AMRegexp = Regexp::union( *ANTIMANIFEST )
# Set some ANSI escape code constants (Shamelessly stolen from Perl's
# Term::ANSIColor by Russ Allbery <[email protected]> and Zenin <[email protected]>
AnsiAttributes = {
'clear' => 0,
'reset' => 0,
'bold' => 1,
'dark' => 2,
'underline' => 4,
'underscore' => 4,
'blink' => 5,
'reverse' => 7,
'concealed' => 8,
'black' => 30, 'on_black' => 40,
'red' => 31, 'on_red' => 41,
'green' => 32, 'on_green' => 42,
'yellow' => 33, 'on_yellow' => 43,
'blue' => 34, 'on_blue' => 44,
'magenta' => 35, 'on_magenta' => 45,
'cyan' => 36, 'on_cyan' => 46,
'white' => 37, 'on_white' => 47
}
ErasePreviousLine = "\033[A\033[K"
###############
module_function
###############
# Create a string that contains the ANSI codes specified and return it
def ansiCode( *attributes )
return '' unless /(?:vt10[03]|xterm(?:-color)?|linux)/i =~ ENV['TERM']
attr = attributes.collect {|a| AnsiAttributes[a] ? AnsiAttributes[a] : nil}.compact.join(';')
if attr.empty?
return ''
else
return "\e[%sm" % attr
end
end
# Test for the presence of the specified <tt>library</tt>, and output a
# message describing the test using <tt>nicename</tt>. If <tt>nicename</tt>
# is <tt>nil</tt>, the value in <tt>library</tt> is used to build a default.
def testForLibrary( library, nicename=nil )
nicename ||= library
message( "Testing for the #{nicename} library..." )
found = false
begin
require library
rescue LoadError => err
message "no found (%s)\n" % err.message
else
message "found\n"
found = true
end
return found
end
# Test for the presence of the specified <tt>library</tt>, and output a
# message describing the problem using <tt>nicename</tt>. If
# <tt>nicename</tt> is <tt>nil</tt>, the value in <tt>library</tt> is used
# to build a default. If <tt>raaUrl</tt> and/or <tt>downloadUrl</tt> are
# specified, they are also use to build a message describing how to find the
# required library. If <tt>fatal</tt> is <tt>true</tt>, a missing library
# will cause the program to abort.
def testForRequiredLibrary( library, nicename=nil, raaUrl=nil, downloadUrl=nil, fatal=true )
nicename ||= library
unless testForLibrary( library, nicename )
msgs = [ "You are missing the required #{nicename} library.\n" ]
msgs << "RAA: #{raaUrl}\n" if raaUrl
msgs << "Download: #{downloadUrl}\n" if downloadUrl
if fatal
abort msgs.join('')
else
errorMessage msgs.join('')
end
end
return true
end
### Output <tt>msg</tt> as a ANSI-colored program/section header (white on
### blue).
def header( msg )
msg.chomp!
$stderr.puts ansiCode( 'bold', 'white', 'on_blue' ) + msg + ansiCode( 'reset' )
$stderr.flush
end
### Output <tt>msg</tt> to STDERR and flush it.
def message( msg )
$stderr.print ansiCode( 'cyan' ) + msg + ansiCode( 'reset' )
$stderr.flush
end
### Output the specified <tt>msg</tt> as an ANSI-colored error message
### (white on red).
def errorMessage( msg )
message ansiCode( 'bold', 'white', 'on_red' ) + msg + ansiCode( 'reset' )
end
### Output the specified <tt>msg</tt> as an ANSI-colored debugging message
### (yellow on blue).
def debugMsg( msg )
return unless $DEBUG
msg.chomp!
$stderr.puts ansiCode( 'bold', 'yellow', 'on_blue' ) + ">>> #{msg}" + ansiCode( 'reset' )
$stderr.flush
end
### Erase the previous line (if supported by your terminal) and output the
### specified <tt>msg</tt> instead.
def replaceMessage( msg )
print ErasePreviousLine
message( msg )
end
### Output a divider made up of <tt>length</tt> hyphen characters.
def divider( length=75 )
puts "\r" + ("-" * length )
end
alias :writeLine :divider
### Output the specified <tt>msg</tt> colored in ANSI red and exit with a
### status of 1.
def abort( msg )
print ansiCode( 'bold', 'red' ) + "Aborted: " + msg.chomp + ansiCode( 'reset' ) + "\n\n"
Kernel.exit!( 1 )
end
### Output the specified <tt>promptString</tt> as a prompt (in green) and
### return the user's input with leading and trailing spaces removed.
def prompt( promptString )
promptString.chomp!
return readline( ansiCode('bold', 'green') + "#{promptString}: " + ansiCode('reset') ).strip
end
### Prompt the user with the given <tt>promptString</tt> via #prompt,
### substituting the given <tt>default</tt> if the user doesn't input
### anything.
def promptWithDefault( promptString, default )
response = prompt( "%s [%s]" % [ promptString, default ] )
if response.empty?
return default
else
return response
end
end
### Search for the program specified by the given <tt>progname</tt> in the
### user's <tt>PATH</tt>, and return the full path to it, or <tt>nil</tt> if
### no such program is in the path.
def findProgram( progname )
ENV['PATH'].split(File::PATH_SEPARATOR).each {|d|
file = File.join( d, progname )
return file if File.executable?( file )
}
return nil
end
### Using the CVS log for the given <tt>file</tt> attempt to guess what the
### next release version might be. This only works if releases are tagged
### with tags like 'RELEASE_x_y'.
def extractNextVersionFromTags( file )
message "Attempting to extract next release version from CVS tags for #{file}...\n"
raise RuntimeError, "No such file '#{file}'" unless File.exists?( file )
cvsPath = findProgram( 'cvs' ) or
raise RuntimeError, "Cannot find the 'cvs' program. Aborting."
output = %x{#{cvsPath} log #{file}}
release = [ 0, 0 ]
output.scan( /RELEASE_(\d+)_(\d+)/ ) {|match|
if $1.to_i > release[0] || $2.to_i > release[1]
release = [ $1.to_i, $2.to_i ]
replaceMessage( "Found %d.%02d...\n" % release )
end
}
if release[1] >= 99
release[0] += 1
release[1] = 1
else
release[1] += 1
end
return "%d.%02d" % release
end
### Write a new manifest file with the given +named+, moving any current one
### aside with an ".old" suffix if +backup+ is true.
def makeManifest( name="MANIFEST", backup=true )
message "Making manifest file '#{name}'"
# Move an old one aside if a backup is desired
if backup and File::exists?( name )
File::rename( name, name + ".old" )
end
File::open( name, File::WRONLY|File::TRUNC|File::CREAT ) {|ofh|
Find::find( "." ) do |file|
Find.prune if AMRegexp =~ file
Find.prune if %r{/\.} =~ file
Find.prune if /TEMPLATE/ =~ file
next if File::directory?( file )
ofh.puts file
end
}
end
### Read the specified <tt>manifestFile</tt>, which is a text file
### describing which files to package up for a distribution. The manifest
### should consist of one or more lines, each containing one filename or
### shell glob pattern.
def readManifest( manifestFile="MANIFEST" )
message "Reading manifest..."
raise "Missing #{manifestFile}, please remake it" unless File.exists? manifestFile
manifest = IO::readlines( manifestFile ).collect {|line|
line.chomp
}.select {|line|
line !~ /^(\s*(#.*)?)?$/
}
filelist = []
for pat in manifest
$stderr.puts "Adding files that match '#{pat}' to the file list" if $VERBOSE
filelist |= Dir.glob( pat ).find_all {|f| FileTest.file?(f)}
end
message "found #{filelist.length} files.\n"
return filelist
end
### Given a <tt>filelist</tt> like that returned by #readManifest, remove
### the entries therein which match the Regexp objects in the given
### <tt>antimanifest</tt> and return the resultant Array.
def vetManifest( filelist, antimanifest=ANITMANIFEST )
origLength = filelist.length
message "Vetting manifest..."
for regex in antimanifest
if $VERBOSE
message "\n\tPattern /#{regex.source}/ removed: " +
filelist.find_all {|file| regex.match(file)}.join(', ')
end
filelist.delete_if {|file| regex.match(file)}
end
message "removed #{origLength - filelist.length} files from the list.\n"
return filelist
end
### Combine a call to #readManifest with one to #vetManifest.
def getVettedManifest( manifestFile="MANIFEST", antimanifest=ANTIMANIFEST )
vetManifest( readManifest(manifestFile), antimanifest )
end
### Given a documentation <tt>catalogFile</tt>, extract the title, if
### available, and return it. Otherwise generate a title from the name of
### the CVS module.
def findRdocTitle( catalogFile="docs/CATALOG" )
# Try extracting it from the CATALOG file from a line that looks like:
# Title: Foo Bar Module
title = findCatalogKeyword( 'title', catalogFile )
# If that doesn't work for some reason, try grabbing the name of the CVS
# repository the directory belongs to.
if title.nil? && File::directory?( "CVS" ) &&
File::exists?( "CVS/Repository" )
title = File::read( "CVS/Repository" ).chomp
end
# As a last resort, use the name of the project directory
if title.nil?
distdir = File::dirname( __FILE__ )
distdir = File::dirname( distdir ) if /docs$/ =~ distdir
title = File::basename( distdir )
end
return title
end
### Given a documentation <tt>catalogFile</tt>, extract the name of the file
### to use as the initally displayed page. If extraction fails, the
### +default+ will be used if it exists. Returns +nil+ if there is no main
### file to be found.
def findRdocMain( catalogFile="docs/CATALOG", default="README" )
# Try extracting it from the CATALOG file from a line that looks like:
# Main: Foo Bar Module
main = findCatalogKeyword( 'main', catalogFile )
# Try to make some educated guesses if that doesn't work
if main.nil?
basedir = File::dirname( __FILE__ )
basedir = File::dirname( basedir ) if /docs$/ =~ basedir
if File::exists?( File::join(basedir, default) )
main = default
end
end
return main
end
### Given a documentation <tt>catalogFile</tt>, extract an upload URL for
### RDoc.
def findRdocUpload( catalogFile="docs/CATALOG" )
findCatalogKeyword( 'upload', catalogFile )
end
### Given a documentation <tt>catalogFile</tt>, extract a CVS web frontend
### URL for RDoc.
def findRdocCvsURL( catalogFile="docs/CATALOG" )
findCatalogKeyword( 'webcvs', catalogFile )
end
### Given a documentation <tt>catalogFile</tt>, try extracting the given
### +keyword+'s value from it. Keywords are lines that look like:
### # <keyword>: <value>
### Returns +nil+ if the catalog file was unreadable or didn't contain the
### specified +keyword+.
def findCatalogKeyword( keyword, catalogFile="docs/CATALOG" )
val = nil
if File::exists? catalogFile
message "Extracting '#{keyword}' from CATALOG file (%s).\n" % catalogFile
File::foreach( catalogFile ) {|line|
debugMsg( "Examining line #{line.inspect}..." )
val = $1.strip and break if /^#\s*#{keyword}:\s*(.*)$/i =~ line
}
end
return val
end
### Given a documentation <tt>catalogFile</tt>, which is in the same format
### as that described by #readManifest, read and expand it, and then return
### a list of those files which appear to have RDoc documentation in
### them. If <tt>catalogFile</tt> is nil or does not exist, the MANIFEST
### file is used instead.
def findRdocableFiles( catalogFile="docs/CATALOG" )
startlist = []
if File.exists? catalogFile
message "Using CATALOG file (%s).\n" % catalogFile
startlist = getVettedManifest( catalogFile )
else
message "Using default MANIFEST\n"
startlist = getVettedManifest()
end
message "Looking for RDoc comments in:\n" if $VERBOSE
startlist.select {|fn|
message " #{fn}: " if $VERBOSE
found = false
File::open( fn, "r" ) {|fh|
fh.each {|line|
if line =~ /^(\s*#)?\s*=/ || line =~ /:\w+:/ || line =~ %r{/\*}
found = true
break
end
}
}
message( (found ? "yes" : "no") + "\n" ) if $VERBOSE
found
}
end
### Open a file and filter each of its lines through the given block a
### <tt>line</tt> at a time. The return value of the block is used as the
### new line, or omitted if the block returns <tt>nil</tt> or
### <tt>false</tt>.
def editInPlace( file ) # :yields: line
raise "No block specified for editing operation" unless block_given?
tempName = "#{file}.#{$$}"
File::open( tempName, File::RDWR|File::CREAT, 0600 ) {|tempfile|
File::unlink( tempName )
File::open( file, File::RDONLY ) {|fh|
fh.each {|line|
newline = yield( line ) or next
tempfile.print( newline )
}
}
tempfile.seek(0)
File::open( file, File::TRUNC|File::WRONLY, 0644 ) {|newfile|
newfile.print( tempfile.read )
}
}
end
### Execute the specified shell <tt>command</tt>, read the results, and
### return them. Like a %x{} that returns an Array instead of a String.
def shellCommand( *command )
raise "Empty command" if command.empty?
cmdpipe = IO::popen( command.join(' '), 'r' )
return cmdpipe.readlines
end
### Execute a block with $VERBOSE set to +false+, restoring it to its
### previous value before returning.
def verboseOff
raise LocalJumpError, "No block given" unless block_given?
thrcrit = Thread.critical
oldverbose = $VERBOSE
begin
Thread.critical = true
$VERBOSE = false
yield
ensure
$VERBOSE = oldverbose
Thread.critical = false
end
end
### Try the specified code block, printing the given
def try( msg, bind=nil )
result = nil
if msg =~ /^to\s/
message = "Trying #{msg}..."
else
message = msg
end
begin
rval = nil
if block_given?
rval = yield
else
file, line = caller(1)[0].split(/:/,2)
rval = eval( msg, bind, file, line.to_i )
end
result = rval.inspect
rescue Exception => err
if err.backtrace
nicetrace = err.backtrace.delete_if {|frame|
/in `(try|eval)'/ =~ frame
}.join("\n\t")
else
nicetrace = "Exception had no backtrace"
end
result = err.message + "\n\t" + nicetrace
ensure
puts result
end
end
def time
start = Time::now
stimes = Process::times
rval = yield
etimes = Process::times
$stderr.puts "Time elapsed: %0.5f user, %0.5f system (%0.5f wall clock seconds)" % [
etimes.utime - stimes.utime,
etimes.stime - stimes.stime,
Time::now.to_f - start.to_f,
]
return rval
end
end
| 29.796029 | 96 | 0.619071 |
d5c7da40046452fe34726aafd1bc0966554920c9 | 1,087 | if ENV['CI'] || ENV['COVERAGE']
require 'coveralls'
require 'simplecov'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
SimpleCov.start do
add_filter 'drop_example_group.rb'
add_filter 'tag_example_group.rb'
add_filter 'spec'
add_filter 'gemfiles'
end
end
# Configure Rails Environment
ENV['RAILS_ENV'] = 'test'
require File.expand_path('../dummy/config/environment.rb', __FILE__)
require 'pry'
require 'liquid-rails'
require 'rspec/rails'
require 'capybara/rspec'
require 'liquid-rails/matchers'
Liquid::Template.error_mode = :strict
Rails.backtrace_cleaner.remove_silencers!
# Load support files
require 'fixtures/poro'
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
RSpec.configure do |config|
config.filter_run focus: true
config.run_all_when_everything_filtered = true
config.include Capybara::RSpecMatchers
config.include ActiveSupport::Testing::SetupAndTeardown
config.include ActionController::TestCase::Behavior
end | 25.880952 | 71 | 0.75805 |
4ae1fd02c03702599ba5bb31dba6962b06947f12 | 199 | # frozen_string_literal: true
# relative-require all rspec files
Dir[File.dirname(__FILE__) + '/rspec/*.rb'].each do |file|
require_relative 'rspec/' + File.basename(file, File.extname(file))
end
| 28.428571 | 69 | 0.738693 |
61ca276fe2fd72e788680ff7552677999a1136c4 | 162 | namespace :glyphs do
desc 'Build all glyphs'
task :all do
puts %x(fontcustom compile)
end
end
desc 'Alias for glyphs:all'
task :glyphs => 'glyphs:all'
| 16.2 | 31 | 0.691358 |
1a4226cf43b791b9d49b233fece0194c7bfee5ec | 112 | require 'test_helper'
describe MongoidOccurrences do
it { _(::MongoidOccurrences::VERSION).wont_be_nil }
end
| 18.666667 | 53 | 0.785714 |
62f810e698d12ccf8ca93539f187aeb62aa59192 | 110 | Sequel.migration do
change do
alter_table :layers do
add_column :tooltip, :text
end
end
end
| 13.75 | 32 | 0.672727 |
2154bd4f288b77ec54946be5fdb414e913e63293 | 1,275 | # frozen_string_literal: true
lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'meta_tags/version'
Gem::Specification.new do |spec|
spec.name = "meta-tags"
spec.version = MetaTags::VERSION
spec.authors = ["Dmytro Shteflyuk"]
spec.email = ["[email protected]"]
spec.summary = "Collection of SEO helpers for Ruby on Rails."
spec.description = "Search Engine Optimization (SEO) plugin for Ruby on Rails applications."
spec.homepage = "http://github.com/kpumuk/meta-tags"
spec.license = "MIT"
spec.platform = Gem::Platform::RUBY
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(\.|(bin|test|spec|features)/)}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "actionpack", ">= 4.0.0"
spec.add_development_dependency "rake", "~> 12.0"
spec.add_development_dependency "rspec", "~> 3.8.0"
spec.add_development_dependency "rspec-html-matchers", "~> 0.9.1"
spec.cert_chain = ["certs/kpumuk.pem"]
spec.signing_key = File.expand_path("~/.ssh/gem-kpumuk.pem") if $PROGRAM_NAME.end_with?('gem')
end
| 38.636364 | 113 | 0.654902 |
62f0a7597f36f49d3999c5fe68d0e9585e29ac75 | 5,011 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :mirror
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "springbig_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
| 44.345133 | 114 | 0.762323 |
f8e021dd9f5f629995e4d68f7ef0b8950e6d2dfc | 176 | $:.unshift(File.dirname(__FILE__)) unless
$:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
module Freckle
VERSION = '0.0.1'
end | 29.333333 | 94 | 0.710227 |
e8b0e8d1cc21fa1f909cd3c618deb59e0290668b | 6,293 | # frozen_string_literal: true
module Facter
module Resolvers
class NetworkingLinux < BaseResolver
@semaphore = Mutex.new
@fact_list = {}
DIRS = ['/var/lib/dhclient/', '/var/lib/dhcp/', '/var/lib/dhcp3/', '/var/lib/NetworkManager/', '/var/db/'].freeze
class << self
private
def post_resolve(fact_name)
@fact_list.fetch(fact_name) { retrieve_network_info(fact_name) }
@fact_list[fact_name]
end
def retrieve_network_info(fact_name)
@fact_list ||= {}
retrieve_interface_info
retrieve_interfaces_mac_and_mtu
retrieve_default_interface
@fact_list[fact_name]
end
def retrieve_interfaces_mac_and_mtu
@fact_list[:interfaces].map do |name, info|
macaddress = Util::FileHelper.safe_read("/sys/class/net/#{name}/address", nil)
info[:mac] = macaddress.strip if macaddress && !macaddress.include?('00:00:00:00:00:00')
mtu = Util::FileHelper.safe_read("/sys/class/net/#{name}/mtu", nil)
info[:mtu] = mtu.strip.to_i if mtu
end
end
def retrieve_interface_info
output = Facter::Core::Execution.execute('ip -o address', logger: log)
interfaces = {}
output.each_line do |ip_line|
ip_tokens = ip_line.split(' ')
fill_ip_v4_info!(ip_tokens, interfaces)
fill_io_v6_info!(ip_tokens, interfaces)
find_dhcp!(ip_tokens, interfaces)
end
@fact_list[:interfaces] = interfaces
end
def find_dhcp!(tokens, network_info)
interface_name = tokens[1]
return if !network_info[interface_name] || network_info[interface_name][:dhcp]
index = tokens[0].delete(':')
dhcp = Util::FileHelper.safe_read("/run/systemd/netif/leases/#{index}", nil)
network_info[interface_name][:dhcp] = dhcp.match(/SERVER_ADDRESS=(.*)/)[1] if dhcp
network_info[interface_name][:dhcp] ||= retrieve_from_other_directories(interface_name)
end
def retrieve_from_other_directories(interface_name)
DIRS.each do |dir|
next unless File.readable?(dir)
lease_files = Dir.entries(dir).select { |file| file =~ /dhclient.*\.lease/ }
next if lease_files.empty?
lease_files.select do |file|
content = Util::FileHelper.safe_read("#{dir}#{file}", nil)
next unless content =~ /interface.*#{interface_name}/
return content.match(/dhcp-server-identifier ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/)[1]
end
end
return unless File.readable?('/var/lib/NetworkManager/')
search_internal_leases(interface_name)
end
def search_internal_leases(interface_name)
files = Dir.entries('/var/lib/NetworkManager/').reject { |dir| dir =~ /^\.+$/ }
lease_file = files.find { |file| file =~ /internal.*#{interface_name}\.lease/ }
return unless lease_file
dhcp = Util::FileHelper.safe_read("/var/lib/NetworkManager/#{lease_file}", nil)
dhcp ? dhcp.match(/SERVER_ADDRESS=(.*)/)[1] : nil
end
def fill_ip_v4_info!(ip_tokens, network_info)
return unless ip_tokens[2].casecmp('inet').zero?
interface_name, ip4_address, ip4_mask_length = retrieve_name_and_ip_info(ip_tokens, '32')
binding = build_binding(ip4_address, ip4_mask_length)
build_network_info_structure!(network_info, interface_name, 'bindings')
populate_other_ipv4_facts(network_info, interface_name, binding)
end
def populate_other_ipv4_facts(network_info, interface_name, binding)
network_info[interface_name]['bindings'] << binding
network_info[interface_name][:ip] ||= binding[:address]
network_info[interface_name][:network] ||= binding[:network]
network_info[interface_name][:netmask] ||= binding[:netmask]
end
def retrieve_name_and_ip_info(tokens, default_mask)
interface_name = tokens[1]
ip_info = tokens[3].split('/')
ip_address = ip_info[0]
if ip_info.length > 1
ip_mask_length = ip_info[1]
else
ip_mask_length = default_mask
end
[interface_name, ip_address, ip_mask_length]
end
def fill_io_v6_info!(ip_tokens, network_info)
return unless ip_tokens[2].casecmp('inet6').zero?
interface_name, ip6_address, ip6_mask_length = retrieve_name_and_ip_info(ip_tokens, '128')
binding = build_binding(ip6_address, ip6_mask_length)
build_network_info_structure!(network_info, interface_name, 'bindings6')
network_info[interface_name][:scope6] ||= ip_tokens[5]
populate_other_ipv6_facts(network_info, interface_name, binding)
end
def populate_other_ipv6_facts(network_info, interface_name, binding)
network_info[interface_name]['bindings6'] << binding
network_info[interface_name][:ip6] ||= binding[:address]
network_info[interface_name][:network6] ||= binding[:network]
network_info[interface_name][:netmask6] ||= binding[:netmask]
end
def retrieve_default_interface
output = Facter::Core::Execution.execute('ip route get 1', logger: log)
ip_route_tokens = output.each_line.first.strip.split(' ')
default_interface = ip_route_tokens[4]
@fact_list[:primary_interface] = default_interface
end
def build_binding(addr, mask_length)
require 'ipaddr'
ip = IPAddr.new(addr)
mask_helper = ip.ipv6? ? 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' : '255.255.255.255'
mask = IPAddr.new(mask_helper).mask(mask_length)
{ address: addr, netmask: mask.to_s, network: ip.mask(mask_length).to_s }
end
def build_network_info_structure!(network_info, interface_name, binding)
network_info[interface_name] = {} unless network_info.dig(interface_name)
network_info[interface_name][binding] = [] unless network_info.dig(interface_name, binding)
end
end
end
end
end
| 37.458333 | 119 | 0.63086 |
87d8625251ba3e26186999ac2021cbaaf08e925f | 602 | cask "appdelete" do
version "4.3.3"
sha256 :no_check
url "http://www.reggieashworth.com/downloads/AppDelete.dmg"
name "AppDelete"
desc "App uninstaller"
homepage "http://www.reggieashworth.com/appdelete.html"
auto_updates true
app "AppDelete.app"
zap trash: [
"~/Library/Application Support/AppDelete",
"~/Library/Caches/com.apps4macs.AppDelete",
"~/Library/Preferences/com.apps4macs.AppDelete.plist",
"~/Library/Saved Application State/com.apps4macs.AppDelete.savedState",
"~/Library/Services/AppDelete.workflow",
]
caveats do
discontinued
end
end
| 23.153846 | 75 | 0.717608 |
3821e0c9493ca0dec1dfc5571a402c3cd9b4b856 | 3,705 | require "cases/helper"
require "models/reply"
require "models/topic"
module ActiveRecord
class DupTest < ActiveRecord::TestCase
fixtures :topics
def test_dup
assert !Topic.new.freeze.dup.frozen?
end
def test_not_readonly
topic = Topic.first
duped = topic.dup
assert !duped.readonly?, "should not be readonly"
end
def test_is_readonly
topic = Topic.first
topic.readonly!
duped = topic.dup
assert duped.readonly?, "should be readonly"
end
def test_dup_not_persisted
topic = Topic.first
duped = topic.dup
assert !duped.persisted?, "topic not persisted"
assert duped.new_record?, "topic is new"
end
def test_dup_not_destroyed
topic = Topic.first
topic.destroy
duped = topic.dup
assert_not duped.destroyed?
end
def test_dup_has_no_id
topic = Topic.first
duped = topic.dup
assert_nil duped.id
end
def test_dup_with_modified_attributes
topic = Topic.first
topic.author_name = "Aaron"
duped = topic.dup
assert_equal "Aaron", duped.author_name
end
def test_dup_with_changes
dbtopic = Topic.first
topic = Topic.new
topic.attributes = dbtopic.attributes.except("id")
#duped has no timestamp values
duped = dbtopic.dup
#clear topic timestamp values
topic.send(:clear_timestamp_attributes)
assert_equal topic.changes, duped.changes
end
def test_dup_topics_are_independent
topic = Topic.first
topic.author_name = "Aaron"
duped = topic.dup
duped.author_name = "meow"
assert_not_equal topic.changes, duped.changes
end
def test_dup_attributes_are_independent
topic = Topic.first
duped = topic.dup
duped.author_name = "meow"
topic.author_name = "Aaron"
assert_equal "Aaron", topic.author_name
assert_equal "meow", duped.author_name
end
def test_dup_timestamps_are_cleared
topic = Topic.first
assert_not_nil topic.updated_at
assert_not_nil topic.created_at
# temporary change to the topic object
topic.updated_at -= 3.days
#dup should not preserve the timestamps if present
new_topic = topic.dup
assert_nil new_topic.updated_at
assert_nil new_topic.created_at
new_topic.save
assert_not_nil new_topic.updated_at
assert_not_nil new_topic.created_at
end
def test_dup_after_initialize_callbacks
topic = Topic.new
assert Topic.after_initialize_called
Topic.after_initialize_called = false
topic.dup
assert Topic.after_initialize_called
end
def test_dup_validity_is_independent
repair_validations(Topic) do
Topic.validates_presence_of :title
topic = Topic.new("title" => "Literature")
topic.valid?
duped = topic.dup
duped.title = nil
assert duped.invalid?
topic.title = nil
duped.title = "Mathematics"
assert topic.invalid?
assert duped.valid?
end
end
def test_dup_with_default_scope
prev_default_scopes = Topic.default_scopes
Topic.default_scopes = [proc { Topic.where(approved: true) }]
topic = Topic.new(approved: false)
assert !topic.dup.approved?, "should not be overridden by default scopes"
ensure
Topic.default_scopes = prev_default_scopes
end
def test_dup_without_primary_key
klass = Class.new(ActiveRecord::Base) do
self.table_name = "parrots_pirates"
end
record = klass.create!
assert_nothing_raised do
record.dup
end
end
end
end
| 23.449367 | 79 | 0.667746 |
1cc57b4555358ed2509da02f5a203234ef5e2274 | 1,993 | class V2::ServiceInstancesController < V2::BaseController
# This is actually the create
def update
plan_guid = params.fetch(:plan_id)
unless Catalog.has_plan?(plan_guid)
return render status: 422, json: {'description' => "Cannot create a service instance. Plan #{plan_guid} was not found in the catalog."}
end
plan_max_storage_mb = Catalog.storage_quota_for_plan_guid(plan_guid)
if ServiceCapacity.can_allocate?(plan_max_storage_mb)
instance_guid = params.fetch(:id)
instance = ServiceInstanceManager.create(guid: instance_guid, plan_guid: plan_guid)
render status: 201, json: {} # { dashboard_url: build_dashboard_url(instance) }
else
render status: 507, json: {'description' => 'Service capacity has been reached'}
end
end
def set_plan
instance_guid = params.fetch(:id)
plan_guid = params.fetch(:plan_id)
begin
ServiceInstanceManager.set_plan(guid: instance_guid, plan_guid: plan_guid)
status = 200
body = {}
rescue ServiceInstanceManager::ServiceInstanceNotFound
status = 404
body = { description: 'Service instance not found' }
rescue ServiceInstanceManager::ServicePlanNotFound
status = 400
body = { description: 'Service plan not found' }
rescue ServiceInstanceManager::InvalidServicePlanUpdate => e
status = 422
body = { description: e.message }
end
render status: status, json: body
end
def destroy
instance_guid = params.fetch(:id)
begin
ServiceInstanceManager.destroy(guid: instance_guid)
status = 200
rescue ServiceInstanceManager::ServiceInstanceNotFound
status = 410
end
render status: status, json: {}
end
private
# def build_dashboard_url(instance)
# domain = Settings.external_host
# path = manage_instance_path(instance.guid)
#
# "#{scheme}://#{domain}#{path}"
# end
def scheme
Settings['ssl_enabled'] == false ? 'http': 'https'
end
end
| 28.471429 | 141 | 0.691922 |
795d573c528452e6465e33a17a261b1265fe66f5 | 578 | cask 'paperspace' do
version '7.2.0.6'
sha256 'b2e539523dec13e8fb475ee43ce542e90beb2d307a20435de3f756dc4727c82f'
# ps-receiver.s3.amazonaws.com was verified as official when first introduced to the cask
url "https://ps-receiver.s3.amazonaws.com/darwin/Paperspace-#{version}.dmg"
appcast 'https://www.macupdater.net/cgi-bin/extract_text/extract_text_split_easy.cgi?url=https://www.paperspace.com/download&user_agent=Mozilla/5.0%20(Macintosh%3B%20Intel%20Mac%20OS%20X%2010_14_5)'
name 'Paperspace'
homepage 'https://www.paperspace.com/'
app 'Paperspace.app'
end
| 44.461538 | 200 | 0.785467 |
0150aa6d4b0cb88ebd060ca8637127d1058d33fc | 548 | require "rdg/analysis/analyser"
module RDG
module Control
class Jump < Analysis::Analyser
def analyse(context)
return unless block
super
remove_all_successors
add_new_successors
end
protected
def block_types
%i(while until for)
end
private
def add_new_successors
new_successors.each { |s| graph.add_edge(@ast_node, s) }
end
def block
@ast_node.ancestors.detect { |a| block_types.include?(a.type) }
end
end
end
end
| 17.677419 | 71 | 0.607664 |
03a50ca0f752c6be1a47b318b6ccf0fad77a3ba9 | 1,210 | class Api::ConsumersController < Api::BaseResourceController
acts_as_token_authentication_handler_for Consumer, except: [:create]
def create
raise ActionController::ParameterMissing.new('phone') unless consumer_params[:phone].present?
raise ActionController::ParameterMissing.new('code') unless consumer_params[:code].present?
raise ActionController::ParameterMissing.new('password') unless consumer_params[:password].present?
raise ActionController::ParameterMissing.new('password_confirmation') unless consumer_params[:password_confirmation].present?
@consumer = Consumer.where(phone: consumer_params[:phone])
if @consumer.present?
render :consumer_not_exist, status: 409
elsif consumer_params[:password] != consumer_params[:password_confirmation]
render :passwords_not_same, status: 407
else
@consumer = Consumer.create!(phone: consumer_params[:phone],
password: consumer_params[:password],
password_confirmation: consumer_params[:password_confirmation])
render :logged_in, status: 200
end
end
private
def consumer_params
params.require(:consumer)
end
end
| 40.333333 | 129 | 0.729752 |
b9473e463b7081b57e6dc2c5427e3680f1294b2f | 498 | require_relative 'remote_logger'
Rails.application.configure do
config.action_controller.perform_caching = true
config.assets.compile = false
config.assets.digest = true
config.assets.js_compressor = :uglifier
config.cache_classes = true
config.consider_all_requests_local = false
config.eager_load = true
config.serve_static_assets = false
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.active_record.dump_schema_after_migration = false
end
| 31.125 | 58 | 0.807229 |
5daab355aaf6edb5512c340ad2b84ca71b430b98 | 79 | require "cookies_eu/version"
require "cookies_eu/engine"
module CookiesEu
end
| 13.166667 | 28 | 0.822785 |
bb6809e08fb43207fa8c23ddf80fd5db954f3f12 | 3,431 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/devtools/artifactregistry/v1beta2/yum_artifact.proto
require 'google/protobuf'
require 'google/api/annotations_pb'
require 'google/api/field_behavior_pb'
require 'google/api/resource_pb'
require 'google/longrunning/operations_pb'
require 'google/rpc/status_pb'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/devtools/artifactregistry/v1beta2/yum_artifact.proto", :syntax => :proto3) do
add_message "google.devtools.artifactregistry.v1beta2.YumArtifact" do
optional :name, :string, 1
optional :package_name, :string, 2
optional :package_type, :enum, 3, "google.devtools.artifactregistry.v1beta2.YumArtifact.PackageType"
optional :architecture, :string, 4
end
add_enum "google.devtools.artifactregistry.v1beta2.YumArtifact.PackageType" do
value :PACKAGE_TYPE_UNSPECIFIED, 0
value :BINARY, 1
value :SOURCE, 2
end
add_message "google.devtools.artifactregistry.v1beta2.ImportYumArtifactsGcsSource" do
repeated :uris, :string, 1
optional :use_wildcards, :bool, 2
end
add_message "google.devtools.artifactregistry.v1beta2.ImportYumArtifactsRequest" do
optional :parent, :string, 1
oneof :source do
optional :gcs_source, :message, 2, "google.devtools.artifactregistry.v1beta2.ImportYumArtifactsGcsSource"
end
end
add_message "google.devtools.artifactregistry.v1beta2.ImportYumArtifactsErrorInfo" do
optional :error, :message, 2, "google.rpc.Status"
oneof :source do
optional :gcs_source, :message, 1, "google.devtools.artifactregistry.v1beta2.ImportYumArtifactsGcsSource"
end
end
add_message "google.devtools.artifactregistry.v1beta2.ImportYumArtifactsResponse" do
repeated :yum_artifacts, :message, 1, "google.devtools.artifactregistry.v1beta2.YumArtifact"
repeated :errors, :message, 2, "google.devtools.artifactregistry.v1beta2.ImportYumArtifactsErrorInfo"
end
add_message "google.devtools.artifactregistry.v1beta2.ImportYumArtifactsMetadata" do
end
end
end
module Google
module Cloud
module ArtifactRegistry
module V1beta2
YumArtifact = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.artifactregistry.v1beta2.YumArtifact").msgclass
YumArtifact::PackageType = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.artifactregistry.v1beta2.YumArtifact.PackageType").enummodule
ImportYumArtifactsGcsSource = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.artifactregistry.v1beta2.ImportYumArtifactsGcsSource").msgclass
ImportYumArtifactsRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.artifactregistry.v1beta2.ImportYumArtifactsRequest").msgclass
ImportYumArtifactsErrorInfo = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.artifactregistry.v1beta2.ImportYumArtifactsErrorInfo").msgclass
ImportYumArtifactsResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.artifactregistry.v1beta2.ImportYumArtifactsResponse").msgclass
ImportYumArtifactsMetadata = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.artifactregistry.v1beta2.ImportYumArtifactsMetadata").msgclass
end
end
end
end
| 52.784615 | 175 | 0.781113 |
877c1d94eaa2da54de335d8840e1ce0662915bad | 1,020 | Puppet::Type.type(:jail_release).provide(:pyiocage) do
desc 'Manage jails release base downloads using iocage(8)'
confine kernel: :freebsd
defaultfor kernel: :freebsd
# this is used for further confinement
commands pyiocage: '/usr/local/bin/iocage'
def self.iocage(*args)
cmd = ['/usr/local/bin/iocage', args].flatten.join(' ')
execute(cmd, override_locale: false, failonfail: true, combine: true)
end
def iocage(*args)
self.class.iocage(args)
end
mk_resource_methods
def self.prefetch(resources)
instances.each do |prov|
if (resource = resources[prov.name])
resource.provider = prov
end
end
end
def self.instances
releases = iocage('list', '-Hr')
releases.split("\n").map { |r| new(name: r, ensure: :present) }
end
def exists?
@property_hash[:ensure] == :present
end
def create
iocage('fetch', '--release', resource[:name])
end
def destroy
iocage('destroy', '--force', '--release', resource[:name])
end
end
| 22.666667 | 73 | 0.657843 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.