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
3975e969d1f757eb9d749d70e45dfb618d21d228
681
module AMQ module Protocol TLS_PORT = 5671 SSL_PORT = 5671 # caching EMPTY_STRING = "".freeze PACK_INT8 = 'c'.freeze PACK_CHAR = 'C'.freeze PACK_UINT16 = 'n'.freeze PACK_UINT16_X2 = 'n2'.freeze PACK_UINT32 = 'N'.freeze PACK_UINT32_X2 = 'N2'.freeze PACK_UINT64_BE = 'Q>'.freeze PACK_INT64 = 'q'.freeze PACK_INT64_BE = 'q>'.freeze PACK_UCHAR_UINT32 = 'CN'.freeze PACK_CHAR_UINT16_UINT32 = 'cnN'.freeze PACK_32BIT_FLOAT = 'f'.freeze PACK_64BIT_FLOAT = 'G'.freeze end end
27.24
42
0.515419
f8ace6338767af6e4d19dc456b8256205b1ae61a
14,452
require "spec_helper" require "ohai" module Omnibus describe Project do subject do described_class.new.evaluate do name "sample" friendly_name "Sample Project" install_dir "/sample" maintainer "Sample Devs" homepage "http://example.com/" build_version "1.0" build_iteration 1 extra_package_file "/path/to/sample_dir" extra_package_file "/path/to/file.conf" resources_path "sample/project/resources" end end it_behaves_like "a cleanroom setter", :name, %{name 'chef'} it_behaves_like "a cleanroom setter", :friendly_name, %{friendly_name 'Chef'} it_behaves_like "a cleanroom setter", :package_name, %{package_name 'chef.package'} it_behaves_like "a cleanroom setter", :maintainer, %{maintainer 'Chef Software, Inc'} it_behaves_like "a cleanroom setter", :homepage, %{homepage 'https://getchef.com'} it_behaves_like "a cleanroom setter", :description, %{description 'Installs the thing'} it_behaves_like "a cleanroom setter", :replace, %{replace 'old-chef'} it_behaves_like "a cleanroom setter", :conflict, %{conflict 'puppet'} it_behaves_like "a cleanroom setter", :build_version, %{build_version '1.2.3'} it_behaves_like "a cleanroom setter", :build_iteration, %{build_iteration 1} it_behaves_like "a cleanroom setter", :package_user, %{package_user 'chef'} it_behaves_like "a cleanroom setter", :package_group, %{package_group 'chef'} it_behaves_like "a cleanroom setter", :override, %{override :chefdk, source: 'foo.com'} it_behaves_like "a cleanroom setter", :resources_path, %{resources_path '/path'} it_behaves_like "a cleanroom setter", :package_scripts_path, %{package_scripts_path '/path/scripts'} it_behaves_like "a cleanroom setter", :dependency, %{dependency 'libxslt-dev'} it_behaves_like "a cleanroom setter", :runtime_dependency, %{runtime_dependency 'libxslt'} it_behaves_like "a cleanroom setter", :exclude, %{exclude 'hamlet'} it_behaves_like "a cleanroom setter", :config_file, %{config_file '/path/to/config.rb'} it_behaves_like "a cleanroom setter", :extra_package_file, %{extra_package_file '/path/to/asset'} it_behaves_like "a cleanroom setter", :text_manifest_path, %{text_manifest_path '/path/to/manifest.txt'} it_behaves_like "a cleanroom setter", :json_manifest_path, %{json_manifest_path '/path/to/manifest.txt'} it_behaves_like "a cleanroom setter", :build_git_revision, %{build_git_revision 'wombats'} it_behaves_like "a cleanroom getter", :files_path it_behaves_like "a cleanroom setter", :license, %{license 'Apache 2.0'} it_behaves_like "a cleanroom setter", :license_file, %{license_file 'LICENSES/artistic.txt'} it_behaves_like "a cleanroom setter", :license_file_path, %{license_file_path 'CHEF_LICENSE'} describe "basics" do it "returns a name" do expect(subject.name).to eq("sample") end it "returns an install_dir" do expect(subject.install_dir).to eq("/sample") end it "returns a maintainer" do expect(subject.maintainer).to eq("Sample Devs") end it "returns a homepage" do expect(subject.homepage).to eq("http://example.com/") end it "returns a build version" do expect(subject.build_version).to eq("1.0") end it "returns a build iteration" do expect(subject.build_iteration).to eq(1) end it "returns an array of files and dirs" do expect(subject.extra_package_files).to eq(["/path/to/sample_dir", "/path/to/file.conf"]) end it "returns a friendly_name" do expect(subject.friendly_name).to eq("Sample Project") end it "returns a resources_path" do expect(subject.resources_path).to include("sample/project/resources") end end describe "#install_dir" do it "removes duplicate slashes" do subject.install_dir("///opt//chef") expect(subject.install_dir).to eq("/opt/chef") end it "converts Windows slashes to Ruby ones" do subject.install_dir('C:\\chef\\chefdk') expect(subject.install_dir).to eq("C:/chef/chefdk") end it "removes trailing slashes" do subject.install_dir("/opt/chef//") expect(subject.install_dir).to eq("/opt/chef") end it "is a DSL method" do expect(subject).to have_exposed_method(:install_dir) end end describe "#default_root" do context "on Windows" do before { stub_ohai(platform: "windows", version: "2012R2") } it "returns C:/" do expect(subject.default_root).to eq("C:") end end context "on non-Windows" do before { stub_ohai(platform: "ubuntu", version: "16.04") } it "returns /opt" do expect(subject.default_root).to eq("/opt") end end it "is a DSL method" do expect(subject).to have_exposed_method(:default_root) end end describe "build_git_revision" do let(:git_repo_subdir_path) do path = local_git_repo("foobar", annotated_tags: ["1.0", "2.0", "3.0"]) subdir_path = File.join(path, "asubdir") Dir.mkdir(subdir_path) subdir_path end it "returns a revision even when running in a subdir" do Dir.chdir(git_repo_subdir_path) do expect(subject.build_git_revision).to eq("632501dde2c41f3bdd988b818b4c008e2ff398dc") end end end describe "#license" do it "sets the default to Unspecified" do expect(subject.license).to eq ("Unspecified") end end describe "#license_file_path" do it "sets the default to LICENSE" do expect(subject.license_file_path).to eq ("/sample/LICENSE") end end describe "#dirty!" do let(:software) { double(Omnibus::Software) } it "dirties the cache" do subject.instance_variable_set(:@culprit, nil) subject.dirty!(software) expect(subject).to be_dirty end it "sets the culprit" do subject.instance_variable_set(:@culprit, nil) subject.dirty!(software) expect(subject.culprit).to be(software) end end describe "#dirty?" do it "returns true by default" do subject.instance_variable_set(:@culprit, nil) expect(subject).to_not be_dirty end it "returns true when the cache is dirty" do subject.instance_variable_set(:@culprit, true) expect(subject).to be_dirty end it "returns false when the cache is not dirty" do subject.instance_variable_set(:@culprit, false) expect(subject).to_not be_dirty end end describe "#<=>" do let(:chefdk) { described_class.new.tap { |p| p.name("chefdk") } } let(:chef) { described_class.new.tap { |p| p.name("chef") } } let(:ruby) { described_class.new.tap { |p| p.name("ruby") } } it "compares projects by name" do list = [chefdk, chef, ruby] expect(list.sort.map(&:name)).to eq(%w{chef chefdk ruby}) end end describe "#build_iteration" do let(:fauxhai_options) { {} } before { stub_ohai(fauxhai_options) } context "when on RHEL" do let(:fauxhai_options) { { platform: "redhat", version: "8" } } it "returns a RHEL iteration" do expect(subject.build_iteration).to eq(1) end end context "when on Debian" do let(:fauxhai_options) { { platform: "debian", version: "10" } } it "returns a Debian iteration" do expect(subject.build_iteration).to eq(1) end end context "when on FreeBSD" do let(:fauxhai_options) { { platform: "freebsd", version: "12" } } it "returns a FreeBSD iteration" do expect(subject.build_iteration).to eq(1) end end context "when on Windows" do before { stub_ohai(platform: "windows", version: "2019") } before { stub_const("File::ALT_SEPARATOR", '\\') } it "returns a Windows iteration" do expect(subject.build_iteration).to eq(1) end end context "when on OS X" do let(:fauxhai_options) { { platform: "mac_os_x", version: "10.15" } } it "returns a generic iteration" do expect(subject.build_iteration).to eq(1) end end end describe "#overrides" do before { subject.overrides.clear } it "sets all the things through #overrides" do subject.override(:thing, version: "6.6.6") expect(subject.override(:zlib)).to be_nil end it "retrieves the things set through #overrides" do subject.override(:thing, version: "6.6.6") expect(subject.override(:thing)[:version]).to eq("6.6.6") end it "symbolizes #overrides" do subject.override("thing", version: "6.6.6") [:thing, "thing"].each do |thing| expect(subject.override(thing)).not_to be_nil end expect(subject.override(:thing)[:version]).to eq("6.6.6") end end describe "#ohai" do before { stub_ohai(platform: "ubuntu", version: "16.04") } it "is a DSL method" do expect(subject).to have_exposed_method(:ohai) end it "delegates to the Ohai class" do expect(subject.ohai).to be(Ohai) end end describe "#packagers_for_system" do it "returns array of packager objects" do subject.packagers_for_system.each do |packager| expect(packager).to be_a(Packager::Base) end end it "calls Packager#for_current_system" do expect(Packager).to receive(:for_current_system) .and_call_original subject.packagers_for_system end end describe "#package" do it "raises an exception when a block is not given" do expect { subject.package(:foo) }.to raise_error(InvalidValue) end it "adds the block to the list" do block = Proc.new {} subject.package(:foo, &block) expect(subject.packagers[:foo]).to include(block) end it "allows for multiple invocations, keeping order" do block_1, block_2 = Proc.new {}, Proc.new {} subject.package(:foo, &block_1) subject.package(:foo, &block_2) expect(subject.packagers[:foo]).to eq([block_1, block_2]) end end describe "#packagers" do it "returns a Hash" do expect(subject.packagers).to be_a(Hash) end it "has a default Hash value of an empty array" do expect(subject.packagers[:foo]).to be_a(Array) expect(subject.packagers[:bar]).to_not be(subject.packagers[:foo]) end end describe "#compressor" do it "returns a compressor object" do expect(subject.compressor).to be_a(Compressor::Base) end it "calls Compressor#for_current_system" do expect(Compressor).to receive(:for_current_system) .and_call_original subject.compressor end it "passes in the current compressors" do subject.compress(:dmg) subject.compress(:tgz) expect(Compressor).to receive(:for_current_system) .with(%i{dmg tgz}) .and_call_original subject.compressor end end describe "#compress" do it "does not raises an exception when a block is not given" do expect { subject.compress(:foo) }.to_not raise_error end it "adds the compressor to the list" do subject.compress(:foo) expect(subject.compressors).to include(:foo) end it "adds the block to the list" do block = Proc.new {} subject.compress(:foo, &block) expect(subject.compressors[:foo]).to include(block) end it "allows for multiple invocations, keeping order" do block_1, block_2 = Proc.new {}, Proc.new {} subject.compress(:foo, &block_1) subject.compress(:foo, &block_2) expect(subject.compressors[:foo]).to eq([block_1, block_2]) end end describe "#compressors" do it "returns a Hash" do expect(subject.compressors).to be_a(Hash) end it "has a default Hash value of an empty array" do expect(subject.compressors[:foo]).to be_a(Array) expect(subject.compressors[:bar]).to_not be(subject.compressors[:foo]) end end describe "#shasum" do context "when a filepath is given" do let(:path) { "/project.rb" } let(:file) { double(File) } before do subject.instance_variable_set(:@filepath, path) allow(File).to receive(:exist?) .with(path) .and_return(true) allow(File).to receive(:open) .with(path) .and_return(file) end it "returns the correct shasum" do expect(subject.shasum).to eq("2cb8bdd11c766caa11a37607e84ffb51af3ae3da16931988f12f7fc9de98d68e") end end context "when a filepath is not given" do before { subject.send(:remove_instance_variable, :@filepath) } it "returns the correct shasum" do expect(subject.shasum).to eq("3cc6bd98da4d643b79c71be2c93761a458b442e2931f7d421636f526d0c1e8bf") end end end describe "#restore_complete_build" do let(:cached_build) { double(GitCache) } let(:first_software) { double(Omnibus::Software) } let(:last_software) { double(Omnibus::Software) } before do allow(Config).to receive(:use_git_caching).and_return(git_caching) end context "when git caching is enabled" do let(:git_caching) { true } it "restores the last software built" do expect(subject).to receive(:softwares).and_return([first_software, last_software]) expect(GitCache).to receive(:new).with(last_software).and_return(cached_build) expect(cached_build).to receive(:restore_from_cache) subject.restore_complete_build end end context "when git caching is disabled" do let(:git_caching) { false } it "does nothing" do expect(subject).not_to receive(:softwares) expect(GitCache).not_to receive(:new) subject.restore_complete_build end end end end end
32.187082
108
0.634445
185cf460c2c269ffa72dacfea714ca07db8084a6
2,837
# Integer : shrink to zero class Integer def shrink shrunk = if self > 8 self / 2 elsif self > 0 self - 1 elsif self < -8 (self + 1) / 2 elsif self < 0 self + 1 else 0 end shrunk end def retry? false end def shrinkable? self != 0 end end # String : shrink to "" class String def shrink shrunk = dup unless empty? idx = Random.rand(size) shrunk[idx] = '' end shrunk end def retry? false end def shrinkable? self != '' end end # Array where elements can be shrunk but not removed class Tuple def initialize(a) @array = a @position = a.size - 1 end def [](i) @array[i] end def []=(i, value) @array[i] = value end def length @array.length end def size length end def to_s @array.to_s.insert(1, 'T ') end def inspect to_s end def each(&block) @array.each(&block) end attr_reader :array def shrink shrunk = @array.dup while @position >= 0 e = @array.at(@position) break if e.respond_to?(:shrinkable?) && e.shrinkable? @position -= 1 end if @position >= 0 shrunk[@position] = e.shrink @position -= 1 end Tuple.new(shrunk) end def retry? @position >= 0 end def shrinkable? @array.any? { |e| e.respond_to?(:shrinkable?) && e.shrinkable? } end end # Array where the elements that can't be shrunk are removed class Deflating def initialize(a) @array = a @position = a.size - 1 end def [](i) @array[i] end def []=(i, value) @array[i] = value end def length @array.length end def size length end def to_s @array.to_s.insert(1, 'D ') end def inspect to_s end def each(&block) @array.each(&block) end attr_reader :array def shrink shrunk = @array.dup if @position >= 0 e = @array.at(@position) if e.respond_to?(:shrinkable?) && e.shrinkable? shrunk[@position] = e.shrink else shrunk.delete_at(@position) end @position -= 1 end Deflating.new(shrunk) end def retry? @position >= 0 end def shrinkable? [email protected]? end end class Hash def shrink if any? { |_, v| v.respond_to?(:shrinkable?) && v.shrinkable? } key, = detect { |_, v| v.respond_to?(:shrinkable?) && v.shrinkable? } clone = dup clone[key] = clone[key].shrink clone elsif !empty? key = keys.first h2 = dup h2.delete(key) h2 else self end end def shrinkable? any? { |_, v| v.respond_to?(:shrinkable?) && v.shrinkable? } || !empty? end def retry? false end end
14.623711
75
0.541065
081295495b9ac6fad6ef7a1213b37328df2e72b2
106
FactoryGirl.define do factory :daycare do name 'My Daycare' structure 'home' user end end
13.25
21
0.669811
bfedc2f0b504e8d36ff06e69a0858997d1c9e2e2
129
# TODO: NOT WORKING factorial = Proc.new do |num| if num == 1 num else factorial.(num-1) end end p factorial.(5)
10.75
29
0.604651
38bd6da54726e080736a8c92270a48b9350a6443
1,863
# # Copyright (C) 2010-2016 dtk contributors # # This file is part of the dtk project. # # 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 DTK module CommonDSL::Parse class NestedModuleInfo class ImpactedFile attr_reader :path # opts can have keys # :is_dsl_file def initialize(parent, path, opts = {}) @parent = parent @path = path @is_dsl_file = opts[:is_dsl_file] || ret_is_dsl_file?(path) #dyanmically set @content = nil end def is_dsl_file? @is_dsl_file end def content @content ||= RepoManager.get_file_content(@path, @parent.service_module_branch) end private # TODO: DTK-2707 use dtk-dsl library rather than hard coding here TOP_COMPONENT_MODULE_DSL_FILE_REGEXP = /dtk\.model\.yaml$/ [ /dtk\.model\.yaml$/, /dtk\.nested_module\.yaml$/ ] def ret_is_dsl_file?(path) if path =~ TOP_COMPONENT_MODULE_DSL_FILE_REGEXP true elsif path == top_nested_module_dsl_path true else false end end def top_nested_module_dsl_path @parent.top_nested_module_dsl_path end end end end end
26.614286
89
0.615674
08803b4df331a309d75a293c58cbb582760aee39
281
class MacpawGemini < Cask version :latest sha256 :no_check url 'http://dl.devmate.com/download/com.macpaw.site.Gemini/macpaw%20gemini.dmg' appcast 'http://updates.devmate.com/com.macpaw.site.Gemini.xml' homepage 'http://macpaw.com/gemini' app 'MacPaw Gemini.app' end
25.545455
81
0.743772
1c7986db175dba7e679f9c5f0043f46173a8cf8d
403
class CreateFocuses < ActiveRecord::Migration def change create_table :focuses, id: false do |t| t.integer :id, null: false t.string :type, null: false t.string :section t.string :name, null: false t.string :description t.integer :comments_count, default: 0 t.json :data, default: { } t.json :tags, default: { } t.timestamps end end end
25.1875
45
0.620347
39daf84b1a56a09b36f0684ccac707b78ac31b62
1,855
require 'spec_helper' module Refinery module Pages describe ContentPagesHelper, :type => :helper do let(:content_presenter) { double(ContentPresenter, :hide_sections => nil, :fetch_template_overrides => nil, :to_html => nil) } describe "when rendering content presenter" do it "asks to content presenter to hide sections if told to" do expect(content_presenter).to receive(:hide_sections).with(['foo', 'bar']) render_content_presenter(content_presenter, :hide_sections => ['foo', 'bar']) end it "attempts to fetch template overrides declared elsewhere via content_for" do expect(content_presenter).to receive(:fetch_template_overrides).and_yield(12) expect(self).to receive(:content_for).with(12) render_content_presenter(content_presenter) end it "outputs the html rendered by the content presenter" do expect(content_presenter).to receive(:to_html).and_return('foobar') expect(render_content_presenter(content_presenter)).to eq('foobar') end it "passes can_use_fallback option through to html rendering" do expect(content_presenter).to receive(:to_html).with(true) render_content_presenter(content_presenter, :can_use_fallback => true) end end describe "when rendering page" do let(:page) { double(Page) } it "builds a content page presenter and returns its html" do expect(self).to receive(:page_title).and_return('some title') expect(Refinery::Pages::ContentPagePresenter).to receive(:new).with(page, 'some title').and_return(content_presenter) expect(content_presenter).to receive(:to_html).and_return('barfoo') expect(render_content_page(page)).to eq('barfoo') end end end end end
41.222222
132
0.684097
ac98bb40840f47162aff9c51729908da796de9b3
238
class CreateArtists < ActiveRecord::Migration[5.1] def change create_table :artists do |t| t.string :name t.string :genre t.integer :age t.string :hometown end end def up end def down end end
14
50
0.621849
1c74f99cb4a0f7310014825028d4f75d3a85ce7e
2,754
require 'launchpad' interaction = Launchpad::Interaction.new current_color = { :red => :hi, :green => :hi, :mode => :normal } def update_scene_buttons(d, color) on = {:red => :hi, :green => :hi} d.change(:scene1, color[:red] == :hi ? on : {:red => :hi}) d.change(:scene2, color[:red] == :med ? on : {:red => :med}) d.change(:scene3, color[:red] == :lo ? on : {:red => :lo}) d.change(:scene4, color[:red] == :off ? on : {:red => :off}) d.change(:scene5, color[:green] == :hi ? on : {:green => :hi}) d.change(:scene6, color[:green] == :med ? on : {:green => :med}) d.change(:scene7, color[:green] == :lo ? on : {:green => :lo}) d.change(:scene8, color[:green] == :off ? on : {:green => :off}) d.change(:user1, :green => color[:mode] == :normal ? :lo : :hi, :mode => :flashing) d.change(:user2, :green => color[:mode] == :normal ? :hi : :lo) end def choose_color(color, opts) lambda do |interaction, action| color.update(opts) update_scene_buttons(interaction.device, color) end end # register color picker interactors on scene buttons interaction.response_to(:scene1, :down, &choose_color(current_color, :red => :hi)) interaction.response_to(:scene2, :down, &choose_color(current_color, :red => :med)) interaction.response_to(:scene3, :down, &choose_color(current_color, :red => :lo)) interaction.response_to(:scene4, :down, &choose_color(current_color, :red => :off)) interaction.response_to(:scene5, :down, &choose_color(current_color, :green => :hi)) interaction.response_to(:scene6, :down, &choose_color(current_color, :green => :med)) interaction.response_to(:scene7, :down, &choose_color(current_color, :green => :lo)) interaction.response_to(:scene8, :down, &choose_color(current_color, :green => :off)) # register mode picker interactors on user buttons interaction.response_to(:user1, :down, &choose_color(current_color, :mode => :flashing)) interaction.response_to(:user2, :down, &choose_color(current_color, :mode => :normal)) # update scene buttons and start flashing update_scene_buttons(interaction.device, current_color) interaction.device.flashing_auto # feedback for grid buttons interaction.response_to(:grid, :down) do |interaction, action| #coord = 16 * action[:y] + action[:x] #brightness = flags[coord] ? :off : :hi #flags[coord] = !flags[coord] interaction.device.change(:grid, action.merge(current_color)) end # mixer button terminates interaction on button up interaction.response_to(:mixer) do |interaction, action| interaction.device.change(:mixer, :red => action[:state] == :down ? :hi : :off) interaction.stop if action[:state] == :up end # start interacting interaction.start # sleep so that the messages can be sent before the program terminates sleep 0.1
39.913043
88
0.687001
e2f016bd32bb9c993e3e90990d3888d6bf38d075
1,135
module EspSdk class Configure attr_accessor :token, :email, :version, :token_expires_at, :end_point, :domain def initialize(options) self.email = options[:email] self.version = options[:version] || 'v1' self.domain = options[:domain] self.token = options[:password] || options[:token] self.end_point = options[:password].present? ? 'new' : 'valid' token_setup end def url(endpoint) "#{domain}/api/#{version}/#{endpoint}" end def domain return @domain if @domain.present? if EspSdk.production? self.domain = 'https://api.evident.io' elsif EspSdk.release? self.domain = 'https://api-rel.evident.io' else self.domain = 'http://0.0.0.0:3000' end end private def token_setup client = Client.new(self) response = client.connect(url("token/#{end_point}")) user = JSON.load(response.body) self.token = user['authentication_token'] self.token_expires_at = user['token_expires_at'].to_s.to_datetime.utc || 1.hour.from_now.to_datetime.utc end end end
27.682927
82
0.618502
0142bbd34ff1af3fd87d7ed6747c3e87794cb694
1,917
class FontIosevkaSlab < Formula version "2.3.2" sha256 "f0fbec19706f38b9f9b751bb3217883340e64b0f1d004fa84d53c4d65d42e11d" url "https://github.com/be5invis/Iosevka/releases/download/v#{version}/ttc-iosevka-slab-#{version}.zip" desc "Iosevka Slab" homepage "https://github.com/be5invis/Iosevka/" def install (share/"fonts").install "iosevka-slab-bold.ttc" (share/"fonts").install "iosevka-slab-bolditalic.ttc" (share/"fonts").install "iosevka-slab-boldoblique.ttc" (share/"fonts").install "iosevka-slab-extrabold.ttc" (share/"fonts").install "iosevka-slab-extrabolditalic.ttc" (share/"fonts").install "iosevka-slab-extraboldoblique.ttc" (share/"fonts").install "iosevka-slab-extralight.ttc" (share/"fonts").install "iosevka-slab-extralightitalic.ttc" (share/"fonts").install "iosevka-slab-extralightoblique.ttc" (share/"fonts").install "iosevka-slab-heavy.ttc" (share/"fonts").install "iosevka-slab-heavyitalic.ttc" (share/"fonts").install "iosevka-slab-heavyoblique.ttc" (share/"fonts").install "iosevka-slab-italic.ttc" (share/"fonts").install "iosevka-slab-light.ttc" (share/"fonts").install "iosevka-slab-lightitalic.ttc" (share/"fonts").install "iosevka-slab-lightoblique.ttc" (share/"fonts").install "iosevka-slab-medium.ttc" (share/"fonts").install "iosevka-slab-mediumitalic.ttc" (share/"fonts").install "iosevka-slab-mediumoblique.ttc" (share/"fonts").install "iosevka-slab-oblique.ttc" (share/"fonts").install "iosevka-slab-regular.ttc" (share/"fonts").install "iosevka-slab-semibold.ttc" (share/"fonts").install "iosevka-slab-semibolditalic.ttc" (share/"fonts").install "iosevka-slab-semiboldoblique.ttc" (share/"fonts").install "iosevka-slab-thin.ttc" (share/"fonts").install "iosevka-slab-thinitalic.ttc" (share/"fonts").install "iosevka-slab-thinoblique.ttc" end test do end end
49.153846
105
0.718832
1a1eabaa72605a434743b7938097edc2b2b511c8
358
class FontCagliostro < Cask version '0' sha256 '0d205e9a9b34691dca50064ea681404157f1747e39b592fce978b2a32bd5fb61' url 'https://googlefontdirectory.googlecode.com/hg-history/67342bc472599b4c32201ee4a002fe59a6447a42/ofl/cagliostro/Cagliostro-Regular.ttf' homepage 'http://www.google.com/fonts/specimen/Cagliostro' font 'Cagliostro-Regular.ttf' end
35.8
140
0.829609
4ab6a1b73af30376629a81f19a21d91f60e9a423
926
class CreateTwitterUserNewFriendsWorker include Sidekiq::Worker prepend TimeoutableWorker sidekiq_options queue: 'creating_low', retry: 0, backtrace: false def unique_key(twitter_user_id, options = {}) twitter_user_id end def unique_in 10.minutes end def expire_in 10.minutes end def after_expire(*args) logger.warn "The job of #{self.class} is expired args=#{args.inspect}" end def _timeout_in 3.minutes end # options: def perform(twitter_user_id, options = {}) twitter_user = TwitterUser.find(twitter_user_id) if (uids = twitter_user.calc_new_friend_uids) twitter_user.update(new_friends_size: uids.size) CreateNewFriendsCountPointWorker.perform_async(twitter_user_id) end rescue => e logger.warn "#{e.inspect.truncate(100)} twitter_user_id=#{twitter_user_id} options=#{options.inspect}" logger.info e.backtrace.join("\n") end end
23.74359
106
0.728942
4a0e23c618453c8dc9ce78e264a7eb0216a3ad76
2,808
# frozen_string_literal: true module PasswordManager # Convert data between several format (site array, json, encrypted) # Use the given crypters to encrypt / decrypt. # # Converter is build from formated data, # parse and store the data and can be re-use to re-format the data # # Encrypting apply the first crypter and apply the next one. # Decrypting apply the last crypter and apply the previous one. # @private @attr [Array(Site)] data All the site from the given data # @private @attr [Array(Crypter)] crypters Store the crypters to apply class Converter # @!group From # Build the converter from crypted data # @param data [String] Encrypted data # @param crypters [Array(Crypter)] Crypters to use to encrypt / decrypt # @return [Converter] Converter with the site array from the given data def self.from_crypt data, crypters crypters.reverse_each { |crypter| data = crypter.decrypt data } Converter.from_json data, crypters end # Build the converter from json data # @param data [String] Json data # @param crypters [Array(Crypter)] Crypters to use to encrypt / decrypt # @raise [ConverterError] When the data have json formating error # @return [Converter] Converter with the site array from the given data def self.from_json data, crypters data = [].tap do |result| sites = JSON.parse data sites.each do |name, values| extra = values.except 'username', 'password' result.push Site.new name, values['username'], values['password'], extra end end Converter.from_array data, crypters rescue JSON::ParserError raise ConverterError, 'Error: the json provided is invalid' end # Build the converter from site array # @param data [Array(Site)] Site to convert # @param crypters [Array(Crypter)] Crypters to use to encrypt / decrypt # @return [Converter] Converter with the site array from the given data def self.from_array data, crypters; Converter.new data, crypters end # @!endgroup # @deprecated Use {.from_array} instead def initialize data, crypters @crypters = crypters @data = data end # @!group To # @return [Site(Array)] The raw site array def to_array; @data.freeze end # @return [String] The data formated into json string def to_json hash = {}.tap do |result| to_array.each do |site| result[site.name] = site.extra.merge 'username' => site.user, 'password' => site.password end end JSON.generate hash end # @return [String] The data formatted in to encrypted string def to_crypt data = to_json @crypters.each { |crypter| data = crypter.encrypt data } data end end end
33.428571
99
0.672721
391231b60f52da39330bc739cd9f91fa9b533775
430
$LOAD_PATH.unshift(File.expand_path(File.join(__FILE__, "../../../../lib"))) require 'living_dead' def run string = "" LivingDead.trace(string) return nil end run alive_count = LivingDead.traced_objects.select { |tracer| tracer.retained? }.length expected = Integer(ENV["EXPECTED_OUT"] || 0) actual = alive_count result = expected == actual ? "PASS" : "FAIL" puts "#{result}: expected: #{expected}, actual: #{actual}"
21.5
83
0.690698
62a559dd6177106ea94cbcc66ebc7bf31d7287a6
569
require 'rails_helper' RSpec.describe User, type: :model do describe 'A user can be created' do let(:name) { 'simple name' } it 'user is valid if it has name' do user = User.create(name: 'username') expect(user).to be_valid end it 'user is not valid if name is not present' do user = User.create expect(user).to_not be_valid end it 'validation error for missing name on user' do user = User.create(name: nil) user.validate expect(user.errors[:name]).to include("can't be blank") end end end
23.708333
61
0.639719
e28e4fa0936f7e41de4e698f069ade01a6d13e5e
16,290
# frozen_string_literal: true require "formula_installer" require "unpack_strategy" require "cask/topological_hash" require "cask/config" require "cask/download" require "cask/staged" require "cask/verify" require "cask/quarantine" require "cgi" module Cask # Installer for a {Cask}. # # @api private class Installer extend Predicable # TODO: it is unwise for Cask::Staged to be a module, when we are # dealing with both staged and unstaged Casks here. This should # either be a class which is only sometimes instantiated, or there # should be explicit checks on whether staged state is valid in # every method. include Staged def initialize(cask, command: SystemCommand, force: false, skip_cask_deps: false, binaries: true, verbose: false, require_sha: false, upgrade: false, installed_as_dependency: false, quarantine: true) @cask = cask @command = command @force = force @skip_cask_deps = skip_cask_deps @binaries = binaries @verbose = verbose @require_sha = require_sha @reinstall = false @upgrade = upgrade @installed_as_dependency = installed_as_dependency @quarantine = quarantine end attr_predicate :binaries?, :force?, :skip_cask_deps?, :require_sha?, :reinstall?, :upgrade?, :verbose?, :installed_as_dependency?, :quarantine? def self.caveats(cask) odebug "Printing caveats" caveats = cask.caveats return if caveats.empty? <<~EOS #{ohai_title "Caveats"} #{caveats} EOS end def fetch odebug "Cask::Installer#fetch" verify_has_sha if require_sha? && !force? download verify satisfy_dependencies end def stage odebug "Cask::Installer#stage" Caskroom.ensure_caskroom_exists extract_primary_container save_caskfile rescue => e purge_versioned_files raise e end def install odebug "Cask::Installer#install" old_config = @cask.config raise CaskAlreadyInstalledError, @cask if @cask.installed? && !force? && !reinstall? && !upgrade? check_conflicts print caveats fetch uninstall_existing_cask if reinstall? backup if force? && @cask.staged_path.exist? && @cask.metadata_versioned_path.exist? oh1 "Installing Cask #{Formatter.identifier(@cask)}" opoo "macOS's Gatekeeper has been disabled for this Cask" unless quarantine? stage @cask.config = Config.global.merge(old_config) install_artifacts ::Utils::Analytics.report_event("cask_install", @cask.token) unless @cask.tap&.private? purge_backed_up_versioned_files puts summary rescue restore_backup raise end def check_conflicts return unless @cask.conflicts_with @cask.conflicts_with[:cask].each do |conflicting_cask| conflicting_cask = CaskLoader.load(conflicting_cask) raise CaskConflictError.new(@cask, conflicting_cask) if conflicting_cask.installed? rescue CaskUnavailableError next # Ignore conflicting Casks that do not exist. end end def reinstall odebug "Cask::Installer#reinstall" @reinstall = true install end def uninstall_existing_cask return unless @cask.installed? # use the same cask file that was used for installation, if possible installed_caskfile = @cask.installed_caskfile installed_cask = installed_caskfile.exist? ? CaskLoader.load(installed_caskfile) : @cask # Always force uninstallation, ignore method parameter Installer.new(installed_cask, binaries: binaries?, verbose: verbose?, force: true, upgrade: upgrade?).uninstall end def summary s = +"" s << "#{Homebrew::EnvConfig.install_badge} " unless Homebrew::EnvConfig.no_emoji? s << "#{@cask} was successfully #{upgrade? ? "upgraded" : "installed"}!" s.freeze end def download return @downloaded_path if @downloaded_path odebug "Downloading" @downloaded_path = Download.new(@cask, force: false, quarantine: quarantine?).perform odebug "Downloaded to -> #{@downloaded_path}" @downloaded_path end def verify_has_sha odebug "Checking cask has checksum" return unless @cask.sha256 == :no_check raise CaskNoShasumError, @cask.token end def verify Verify.all(@cask, @downloaded_path) end def primary_container @primary_container ||= begin download UnpackStrategy.detect(@downloaded_path, type: @cask.container&.type, merge_xattrs: true) end end def extract_primary_container odebug "Extracting primary container" odebug "Using container class #{primary_container.class} for #{@downloaded_path}" basename = CGI.unescape(File.basename(@cask.url.path)) if nested_container = @cask.container&.nested Dir.mktmpdir do |tmpdir| tmpdir = Pathname(tmpdir) primary_container.extract(to: tmpdir, basename: basename, verbose: verbose?) FileUtils.chmod_R "+rw", tmpdir/nested_container, force: true, verbose: verbose? UnpackStrategy.detect(tmpdir/nested_container, merge_xattrs: true) .extract_nestedly(to: @cask.staged_path, verbose: verbose?) end else primary_container.extract_nestedly(to: @cask.staged_path, basename: basename, verbose: verbose?) end return unless quarantine? return unless Quarantine.available? Quarantine.propagate(from: @downloaded_path, to: @cask.staged_path) end def install_artifacts already_installed_artifacts = [] odebug "Installing artifacts" artifacts = @cask.artifacts odebug "#{artifacts.length} artifact/s defined", artifacts artifacts.each do |artifact| next unless artifact.respond_to?(:install_phase) odebug "Installing artifact of class #{artifact.class}" if artifact.is_a?(Artifact::Binary) next unless binaries? end artifact.install_phase(command: @command, verbose: verbose?, force: force?) already_installed_artifacts.unshift(artifact) end save_config_file rescue => e begin already_installed_artifacts.each do |artifact| next unless artifact.respond_to?(:uninstall_phase) odebug "Reverting installation of artifact of class #{artifact.class}" artifact.uninstall_phase(command: @command, verbose: verbose?, force: force?) end already_installed_artifacts.each do |artifact| next unless artifact.respond_to?(:post_uninstall_phase) odebug "Reverting installation of artifact of class #{artifact.class}" artifact.post_uninstall_phase(command: @command, verbose: verbose?, force: force?) end ensure purge_versioned_files raise e end end # TODO: move dependencies to a separate class, # dependencies should also apply for `brew cask stage`, # override dependencies with `--force` or perhaps `--force-deps` def satisfy_dependencies return unless @cask.depends_on macos_dependencies arch_dependencies x11_dependencies cask_and_formula_dependencies end def macos_dependencies return unless @cask.depends_on.macos return if @cask.depends_on.macos.satisfied? raise CaskError, @cask.depends_on.macos.message(type: :cask) end def arch_dependencies return if @cask.depends_on.arch.nil? @current_arch ||= { type: Hardware::CPU.type, bits: Hardware::CPU.bits } return if @cask.depends_on.arch.any? do |arch| arch[:type] == @current_arch[:type] && Array(arch[:bits]).include?(@current_arch[:bits]) end raise CaskError, "Cask #{@cask} depends on hardware architecture being one of " \ "[#{@cask.depends_on.arch.map(&:to_s).join(", ")}], " \ "but you are running #{@current_arch}" end def x11_dependencies return unless @cask.depends_on.x11 raise CaskX11DependencyError, @cask.token unless MacOS::X11.installed? end def graph_dependencies(cask_or_formula, acc = TopologicalHash.new) return acc if acc.key?(cask_or_formula) if cask_or_formula.is_a?(Cask) formula_deps = cask_or_formula.depends_on.formula.map { |f| Formula[f] } cask_deps = cask_or_formula.depends_on.cask.map(&CaskLoader.public_method(:load)) else formula_deps = cask_or_formula.deps.reject(&:build?).map(&:to_formula) cask_deps = cask_or_formula.requirements.map(&:cask).compact.map(&CaskLoader.public_method(:load)) end acc[cask_or_formula] ||= [] acc[cask_or_formula] += formula_deps acc[cask_or_formula] += cask_deps formula_deps.each do |f| graph_dependencies(f, acc) end cask_deps.each do |c| graph_dependencies(c, acc) end acc end def collect_cask_and_formula_dependencies return @cask_and_formula_dependencies if @cask_and_formula_dependencies graph = graph_dependencies(@cask) raise CaskSelfReferencingDependencyError, cask.token if graph[@cask].include?(@cask) primary_container.dependencies.each do |dep| graph_dependencies(dep, graph) end begin @cask_and_formula_dependencies = graph.tsort - [@cask] rescue TSort::Cyclic strongly_connected_components = graph.strongly_connected_components.sort_by(&:count) cyclic_dependencies = strongly_connected_components.last - [@cask] raise CaskCyclicDependencyError.new(@cask.token, cyclic_dependencies.to_sentence) end end def missing_cask_and_formula_dependencies collect_cask_and_formula_dependencies.reject do |cask_or_formula| installed = if cask_or_formula.respond_to?(:any_version_installed?) cask_or_formula.any_version_installed? else cask_or_formula.try(:installed?) end installed && (cask_or_formula.respond_to?(:opt_linked?) ? cask_or_formula.opt_linked? : true) end end def cask_and_formula_dependencies return if installed_as_dependency? formulae_and_casks = collect_cask_and_formula_dependencies return if formulae_and_casks.empty? missing_formulae_and_casks = missing_cask_and_formula_dependencies if missing_formulae_and_casks.empty? puts "All Formula dependencies satisfied." return end ohai "Installing dependencies: #{missing_formulae_and_casks.map(&:to_s).join(", ")}" missing_formulae_and_casks.each do |cask_or_formula| if cask_or_formula.is_a?(Cask) if skip_cask_deps? opoo "`--skip-cask-deps` is set; skipping installation of #{@cask}." next end Installer.new( cask_or_formula, binaries: binaries?, verbose: verbose?, installed_as_dependency: true, force: false, ).install else FormulaInstaller.new(cask_or_formula, verbose: verbose?).yield_self do |fi| fi.installed_as_dependency = true fi.installed_on_request = false fi.show_header = true fi.prelude fi.fetch fi.install fi.finish end end end end def caveats self.class.caveats(@cask) end def save_caskfile old_savedir = @cask.metadata_timestamped_path return unless @cask.sourcefile_path savedir = @cask.metadata_subdir("Casks", timestamp: :now, create: true) FileUtils.copy @cask.sourcefile_path, savedir old_savedir&.rmtree end def save_config_file @cask.config_path.atomic_write(@cask.config.to_json) end def uninstall oh1 "Uninstalling Cask #{Formatter.identifier(@cask)}" uninstall_artifacts(clear: true) remove_config_file unless reinstall? || upgrade? purge_versioned_files purge_caskroom_path if force? end def remove_config_file FileUtils.rm_f @cask.config_path @cask.config_path.parent.rmdir_if_possible end def start_upgrade uninstall_artifacts backup end def backup @cask.staged_path.rename backup_path @cask.metadata_versioned_path.rename backup_metadata_path end def restore_backup return unless backup_path.directory? && backup_metadata_path.directory? Pathname.new(@cask.staged_path).rmtree if @cask.staged_path.exist? Pathname.new(@cask.metadata_versioned_path).rmtree if @cask.metadata_versioned_path.exist? backup_path.rename @cask.staged_path backup_metadata_path.rename @cask.metadata_versioned_path end def revert_upgrade opoo "Reverting upgrade for Cask #{@cask}" restore_backup install_artifacts end def finalize_upgrade ohai "Purging files for version #{@cask.version} of Cask #{@cask}" purge_backed_up_versioned_files puts summary end def uninstall_artifacts(clear: false) odebug "Uninstalling artifacts" artifacts = @cask.artifacts odebug "#{artifacts.length} artifact/s defined", artifacts artifacts.each do |artifact| next unless artifact.respond_to?(:uninstall_phase) odebug "Uninstalling artifact of class #{artifact.class}" artifact.uninstall_phase(command: @command, verbose: verbose?, skip: clear, force: force?, upgrade: upgrade?) end artifacts.each do |artifact| next unless artifact.respond_to?(:post_uninstall_phase) odebug "Post-uninstalling artifact of class #{artifact.class}" artifact.post_uninstall_phase( command: @command, verbose: verbose?, skip: clear, force: force?, upgrade: upgrade?, ) end end def zap ohai %Q(Implied "brew cask uninstall #{@cask}") uninstall_artifacts if (zap_stanzas = @cask.artifacts.select { |a| a.is_a?(Artifact::Zap) }).empty? opoo "No zap stanza present for Cask '#{@cask}'" else ohai "Dispatching zap stanza" zap_stanzas.each do |stanza| stanza.zap_phase(command: @command, verbose: verbose?, force: force?) end end ohai "Removing all staged versions of Cask '#{@cask}'" purge_caskroom_path end def backup_path return if @cask.staged_path.nil? Pathname("#{@cask.staged_path}.upgrading") end def backup_metadata_path return if @cask.metadata_versioned_path.nil? Pathname("#{@cask.metadata_versioned_path}.upgrading") end def gain_permissions_remove(path) Utils.gain_permissions_remove(path, command: @command) end def purge_backed_up_versioned_files # versioned staged distribution gain_permissions_remove(backup_path) if backup_path&.exist? # Homebrew Cask metadata return unless backup_metadata_path.directory? backup_metadata_path.children.each do |subdir| gain_permissions_remove(subdir) end backup_metadata_path.rmdir_if_possible end def purge_versioned_files ohai "Purging files for version #{@cask.version} of Cask #{@cask}" # versioned staged distribution gain_permissions_remove(@cask.staged_path) if @cask.staged_path&.exist? # Homebrew Cask metadata if @cask.metadata_versioned_path.directory? @cask.metadata_versioned_path.children.each do |subdir| gain_permissions_remove(subdir) end @cask.metadata_versioned_path.rmdir_if_possible end @cask.metadata_master_container_path.rmdir_if_possible unless upgrade? # toplevel staged distribution @cask.caskroom_path.rmdir_if_possible unless upgrade? end def purge_caskroom_path odebug "Purging all staged versions of Cask #{@cask}" gain_permissions_remove(@cask.caskroom_path) end end end
29.944853
117
0.669982
bf951cd60b3c2c5067a95fd5e897ae8e5f311570
36,843
# WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE require 'seahorse/client/plugins/content_length.rb' require 'aws-sdk-core/plugins/credentials_configuration.rb' require 'aws-sdk-core/plugins/logging.rb' require 'aws-sdk-core/plugins/param_converter.rb' require 'aws-sdk-core/plugins/param_validator.rb' require 'aws-sdk-core/plugins/user_agent.rb' require 'aws-sdk-core/plugins/helpful_socket_errors.rb' require 'aws-sdk-core/plugins/retry_errors.rb' require 'aws-sdk-core/plugins/global_configuration.rb' require 'aws-sdk-core/plugins/regional_endpoint.rb' require 'aws-sdk-core/plugins/response_paging.rb' require 'aws-sdk-core/plugins/stub_responses.rb' require 'aws-sdk-core/plugins/idempotency_token.rb' require 'aws-sdk-core/plugins/jsonvalue_converter.rb' require 'aws-sdk-core/plugins/signature_v4.rb' require 'aws-sdk-core/plugins/protocols/rest_json.rb' Aws::Plugins::GlobalConfiguration.add_identifier(:mq) module Aws::MQ class Client < Seahorse::Client::Base include Aws::ClientStubs @identifier = :mq set_api(ClientApi::API) add_plugin(Seahorse::Client::Plugins::ContentLength) add_plugin(Aws::Plugins::CredentialsConfiguration) add_plugin(Aws::Plugins::Logging) add_plugin(Aws::Plugins::ParamConverter) add_plugin(Aws::Plugins::ParamValidator) add_plugin(Aws::Plugins::UserAgent) add_plugin(Aws::Plugins::HelpfulSocketErrors) add_plugin(Aws::Plugins::RetryErrors) add_plugin(Aws::Plugins::GlobalConfiguration) add_plugin(Aws::Plugins::RegionalEndpoint) add_plugin(Aws::Plugins::ResponsePaging) add_plugin(Aws::Plugins::StubResponses) add_plugin(Aws::Plugins::IdempotencyToken) add_plugin(Aws::Plugins::JsonvalueConverter) add_plugin(Aws::Plugins::SignatureV4) add_plugin(Aws::Plugins::Protocols::RestJson) # @option options [required, Aws::CredentialProvider] :credentials # Your AWS credentials. This can be an instance of any one of the # following classes: # # * `Aws::Credentials` - Used for configuring static, non-refreshing # credentials. # # * `Aws::InstanceProfileCredentials` - Used for loading credentials # from an EC2 IMDS on an EC2 instance. # # * `Aws::SharedCredentials` - Used for loading credentials from a # shared file, such as `~/.aws/config`. # # * `Aws::AssumeRoleCredentials` - Used when you need to assume a role. # # When `:credentials` are not configured directly, the following # locations will be searched for credentials: # # * `Aws.config[:credentials]` # * The `:access_key_id`, `:secret_access_key`, and `:session_token` options. # * ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'] # * `~/.aws/credentials` # * `~/.aws/config` # * EC2 IMDS instance profile - When used by default, the timeouts are # very aggressive. Construct and pass an instance of # `Aws::InstanceProfileCredentails` to enable retries and extended # timeouts. # # @option options [required, String] :region # The AWS region to connect to. The configured `:region` is # used to determine the service `:endpoint`. When not passed, # a default `:region` is search for in the following locations: # # * `Aws.config[:region]` # * `ENV['AWS_REGION']` # * `ENV['AMAZON_REGION']` # * `ENV['AWS_DEFAULT_REGION']` # * `~/.aws/credentials` # * `~/.aws/config` # # @option options [String] :access_key_id # # @option options [Boolean] :convert_params (true) # When `true`, an attempt is made to coerce request parameters into # the required types. # # @option options [String] :endpoint # The client endpoint is normally constructed from the `:region` # option. You should only configure an `:endpoint` when connecting # to test endpoints. This should be avalid HTTP(S) URI. # # @option options [Aws::Log::Formatter] :log_formatter (Aws::Log::Formatter.default) # The log formatter. # # @option options [Symbol] :log_level (:info) # The log level to send messages to the `:logger` at. # # @option options [Logger] :logger # The Logger instance to send log messages to. If this option # is not set, logging will be disabled. # # @option options [String] :profile ("default") # Used when loading credentials from the shared credentials file # at HOME/.aws/credentials. When not specified, 'default' is used. # # @option options [Float] :retry_base_delay (0.3) # The base delay in seconds used by the default backoff function. # # @option options [Symbol] :retry_jitter (:none) # A delay randomiser function used by the default backoff function. Some predefined functions can be referenced by name - :none, :equal, :full, otherwise a Proc that takes and returns a number. # # @see https://www.awsarchitectureblog.com/2015/03/backoff.html # # @option options [Integer] :retry_limit (3) # The maximum number of times to retry failed requests. Only # ~ 500 level server errors and certain ~ 400 level client errors # are retried. Generally, these are throttling errors, data # checksum errors, networking errors, timeout errors and auth # errors from expired credentials. # # @option options [Integer] :retry_max_delay (0) # The maximum number of seconds to delay between retries (0 for no limit) used by the default backoff function. # # @option options [String] :secret_access_key # # @option options [String] :session_token # # @option options [Boolean] :stub_responses (false) # Causes the client to return stubbed responses. By default # fake responses are generated and returned. You can specify # the response data to return or errors to raise by calling # {ClientStubs#stub_responses}. See {ClientStubs} for more information. # # ** Please note ** When response stubbing is enabled, no HTTP # requests are made, and retries are disabled. # # @option options [Boolean] :validate_params (true) # When `true`, request parameters are validated before # sending the request. # def initialize(*args) super end # @!group API Operations # Creates a broker. Note: This API is asynchronous. # # @option params [Boolean] :auto_minor_version_upgrade # # @option params [String] :broker_name # # @option params [Types::ConfigurationId] :configuration # A list of information about the configuration. # # @option params [String] :creator_request_id # **A suitable default value is auto-generated.** You should normally # not need to pass this option.** # # @option params [String] :deployment_mode # The deployment mode of the broker. # # @option params [String] :engine_type # The type of broker engine. Note: Currently, Amazon MQ supports only # ActiveMQ. # # @option params [String] :engine_version # # @option params [String] :host_instance_type # # @option params [Types::Logs] :logs # The list of information about logs to be enabled for the specified # broker. # # @option params [Types::WeeklyStartTime] :maintenance_window_start_time # The scheduled time period relative to UTC during which Amazon MQ # begins to apply pending updates or patches to the broker. # # @option params [Boolean] :publicly_accessible # # @option params [Array<String>] :security_groups # # @option params [Array<String>] :subnet_ids # # @option params [Array<Types::User>] :users # # @return [Types::CreateBrokerResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::CreateBrokerResponse#broker_arn #broker_arn} => String # * {Types::CreateBrokerResponse#broker_id #broker_id} => String # # @example Request syntax with placeholder values # # resp = client.create_broker({ # auto_minor_version_upgrade: false, # broker_name: "__string", # configuration: { # id: "__string", # revision: 1, # }, # creator_request_id: "__string", # deployment_mode: "SINGLE_INSTANCE", # accepts SINGLE_INSTANCE, ACTIVE_STANDBY_MULTI_AZ # engine_type: "ACTIVEMQ", # accepts ACTIVEMQ # engine_version: "__string", # host_instance_type: "__string", # logs: { # audit: false, # general: false, # }, # maintenance_window_start_time: { # day_of_week: "MONDAY", # accepts MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY # time_of_day: "__string", # time_zone: "__string", # }, # publicly_accessible: false, # security_groups: ["__string"], # subnet_ids: ["__string"], # users: [ # { # console_access: false, # groups: ["__string"], # password: "__string", # username: "__string", # }, # ], # }) # # @example Response structure # # resp.broker_arn #=> String # resp.broker_id #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/CreateBroker AWS API Documentation # # @overload create_broker(params = {}) # @param [Hash] params ({}) def create_broker(params = {}, options = {}) req = build_request(:create_broker, params) req.send_request(options) end # Creates a new configuration for the specified configuration name. # Amazon MQ uses the default configuration (the engine type and # version). # # @option params [String] :engine_type # The type of broker engine. Note: Currently, Amazon MQ supports only # ActiveMQ. # # @option params [String] :engine_version # # @option params [String] :name # # @return [Types::CreateConfigurationResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::CreateConfigurationResponse#arn #arn} => String # * {Types::CreateConfigurationResponse#created #created} => Time # * {Types::CreateConfigurationResponse#id #id} => String # * {Types::CreateConfigurationResponse#latest_revision #latest_revision} => Types::ConfigurationRevision # * {Types::CreateConfigurationResponse#name #name} => String # # @example Request syntax with placeholder values # # resp = client.create_configuration({ # engine_type: "ACTIVEMQ", # accepts ACTIVEMQ # engine_version: "__string", # name: "__string", # }) # # @example Response structure # # resp.arn #=> String # resp.created #=> Time # resp.id #=> String # resp.latest_revision.created #=> Time # resp.latest_revision.description #=> String # resp.latest_revision.revision #=> Integer # resp.name #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/CreateConfiguration AWS API Documentation # # @overload create_configuration(params = {}) # @param [Hash] params ({}) def create_configuration(params = {}, options = {}) req = build_request(:create_configuration, params) req.send_request(options) end # Creates an ActiveMQ user. # # @option params [required, String] :broker_id # # @option params [Boolean] :console_access # # @option params [Array<String>] :groups # # @option params [String] :password # # @option params [required, String] :username # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.create_user({ # broker_id: "__string", # required # console_access: false, # groups: ["__string"], # password: "__string", # username: "__string", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/CreateUser AWS API Documentation # # @overload create_user(params = {}) # @param [Hash] params ({}) def create_user(params = {}, options = {}) req = build_request(:create_user, params) req.send_request(options) end # Deletes a broker. Note: This API is asynchronous. # # @option params [required, String] :broker_id # # @return [Types::DeleteBrokerResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::DeleteBrokerResponse#broker_id #broker_id} => String # # @example Request syntax with placeholder values # # resp = client.delete_broker({ # broker_id: "__string", # required # }) # # @example Response structure # # resp.broker_id #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DeleteBroker AWS API Documentation # # @overload delete_broker(params = {}) # @param [Hash] params ({}) def delete_broker(params = {}, options = {}) req = build_request(:delete_broker, params) req.send_request(options) end # Deletes an ActiveMQ user. # # @option params [required, String] :broker_id # # @option params [required, String] :username # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.delete_user({ # broker_id: "__string", # required # username: "__string", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DeleteUser AWS API Documentation # # @overload delete_user(params = {}) # @param [Hash] params ({}) def delete_user(params = {}, options = {}) req = build_request(:delete_user, params) req.send_request(options) end # Returns information about the specified broker. # # @option params [required, String] :broker_id # # @return [Types::DescribeBrokerResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::DescribeBrokerResponse#auto_minor_version_upgrade #auto_minor_version_upgrade} => Boolean # * {Types::DescribeBrokerResponse#broker_arn #broker_arn} => String # * {Types::DescribeBrokerResponse#broker_id #broker_id} => String # * {Types::DescribeBrokerResponse#broker_instances #broker_instances} => Array&lt;Types::BrokerInstance&gt; # * {Types::DescribeBrokerResponse#broker_name #broker_name} => String # * {Types::DescribeBrokerResponse#broker_state #broker_state} => String # * {Types::DescribeBrokerResponse#configurations #configurations} => Types::Configurations # * {Types::DescribeBrokerResponse#created #created} => Time # * {Types::DescribeBrokerResponse#deployment_mode #deployment_mode} => String # * {Types::DescribeBrokerResponse#engine_type #engine_type} => String # * {Types::DescribeBrokerResponse#engine_version #engine_version} => String # * {Types::DescribeBrokerResponse#host_instance_type #host_instance_type} => String # * {Types::DescribeBrokerResponse#logs #logs} => Types::LogsSummary # * {Types::DescribeBrokerResponse#maintenance_window_start_time #maintenance_window_start_time} => Types::WeeklyStartTime # * {Types::DescribeBrokerResponse#publicly_accessible #publicly_accessible} => Boolean # * {Types::DescribeBrokerResponse#security_groups #security_groups} => Array&lt;String&gt; # * {Types::DescribeBrokerResponse#subnet_ids #subnet_ids} => Array&lt;String&gt; # * {Types::DescribeBrokerResponse#users #users} => Array&lt;Types::UserSummary&gt; # # @example Request syntax with placeholder values # # resp = client.describe_broker({ # broker_id: "__string", # required # }) # # @example Response structure # # resp.auto_minor_version_upgrade #=> Boolean # resp.broker_arn #=> String # resp.broker_id #=> String # resp.broker_instances #=> Array # resp.broker_instances[0].console_url #=> String # resp.broker_instances[0].endpoints #=> Array # resp.broker_instances[0].endpoints[0] #=> String # resp.broker_instances[0].ip_address #=> String # resp.broker_name #=> String # resp.broker_state #=> String, one of "CREATION_IN_PROGRESS", "CREATION_FAILED", "DELETION_IN_PROGRESS", "RUNNING", "REBOOT_IN_PROGRESS" # resp.configurations.current.id #=> String # resp.configurations.current.revision #=> Integer # resp.configurations.history #=> Array # resp.configurations.history[0].id #=> String # resp.configurations.history[0].revision #=> Integer # resp.configurations.pending.id #=> String # resp.configurations.pending.revision #=> Integer # resp.created #=> Time # resp.deployment_mode #=> String, one of "SINGLE_INSTANCE", "ACTIVE_STANDBY_MULTI_AZ" # resp.engine_type #=> String, one of "ACTIVEMQ" # resp.engine_version #=> String # resp.host_instance_type #=> String # resp.logs.audit #=> Boolean # resp.logs.audit_log_group #=> String # resp.logs.general #=> Boolean # resp.logs.general_log_group #=> String # resp.logs.pending.audit #=> Boolean # resp.logs.pending.general #=> Boolean # resp.maintenance_window_start_time.day_of_week #=> String, one of "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY" # resp.maintenance_window_start_time.time_of_day #=> String # resp.maintenance_window_start_time.time_zone #=> String # resp.publicly_accessible #=> Boolean # resp.security_groups #=> Array # resp.security_groups[0] #=> String # resp.subnet_ids #=> Array # resp.subnet_ids[0] #=> String # resp.users #=> Array # resp.users[0].pending_change #=> String, one of "CREATE", "UPDATE", "DELETE" # resp.users[0].username #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeBroker AWS API Documentation # # @overload describe_broker(params = {}) # @param [Hash] params ({}) def describe_broker(params = {}, options = {}) req = build_request(:describe_broker, params) req.send_request(options) end # Returns information about the specified configuration. # # @option params [required, String] :configuration_id # # @return [Types::DescribeConfigurationResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::DescribeConfigurationResponse#arn #arn} => String # * {Types::DescribeConfigurationResponse#created #created} => Time # * {Types::DescribeConfigurationResponse#description #description} => String # * {Types::DescribeConfigurationResponse#engine_type #engine_type} => String # * {Types::DescribeConfigurationResponse#engine_version #engine_version} => String # * {Types::DescribeConfigurationResponse#id #id} => String # * {Types::DescribeConfigurationResponse#latest_revision #latest_revision} => Types::ConfigurationRevision # * {Types::DescribeConfigurationResponse#name #name} => String # # @example Request syntax with placeholder values # # resp = client.describe_configuration({ # configuration_id: "__string", # required # }) # # @example Response structure # # resp.arn #=> String # resp.created #=> Time # resp.description #=> String # resp.engine_type #=> String, one of "ACTIVEMQ" # resp.engine_version #=> String # resp.id #=> String # resp.latest_revision.created #=> Time # resp.latest_revision.description #=> String # resp.latest_revision.revision #=> Integer # resp.name #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeConfiguration AWS API Documentation # # @overload describe_configuration(params = {}) # @param [Hash] params ({}) def describe_configuration(params = {}, options = {}) req = build_request(:describe_configuration, params) req.send_request(options) end # Returns the specified configuration revision for the specified # configuration. # # @option params [required, String] :configuration_id # # @option params [required, String] :configuration_revision # # @return [Types::DescribeConfigurationRevisionResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::DescribeConfigurationRevisionResponse#configuration_id #configuration_id} => String # * {Types::DescribeConfigurationRevisionResponse#created #created} => Time # * {Types::DescribeConfigurationRevisionResponse#data #data} => String # * {Types::DescribeConfigurationRevisionResponse#description #description} => String # # @example Request syntax with placeholder values # # resp = client.describe_configuration_revision({ # configuration_id: "__string", # required # configuration_revision: "__string", # required # }) # # @example Response structure # # resp.configuration_id #=> String # resp.created #=> Time # resp.data #=> String # resp.description #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeConfigurationRevision AWS API Documentation # # @overload describe_configuration_revision(params = {}) # @param [Hash] params ({}) def describe_configuration_revision(params = {}, options = {}) req = build_request(:describe_configuration_revision, params) req.send_request(options) end # Returns information about an ActiveMQ user. # # @option params [required, String] :broker_id # # @option params [required, String] :username # # @return [Types::DescribeUserResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::DescribeUserResponse#broker_id #broker_id} => String # * {Types::DescribeUserResponse#console_access #console_access} => Boolean # * {Types::DescribeUserResponse#groups #groups} => Array&lt;String&gt; # * {Types::DescribeUserResponse#pending #pending} => Types::UserPendingChanges # * {Types::DescribeUserResponse#username #username} => String # # @example Request syntax with placeholder values # # resp = client.describe_user({ # broker_id: "__string", # required # username: "__string", # required # }) # # @example Response structure # # resp.broker_id #=> String # resp.console_access #=> Boolean # resp.groups #=> Array # resp.groups[0] #=> String # resp.pending.console_access #=> Boolean # resp.pending.groups #=> Array # resp.pending.groups[0] #=> String # resp.pending.pending_change #=> String, one of "CREATE", "UPDATE", "DELETE" # resp.username #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/DescribeUser AWS API Documentation # # @overload describe_user(params = {}) # @param [Hash] params ({}) def describe_user(params = {}, options = {}) req = build_request(:describe_user, params) req.send_request(options) end # Returns a list of all brokers. # # @option params [Integer] :max_results # # @option params [String] :next_token # # @return [Types::ListBrokersResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListBrokersResponse#broker_summaries #broker_summaries} => Array&lt;Types::BrokerSummary&gt; # * {Types::ListBrokersResponse#next_token #next_token} => String # # @example Request syntax with placeholder values # # resp = client.list_brokers({ # max_results: 1, # next_token: "__string", # }) # # @example Response structure # # resp.broker_summaries #=> Array # resp.broker_summaries[0].broker_arn #=> String # resp.broker_summaries[0].broker_id #=> String # resp.broker_summaries[0].broker_name #=> String # resp.broker_summaries[0].broker_state #=> String, one of "CREATION_IN_PROGRESS", "CREATION_FAILED", "DELETION_IN_PROGRESS", "RUNNING", "REBOOT_IN_PROGRESS" # resp.broker_summaries[0].created #=> Time # resp.broker_summaries[0].deployment_mode #=> String, one of "SINGLE_INSTANCE", "ACTIVE_STANDBY_MULTI_AZ" # resp.broker_summaries[0].host_instance_type #=> String # resp.next_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/ListBrokers AWS API Documentation # # @overload list_brokers(params = {}) # @param [Hash] params ({}) def list_brokers(params = {}, options = {}) req = build_request(:list_brokers, params) req.send_request(options) end # Returns a list of all revisions for the specified configuration. # # @option params [required, String] :configuration_id # # @option params [Integer] :max_results # # @option params [String] :next_token # # @return [Types::ListConfigurationRevisionsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListConfigurationRevisionsResponse#configuration_id #configuration_id} => String # * {Types::ListConfigurationRevisionsResponse#max_results #max_results} => Integer # * {Types::ListConfigurationRevisionsResponse#next_token #next_token} => String # * {Types::ListConfigurationRevisionsResponse#revisions #revisions} => Array&lt;Types::ConfigurationRevision&gt; # # @example Request syntax with placeholder values # # resp = client.list_configuration_revisions({ # configuration_id: "__string", # required # max_results: 1, # next_token: "__string", # }) # # @example Response structure # # resp.configuration_id #=> String # resp.max_results #=> Integer # resp.next_token #=> String # resp.revisions #=> Array # resp.revisions[0].created #=> Time # resp.revisions[0].description #=> String # resp.revisions[0].revision #=> Integer # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/ListConfigurationRevisions AWS API Documentation # # @overload list_configuration_revisions(params = {}) # @param [Hash] params ({}) def list_configuration_revisions(params = {}, options = {}) req = build_request(:list_configuration_revisions, params) req.send_request(options) end # Returns a list of all configurations. # # @option params [Integer] :max_results # # @option params [String] :next_token # # @return [Types::ListConfigurationsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListConfigurationsResponse#configurations #configurations} => Array&lt;Types::Configuration&gt; # * {Types::ListConfigurationsResponse#max_results #max_results} => Integer # * {Types::ListConfigurationsResponse#next_token #next_token} => String # # @example Request syntax with placeholder values # # resp = client.list_configurations({ # max_results: 1, # next_token: "__string", # }) # # @example Response structure # # resp.configurations #=> Array # resp.configurations[0].arn #=> String # resp.configurations[0].created #=> Time # resp.configurations[0].description #=> String # resp.configurations[0].engine_type #=> String, one of "ACTIVEMQ" # resp.configurations[0].engine_version #=> String # resp.configurations[0].id #=> String # resp.configurations[0].latest_revision.created #=> Time # resp.configurations[0].latest_revision.description #=> String # resp.configurations[0].latest_revision.revision #=> Integer # resp.configurations[0].name #=> String # resp.max_results #=> Integer # resp.next_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/ListConfigurations AWS API Documentation # # @overload list_configurations(params = {}) # @param [Hash] params ({}) def list_configurations(params = {}, options = {}) req = build_request(:list_configurations, params) req.send_request(options) end # Returns a list of all ActiveMQ users. # # @option params [required, String] :broker_id # # @option params [Integer] :max_results # # @option params [String] :next_token # # @return [Types::ListUsersResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListUsersResponse#broker_id #broker_id} => String # * {Types::ListUsersResponse#max_results #max_results} => Integer # * {Types::ListUsersResponse#next_token #next_token} => String # * {Types::ListUsersResponse#users #users} => Array&lt;Types::UserSummary&gt; # # @example Request syntax with placeholder values # # resp = client.list_users({ # broker_id: "__string", # required # max_results: 1, # next_token: "__string", # }) # # @example Response structure # # resp.broker_id #=> String # resp.max_results #=> Integer # resp.next_token #=> String # resp.users #=> Array # resp.users[0].pending_change #=> String, one of "CREATE", "UPDATE", "DELETE" # resp.users[0].username #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/ListUsers AWS API Documentation # # @overload list_users(params = {}) # @param [Hash] params ({}) def list_users(params = {}, options = {}) req = build_request(:list_users, params) req.send_request(options) end # Reboots a broker. Note: This API is asynchronous. # # @option params [required, String] :broker_id # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.reboot_broker({ # broker_id: "__string", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/RebootBroker AWS API Documentation # # @overload reboot_broker(params = {}) # @param [Hash] params ({}) def reboot_broker(params = {}, options = {}) req = build_request(:reboot_broker, params) req.send_request(options) end # Adds a pending configuration change to a broker. # # @option params [required, String] :broker_id # # @option params [Types::ConfigurationId] :configuration # A list of information about the configuration. # # @option params [Types::Logs] :logs # The list of information about logs to be enabled for the specified # broker. # # @return [Types::UpdateBrokerResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::UpdateBrokerResponse#broker_id #broker_id} => String # * {Types::UpdateBrokerResponse#configuration #configuration} => Types::ConfigurationId # * {Types::UpdateBrokerResponse#logs #logs} => Types::Logs # # @example Request syntax with placeholder values # # resp = client.update_broker({ # broker_id: "__string", # required # configuration: { # id: "__string", # revision: 1, # }, # logs: { # audit: false, # general: false, # }, # }) # # @example Response structure # # resp.broker_id #=> String # resp.configuration.id #=> String # resp.configuration.revision #=> Integer # resp.logs.audit #=> Boolean # resp.logs.general #=> Boolean # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/UpdateBroker AWS API Documentation # # @overload update_broker(params = {}) # @param [Hash] params ({}) def update_broker(params = {}, options = {}) req = build_request(:update_broker, params) req.send_request(options) end # Updates the specified configuration. # # @option params [required, String] :configuration_id # # @option params [String] :data # # @option params [String] :description # # @return [Types::UpdateConfigurationResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::UpdateConfigurationResponse#arn #arn} => String # * {Types::UpdateConfigurationResponse#created #created} => Time # * {Types::UpdateConfigurationResponse#id #id} => String # * {Types::UpdateConfigurationResponse#latest_revision #latest_revision} => Types::ConfigurationRevision # * {Types::UpdateConfigurationResponse#name #name} => String # * {Types::UpdateConfigurationResponse#warnings #warnings} => Array&lt;Types::SanitizationWarning&gt; # # @example Request syntax with placeholder values # # resp = client.update_configuration({ # configuration_id: "__string", # required # data: "__string", # description: "__string", # }) # # @example Response structure # # resp.arn #=> String # resp.created #=> Time # resp.id #=> String # resp.latest_revision.created #=> Time # resp.latest_revision.description #=> String # resp.latest_revision.revision #=> Integer # resp.name #=> String # resp.warnings #=> Array # resp.warnings[0].attribute_name #=> String # resp.warnings[0].element_name #=> String # resp.warnings[0].reason #=> String, one of "DISALLOWED_ELEMENT_REMOVED", "DISALLOWED_ATTRIBUTE_REMOVED", "INVALID_ATTRIBUTE_VALUE_REMOVED" # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/UpdateConfiguration AWS API Documentation # # @overload update_configuration(params = {}) # @param [Hash] params ({}) def update_configuration(params = {}, options = {}) req = build_request(:update_configuration, params) req.send_request(options) end # Updates the information for an ActiveMQ user. # # @option params [required, String] :broker_id # # @option params [Boolean] :console_access # # @option params [Array<String>] :groups # # @option params [String] :password # # @option params [required, String] :username # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.update_user({ # broker_id: "__string", # required # console_access: false, # groups: ["__string"], # password: "__string", # username: "__string", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/UpdateUser AWS API Documentation # # @overload update_user(params = {}) # @param [Hash] params ({}) def update_user(params = {}, options = {}) req = build_request(:update_user, params) req.send_request(options) end # @!endgroup # @param params ({}) # @api private def build_request(operation_name, params = {}) handlers = @handlers.for(operation_name) context = Seahorse::Client::RequestContext.new( operation_name: operation_name, operation: config.api.operation(operation_name), client: self, params: params, config: config) context[:gem_name] = 'aws-sdk-mq' context[:gem_version] = '1.2.0' Seahorse::Client::Request.new(handlers, context) end # @api private # @deprecated def waiter_names [] end class << self # @api private attr_reader :identifier # @api private def errors_module Errors end end end end
39.153029
199
0.651956
f81308e442e71e838384e8705b387829a0f4eb65
1,568
# encoding: UTF-8 lib = File.expand_path('../lib/', __FILE__) $LOAD_PATH.unshift lib unless $LOAD_PATH.include?(lib) require 'spree_nice_admin/version' Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_nice_admin' s.version = SpreeNiceAdmin.version s.summary = 'Add extension summary here' s.description = 'Add (optional) extension description here' s.required_ruby_version = '>= 2.3.3' s.author = 'You' s.email = '[email protected]' s.homepage = 'https://github.com/your-github-handle/spree_nice_admin' s.license = 'BSD-3-Clause' # s.files = `git ls-files`.split("\n").reject { |f| f.match(/^spec/) && !f.match(/^spec\/fixtures/) } s.require_path = 'lib' s.requirements << 'none' spree_version = '>= 3.2.0', '< 4.3' s.add_dependency 'spree_core', spree_version s.add_dependency 'spree_backend', spree_version s.add_dependency 'spree_extension' s.add_development_dependency 'appraisal' s.add_development_dependency 'capybara' s.add_development_dependency 'capybara-screenshot' s.add_development_dependency 'coffee-rails' s.add_development_dependency 'database_cleaner' s.add_development_dependency 'factory_bot' s.add_development_dependency 'ffaker' s.add_development_dependency 'mysql2' s.add_development_dependency 'pg' s.add_development_dependency 'rspec-rails' s.add_development_dependency 'sass-rails' s.add_development_dependency 'selenium-webdriver' s.add_development_dependency 'simplecov' s.add_development_dependency 'sqlite3' end
35.636364
109
0.735332
61f8b5a81125b1efa36cf0c3fd4a2d76e8fb574e
1,538
require_relative '../../helper' class Repositext class Services describe ExtractContentAtMainTitles do describe 'call' do [ [ "# *The title*{: .a_class}\n\nAnd a para\n\n", :plain_text, false, 'The title' ], [ "^^^ {: .rid #rid-1234}\n\n# *The title*{: .a_class}\n\nAnd a para\n\n", :plain_text, false, 'The title' ], [ "# *The title*{: .a_class}\n\nAnd a para\n\n", :content_at, false, '*The title*{: .a_class}' ], [ "^^^ {: .rid #rid-1234}\n\n# *The title*{: .a_class}\n\nAnd a para\n\n", :content_at, false, '*The title*{: .a_class}' ], [ "# *The title*{: .a_class}\n\nAnd a para\n\n", :content_at, false, '*The title*{: .a_class}' ], [ "^^^ {: .rid #rid-1234}\n\n# Title\n\n## Subtitle\n\n^^^ {: .rid #rid-1235}\n\n", :content_at, true, ['Title', 'Subtitle'] ], ].each do |content_at, format, include_level_2_title, xpect| it "handles #{ content_at.inspect }" do ExtractContentAtMainTitles.call( content_at, format, include_level_2_title ).result.must_equal(xpect) end end end end end end
26.067797
93
0.419376
873b886c6a2bdba23652cf2c5eff7b293eab7a99
534
cask 'superproductivity' do version '2.7.7' sha256 'fb16e40859cff975474063aa8f99afb0e5db7a616198fdfb953c5c0b7d92fe18' # github.com/johannesjo/super-productivity was verified as official when first introduced to the cask url "https://github.com/johannesjo/super-productivity/releases/download/v#{version}/superProductivity-#{version}-mac.zip" appcast 'https://github.com/johannesjo/super-productivity/releases.atom' name 'Super Productivity' homepage 'https://super-productivity.com/' app 'superProductivity.app' end
41.076923
123
0.797753
79491a116aa4b8c91575b1b85ee6a8028c244a01
322
module ActiveSupport # Returns the version of the currently loaded Active Support as a <tt>Gem::Version</tt>. def self.gem_version Gem::Version.new VERSION::STRING end module VERSION MAJOR = 5 MINOR = 1 TINY = 7 PRE = nil STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end end
20.125
90
0.649068
ac0554b20f5c90d0b3e378373a3dadc349a1817f
785
cask 'taskexplorer' do version '2.0.1' sha256 '87867920e2d3bde91df9ebd7e416c20be997dfa707471b8b32732bd856de85fd' # bitbucket.org/objective-see was verified as official when first introduced to the cask url "https://bitbucket.org/objective-see/deploy/downloads/TaskExplorer_#{version}.zip" appcast 'https://objective-see.com/products/changelogs/TaskExplorer.txt' name 'TaskExplorer' homepage 'https://objective-see.com/products/taskexplorer.html' depends_on macos: '>= :mountain_lion' app 'TaskExplorer.app' uninstall_preflight do set_ownership "#{appdir}/TaskExplorer.app" end zap trash: [ '~/Library/Caches/com.objective-see.TaskExplorer', '~/Library/Preferences/com.objective-see.TaskExplorer.plist', ] end
32.708333
90
0.73121
08d6d312c06e7a087a8d89d8c40db1e202cb0da8
292
cask 'fritzing' do version '0.9.2b' sha256 'ad0a23897a761b1342cf1aaae2806109824fbc37d95567aab836877363385fdd' url "http://fritzing.org/download/#{version}/mac-os-x-105/Fritzing#{version}.dmg" name 'Fritzing' homepage 'http://fritzing.org/' license :gpl app 'Fritzing.app' end
24.333333
83
0.743151
bb15e68af13b8191c7906c767c5f23cdc26b39af
9,513
require 'date' module Phrase class LocaleUpdateParameters # specify the branch to use attr_accessor :branch # Locale name attr_accessor :name # Locale ISO code attr_accessor :code # Indicates whether locale is the default locale. If set to true, the previous default locale the project is no longer the default locale. attr_accessor :default # Indicates whether locale is a main locale. Main locales are part of the <a href=\"https://help.phrase.com/help/verification-and-proofreading\" target=\"_blank\">Verification System</a> feature. attr_accessor :main # Indicates whether locale is a RTL (Right-to-Left) locale. attr_accessor :rtl # Source locale. Can be the name or public id of the locale. Preferred is the public id. attr_accessor :source_locale_id # Indicates that new translations for this locale should be marked as unverified. Part of the <a href=\"https://help.phrase.com/help/verification-and-proofreading\" target=\"_blank\">Advanced Workflows</a> feature. attr_accessor :unverify_new_translations # Indicates that updated translations for this locale should be marked as unverified. Part of the <a href=\"https://help.phrase.com/help/verification-and-proofreading\" target=\"_blank\">Advanced Workflows</a> feature. attr_accessor :unverify_updated_translations # If set, translations for this locale will be fetched automatically, right after creation. attr_accessor :autotranslate # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'branch' => :'branch', :'name' => :'name', :'code' => :'code', :'default' => :'default', :'main' => :'main', :'rtl' => :'rtl', :'source_locale_id' => :'source_locale_id', :'unverify_new_translations' => :'unverify_new_translations', :'unverify_updated_translations' => :'unverify_updated_translations', :'autotranslate' => :'autotranslate' } end # Attribute type mapping. def self.openapi_types { :'branch' => :'String', :'name' => :'String', :'code' => :'String', :'default' => :'Boolean', :'main' => :'Boolean', :'rtl' => :'Boolean', :'source_locale_id' => :'String', :'unverify_new_translations' => :'Boolean', :'unverify_updated_translations' => :'Boolean', :'autotranslate' => :'Boolean' } 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 `Phrase::LocaleUpdateParameters` 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 `Phrase::LocaleUpdateParameters`. 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?(:'branch') self.branch = attributes[:'branch'] end if attributes.key?(:'name') self.name = attributes[:'name'] end if attributes.key?(:'code') self.code = attributes[:'code'] end if attributes.key?(:'default') self.default = attributes[:'default'] end if attributes.key?(:'main') self.main = attributes[:'main'] end if attributes.key?(:'rtl') self.rtl = attributes[:'rtl'] end if attributes.key?(:'source_locale_id') self.source_locale_id = attributes[:'source_locale_id'] end if attributes.key?(:'unverify_new_translations') self.unverify_new_translations = attributes[:'unverify_new_translations'] end if attributes.key?(:'unverify_updated_translations') self.unverify_updated_translations = attributes[:'unverify_updated_translations'] end if attributes.key?(:'autotranslate') self.autotranslate = attributes[:'autotranslate'] 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 && branch == o.branch && name == o.name && code == o.code && default == o.default && main == o.main && rtl == o.rtl && source_locale_id == o.source_locale_id && unverify_new_translations == o.unverify_new_translations && unverify_updated_translations == o.unverify_updated_translations && autotranslate == o.autotranslate 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 [branch, name, code, default, main, rtl, source_locale_id, unverify_new_translations, unverify_updated_translations, autotranslate].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def self.build_from_hash(attributes) new.build_from_hash(attributes) end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.openapi_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) 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 Phrase.const_get(type).build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) if value.nil? is_nullable = self.class.openapi_nullable.include?(attr) next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) end hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
33.262238
222
0.629454
1ad3759354db96bb8753a4b6d023bed0a5060bd8
1,350
# frozen_string_literal: true # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! # [START monitoring_v3_generated_NotificationChannelService_DeleteNotificationChannel_sync] require "google/cloud/monitoring/v3" # Create a client object. The client can be reused for multiple calls. client = Google::Cloud::Monitoring::V3::NotificationChannelService::Client.new # Create a request. To set request fields, pass in keyword arguments. request = Google::Cloud::Monitoring::V3::DeleteNotificationChannelRequest.new # Call the delete_notification_channel method. result = client.delete_notification_channel request # The returned object is of type Google::Protobuf::Empty. p result # [END monitoring_v3_generated_NotificationChannelService_DeleteNotificationChannel_sync]
39.705882
91
0.800741
bbba51449ac250fee429435088303ac1b81656e0
1,598
require File.dirname(__FILE__) + "/../spec_helper" require 'java' describe "Loading scripts from jar files" do # JRUBY-4774, WARBLER-15 it "works with classpath URLs that have spaces in them" do url_loader = java.net.URLClassLoader.new([java.net.URL.new("file:" + File.expand_path("test/dir with spaces/test_jar.jar"))].to_java(java.net.URL)) container = org.jruby.embed.ScriptingContainer.new(org.jruby.embed.LocalContextScope::SINGLETHREAD) container.setClassLoader(url_loader) container.runScriptlet("begin; require 'abc/foo'; rescue LoadError; false; end").should be_true end it "works when the jar path contains '#' symbols" do require("jar:file:" + File.expand_path("test/dir with spaces/test#hash#symbol##jar.jar") + "!/abc/foo.rb").should == true $LOADED_FEATURES.pop.should =~ /foo\.rb$/ require("file:" + File.expand_path("test/dir with spaces/test#hash#symbol##jar.jar") + "!/abc/foo.rb").should == true $LOADED_FEATURES.pop.should =~ /foo\.rb$/ end it "works when the load path is a jar and the path contains '#' symbols" do begin $LOAD_PATH.unshift "jar:file:" + File.expand_path("test/dir with spaces/test#hash#symbol##jar.jar") + "!/abc" require("foo").should == true $LOADED_FEATURES.pop.should =~ /foo\.rb$/ ensure $LOAD_PATH.shift end begin $LOAD_PATH.unshift "file:" + File.expand_path("test/dir with spaces/test#hash#symbol##jar.jar") + "!" require("abc/foo").should == true $LOADED_FEATURES.pop.should =~ /foo\.rb$/ ensure $LOAD_PATH.shift end end end
38.97561
151
0.680225
086a55fd2608ff223b1040b31166a83d191ecbda
221
# frozen_string_literal: true module Error # Centralized CLI APP runner custom error handler class ErrorHandler < Parent::Speaker def handle(error) @prompt.send(error.kind, error.message) end end end
20.090909
51
0.728507
ed8c9d0ccc9e1d6aabcc50908ce3333025dfbdd6
2,636
require 'test_helper' class ReppV1ContactsTechReplaceTest < ActionDispatch::IntegrationTest def setup @user = users(:api_bestnames) token = Base64.encode64("#{@user.username}:#{@user.plain_text_password}") token = "Basic #{token}" @auth_headers = { 'Authorization' => token } end def test_replaces_tech_contacts old_contact = contacts(:john) new_contact = contacts(:william) assert DomainContact.where(contact: old_contact, type: 'TechDomainContact').any? payload = { current_contact_id: old_contact.code, new_contact_id: new_contact.code} patch "/repp/v1/domains/contacts", headers: @auth_headers, params: payload json = JSON.parse(response.body, symbolize_names: true) assert_response :ok assert_equal 1000, json[:code] assert_empty ["hospital.test", "library.test"] - json[:data][:affected_domains] assert DomainContact.where(contact: old_contact, type: 'TechDomainContact').blank? end def test_validates_contact_codes payload = { current_contact_id: 'aaa', new_contact_id: 'bbb'} patch "/repp/v1/domains/contacts", headers: @auth_headers, params: payload json = JSON.parse(response.body, symbolize_names: true) assert_response :not_found assert_equal 2303, json[:code] assert_equal 'Object does not exist', json[:message] end def test_new_contact_must_be_different old_contact = contacts(:john) payload = { current_contact_id: old_contact.code, new_contact_id: old_contact.code } patch "/repp/v1/domains/contacts", headers: @auth_headers, params: payload json = JSON.parse(response.body, symbolize_names: true) assert_response :bad_request assert_equal 2304, json[:code] assert_equal 'New contact must be different from current', json[:message] end def test_domain_has_status_tech_change_prohibited domain_shop = domains(:shop) domain_shop_tech_contact_id = domain_shop.tech_domain_contacts[0][:contact_id] old_contact = Contact.find_by(id: domain_shop_tech_contact_id) new_contact = contacts(:john) domain_shop.update(statuses: [DomainStatus::SERVER_TECH_CHANGE_PROHIBITED]) domain_shop.reload assert domain_shop.statuses.include? DomainStatus::SERVER_TECH_CHANGE_PROHIBITED payload = { current_contact_id: old_contact.code, new_contact_id: new_contact.code } patch "/repp/v1/domains/contacts", headers: @auth_headers, params: payload json = JSON.parse(response.body, symbolize_names: true) assert_equal json[:data][:skipped_domains], ["shop.test"] assert domain_shop.contacts.find_by(id: domain_shop_tech_contact_id).present? end end
38.202899
88
0.748483
910f1965f7014c8e2fbb7b0495689660aed6686b
1,202
module Job::SS::Binding::Task extend ActiveSupport::Concern included do # task class mattr_accessor(:task_class, instance_accessor: false) { SS::Task } # task attr_accessor :task_id around_perform :ready end def task @task ||= begin return nil if task_id.blank? self.class.task_class.where({ id: task_id }).first end end def bind(bindings) if bindings['task_id'].present? self.task_id = bindings['task_id'].to_param @task = nil end super end def bindings ret = super ret['task_id'] = task_id if task_id.present? ret end private def ready if task.blank? return yield end unless task.start Rails.logger.info("task #{task.name} is already started") return end ret = nil begin require 'benchmark' time = Benchmark.realtime { ret = yield } task.log sprintf("# %d sec\n\n", time) rescue Interrupt => e task.log "-- #{e}" #@task.log e.backtrace.join("\n") rescue StandardError => e task.log "-- Error" task.log e.to_s task.log e.backtrace.join("\n") ensure task.close end ret end end
18.78125
70
0.601498
79f12db0196af951b52f761ceaa11034ce71f56c
73
require "lol_auth/engine" module LolAuth # Your code goes here... end
12.166667
26
0.726027
e8c3d42ce9458479e35fdbb5dc41bbcf0f66c7fb
350
module BookTicketComponent module Messages module Commands class BookTicketM include Messaging::Message attribute :book_ticket_id, String attribute :request, Hash # meeeeeh, should be [("mow-led", "galileo"), ("led-par", "sirena"), ("par-lon", "sita")] attribute :time, String end end end end
25
122
0.634286
f7aac5d43e947fb565d79590e12917978be8a9d2
1,917
shared_examples_for 'dom_only' do |source| it_should_behave_like 'element' it_should_behave_like 'inputtable' it_should_behave_like 'with_node' it_should_behave_like 'with_dom', source it "supports #{Arachni::RPC::Serializer}" do expect(subject).to eq(Arachni::RPC::Serializer.deep_clone( subject )) end describe '.new' do describe ':action' do it 'sets the #action' do expect(described_class.new( action: url ).action).to eq url end it 'sets the #url' do expect(described_class.new( action: url ).url).to eq url end end describe ':method' do it 'sets the #method' do expect(described_class.new( action: url, method: 'onclick' ).method).to eq 'onclick' end end end describe '#mutation?' do it 'returns false' do expect(subject.mutation?).to be_falsey end end describe '#coverage_id' do it 'delegates to #dom' do allow(subject.dom).to receive(:coverage_id).and_return( 'stuff' ) expect(subject.coverage_id).to eq "#{described_class.type}:stuff" end end describe '#coverage_hash' do it 'hashes #coverage_id' do expect(subject.coverage_hash).to eq subject.coverage_id.persistent_hash end end describe '#id' do it 'delegates to #dom' do allow(subject.dom).to receive(:id).and_return( 'stuff' ) expect(subject.id).to eq "#{described_class.type}:stuff" end end describe '#type' do it "delegates to #{described_class}" do allow(described_class).to receive(:type).and_return( :stuff ) expect(subject.type).to eq :stuff end end end
29.492308
83
0.568597
ff4d719ae63f4bd6cd8c22dc6c5e4a8aeb0ec27b
6,571
module RDF; class Literal ## # An floating point number literal. # # @example Arithmetic with floating point literals # RDF::Literal(1.0) + 0.5 #=> RDF::Literal(1.5) # RDF::Literal(3.0) - 6 #=> RDF::Literal(-3.0) # RDF::Literal(Math::PI) * 2 #=> RDF::Literal(Math::PI * 2) # RDF::Literal(Math::PI) / 2 #=> RDF::Literal(Math::PI / 2) # # @see http://www.w3.org/TR/xmlschema11-2/#double # @since 0.2.1 class Double < Numeric DATATYPE = RDF::URI("http://www.w3.org/2001/XMLSchema#double") GRAMMAR = /^(?:NaN|\-?INF|[+\-]?(?:\d+(:?\.\d*)?|\.\d+)(?:[eE][\+\-]?\d+)?)$/.freeze ## # @param [String, Float, #to_f] value # @param (see Literal#initialize) def initialize(value, datatype: nil, lexical: nil, **options) @datatype = RDF::URI(datatype || self.class.const_get(:DATATYPE)) @string = lexical || (value if value.is_a?(String)) @object = case when value.is_a?(::String) then case value.upcase when '+INF' then 1/0.0 when 'INF' then 1/0.0 when '-INF' then -1/0.0 when 'NAN' then 0/0.0 else Float(value.sub(/\.[eE]/, '.0E')) rescue nil end when value.is_a?(::Float) then value when value.respond_to?(:to_f) then value.to_f else 0.0 # FIXME end end ## # Converts this literal into its canonical lexical representation. # # @return [RDF::Literal] `self` # @see http://www.w3.org/TR/xmlschema11-2/#double def canonicalize! # Can't use simple %f transformation due to special requirements from # N3 tests in representation @string = case when @object.nil? then 'NaN' when @object.nan? then 'NaN' when @object.infinite? then @object.to_s[0...-'inity'.length].upcase when @object.zero? then '0.0E0' else i, f, e = ('%.15E' % @object.to_f).split(/[\.E]/) f.sub!(/0*$/, '') # remove any trailing zeroes f = '0' if f.empty? # ...but there must be a digit to the right of the decimal point e.sub!(/^(?:\+|(\-))?0+(\d+)$/, '\1\2') # remove the optional leading '+' sign and any extra leading zeroes "#{i}.#{f}E#{e}" end @object = case @string when 'NaN' then 0/0.0 when 'INF' then 1/0.0 when '-INF' then -1/0.0 else Float(@string) end self end ## # Returns `true` if this literal is equal to `other`. # # @param [Object] other # @return [Boolean] `true` or `false` # @since 0.3.0 def ==(other) if valid? && infinite? && other.respond_to?(:infinite?) && other.infinite? infinite? == other.infinite? # JRuby INF comparisons differ from MRI else super end end ## # Compares this literal to `other` for sorting purposes. # # @param [Object] other # @return [Integer] `-1`, `0`, or `1` # @since 0.3.0 def <=>(other) case other when ::Numeric to_f <=> other when RDF::Literal::Decimal to_f <=> other.to_d when RDF::Literal::Double to_f <=> other.to_f else super end end ## # Returns `true` if the value is an invalid IEEE floating point number. # # @example # RDF::Literal(-1.0).nan? #=> false # RDF::Literal(1.0/0.0).nan? #=> false # RDF::Literal(0.0/0.0).nan? #=> true # # @return [Boolean] # @since 0.2.3 def nan? to_f.nan? end ## # Returns `true` if the value is a valid IEEE floating point number (it # is not infinite, and `nan?` is `false`). # # @example # RDF::Literal(-1.0).finite? #=> true # RDF::Literal(1.0/0.0).finite? #=> false # RDF::Literal(0.0/0.0).finite? #=> false # # @return [Boolean] # @since 0.2.3 def finite? to_f.finite? end ## # Returns `nil`, `-1`, or `+1` depending on whether the value is finite, # `-INF`, or `+INF`. # # @example # RDF::Literal(0.0/0.0).infinite? #=> nil # RDF::Literal(-1.0/0.0).infinite? #=> -1 # RDF::Literal(+1.0/0.0).infinite? #=> 1 # # @return [Integer] # @since 0.2.3 def infinite? to_f.infinite? end ## # Returns the smallest integer greater than or equal to `self`. # # @example # RDF::Literal(1.2).ceil #=> RDF::Literal(2) # RDF::Literal(-1.2).ceil #=> RDF::Literal(-1) # RDF::Literal(2.0).ceil #=> RDF::Literal(2) # RDF::Literal(-2.0).ceil #=> RDF::Literal(-2) # # @return [RDF::Literal::Integer] # @since 0.2.3 def ceil RDF::Literal::Integer.new(to_f.ceil) end ## # Returns the largest integer less than or equal to `self`. # # @example # RDF::Literal(1.2).floor #=> RDF::Literal(1) # RDF::Literal(-1.2).floor #=> RDF::Literal(-2) # RDF::Literal(2.0).floor #=> RDF::Literal(2) # RDF::Literal(-2.0).floor #=> RDF::Literal(-2) # # @return [RDF::Literal::Integer] # @since 0.2.3 def floor RDF::Literal::Integer.new(to_f.floor) end ## # Returns the absolute value of `self`. # # @return [RDF::Literal] # @since 0.2.3 def abs (f = to_f) && f > 0 ? self : self.class.new(f.abs) end ## # Returns the number with no fractional part that is closest to the argument. If there are two such numbers, then the one that is closest to positive infinity is returned. An error is raised if arg is not a numeric value. # # @return [RDF::Literal::Double] def round self.class.new(to_d.round(half: (to_d < 0 ? :down : :up))) end ## # Returns `true` if the value is zero. # # @return [Boolean] # @since 0.2.3 def zero? to_f.zero? end ## # Returns `self` if the value is not zero, `nil` otherwise. # # @return [Boolean] # @since 0.2.3 def nonzero? to_f.nonzero? ? self : nil end ## # Returns the value as a string. # # @return [String] def to_s @string || case when @object.nan? then 'NaN' when @object.infinite? then @object.to_s[0...-'inity'.length].upcase else @object.to_s end end end # Double end; end # RDF::Literal
29.466368
225
0.520012
6aac524c62a4982aab8b1f78a5db53343fc6ca5e
715
# frozen_string_literal: true require 'rainbow' module Root module Display # Handle logic for showing the victory points # Either stack, or all one square? # Some way to handle it so it's not shifting constantly. class ActiveQuests attr_reader :quests def initialize(quests) @quests = quests end def display ::Terminal::Table.new( title: 'Active Quests', rows: rows, style: { width: 22 } ) end def rows quests.map do |quest| item_info = quest.items.map(&:capitalize).join(', ') [Rainbow(item_info).fg(Colors::SUIT_COLOR[quest.suit])] end end end end end
21.029412
65
0.584615
08b7740e5c231e3c413d1c65b3cebd234943166d
2,034
# Copyright 2010-present Basho Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'riak/errors/base' module Riak class FailedRequest < Error def initialize(message) super(message || t('failed_request')) end end # Exception raised when receiving an unexpected Protocol Buffers response from Riak class ProtobuffsFailedRequest < FailedRequest attr_reader :code, :original_message def initialize(code, message) super t('protobuffs_failed_request', :code => code, :body => message) @original_message = message @code = code @not_found = code == :not_found @server_error = code == :server_error end # @return [true, false] whether the error response is in JSON def is_json? begin JSON.parse(@original_message) true rescue false end end # @return [true,false] whether the error represents a "not found" response def not_found? @not_found end # @return [true,false] whether the error represents an internal # server error def server_error? @server_error end def body @original_message end end class ProtobuffsUnexpectedResponse < ProtobuffsFailedRequest def initialize(code, expected) super code, t('pbc.unexpected_response', expected: expected, actual: code) end end class ProtobuffsErrorResponse < ProtobuffsFailedRequest def initialize(payload) super payload.errcode, payload.errmsg end end end
27.863014
85
0.702557
39d3e6dbc11394a0e850bfeb7f7964498da606e5
282
class CreateGradeEntryStudentsTas < ActiveRecord::Migration def self.up create_table :grade_entry_students_tas, :id => false do |t| t.integer :grade_entry_student_id t.integer :ta_id end end def self.down drop_table :grade_entry_students_tas end end
21.692308
62
0.737589
e96aa188ee86f22053fa3c63c4df1432c8777c78
36
# placeholder for v0.14 time module
18
35
0.777778
e2f1d9e8d1467a78a26dcfed49f3d835e08d6ce1
1,811
# encoding: utf-8 module Mongoid # :nodoc: module Relations #:nodoc: module Bindings #:nodoc: module Embedded #:nodoc: # Binding class for embeds_one relations. class One < Binding # Binds the base object to the inverse of the relation. This is so we # are referenced to the actual objects themselves on both sides. # # This case sets the metadata on the inverse object as well as the # document itself. # # @example Bind the document. # person.name.bind(:continue => true) # person.name = Name.new # # @param [ Hash ] options The options to pass through. # # @option options [ true, false ] :continue Do we continue binding? # @option options [ true, false ] :binding Are we in build mode? # # @since 2.0.0.rc.1 def bind_one target.parentize(base) binding do target.do_or_do_not(metadata.inverse_setter(target), base) end end # Unbinds the base object and the inverse, caused by setting the # reference to nil. # # @example Unbind the document. # person.name.unbind(:continue => true) # person.name = nil # # @param [ Hash ] options The options to pass through. # # @option options [ true, false ] :continue Do we continue unbinding? # @option options [ true, false ] :binding Are we in build mode? # # @since 2.0.0.rc.1 def unbind_one binding do target.do_or_do_not(metadata.inverse_setter(target), nil) end end end end end end end
32.339286
79
0.541137
083e89b9194695f696fda91e57ba6f55999d8ed8
1,584
class CustomersController < ApplicationController def index render json: fetch_customers, each_serializer: customer_serializer, root: customers_root end def show render_result_for Customer.rpc_find(params[:id]) end def get_crm_tickets if tickets = CrmTicket.rpc_fetch(params[:requester_id], force_reload?) render json: tickets, each_serializer: CrmTicketSerializer, root: :crm_tickets else render nothing: true, status: 404 end end def create_crm_ticket render_result_for CrmTicket.rpc_create(params[:crm_ticket], current_user.crmuser_id) end def update_history hid = params[:id] par = params[:history_entry] par[:user_id] = current_user.id render_result_for Customer.rpc_update_history_with(hid, par) end def update cid = params[:id] par = params[:customer] render_result_for Customer.rpc_update_with(cid, par) end private def force_reload? params[:reload] == 'true' end def fetch_customers if params[:caller_id] Customer.rpc_where(opts_for_call) elsif request_is_search? Customer.rpc_search(opts_for_search) else [] end end def opts_for_call {caller_ids: params[:caller_id]} end def opts_for_search {c: params[:c], h: params[:h], t: params[:t], s: 50} end def customers_root request_is_search? ? :search_results : :customers end def customer_serializer request_is_search? ? SearchResultSerializer : CustomerSerializer end def request_is_search? params[:c] || params[:h] end end
18.418605
92
0.707071
e9bcd4bc53bf737188253166b732a67118312a13
141
require File.expand_path('../../../spec_helper', __FILE__) describe "Delegator#!=" do it "needs to be reviewed for spec completeness" end
23.5
58
0.716312
1a65ebbc617d6ec221be24764399e334630141e8
872
# relationship between a supervisor and volunteer class SupervisorVolunteer < ApplicationRecord has_paper_trail belongs_to :volunteer, class_name: "User" belongs_to :supervisor, class_name: "User" validates :supervisor_id, uniqueness: {scope: :volunteer_id} # only 1 row allowed per supervisor-volunteer pair end # == Schema Information # # Table name: supervisor_volunteers # # id :bigint not null, primary key # created_at :datetime not null # updated_at :datetime not null # supervisor_id :bigint not null # volunteer_id :bigint not null # # Indexes # # index_supervisor_volunteers_on_supervisor_id (supervisor_id) # index_supervisor_volunteers_on_volunteer_id (volunteer_id) # # Foreign Keys # # fk_rails_... (supervisor_id => users.id) # fk_rails_... (volunteer_id => users.id) #
30.068966
113
0.708716
286cbd10d5568208f847f9648491757bedb03662
61
code_deploy_agent 'codedeploy-agent' do action :enable end
15.25
39
0.803279
91e6b07532639445179cba2b1f4bed123d2427a7
3,870
module Cts module Mpx # Enumerable collection that can store an entry field in it # @attribute collection storage for the individual field # @return [Field[]] class Fields include Enumerable extend Creatable attribute name: 'collection', kind_of: Array # Create a new fields collection from a data hash # @param [Hash] data raw fields to add # @param [Hash] xmlns namespace of the fields # @raise [ArgumentError] if :data or :xmlns are not provided # @return [Fields] a new fields collection def self.create_from_data(data: nil, xmlns: nil) Driver::Helpers.required_arguments([:data], binding) obj = new obj.parse(data: data, xmlns: xmlns) obj end # Addressable method, indexed by field name # @param [String] key name of the field # @return [Self.collection,Field,nil] Can return the collection, a single field, or nil if nothing found def [](key = nil) return @collection unless key result = @collection.find { |f| f.name == key } return result.value if result nil end # Addresable set method, indexed by field name # @note will create a new copy if it is not found in the collection # @param [String] key name of the field # @param [Object] value value of the field # @param [Hash] xmlns namespace of the field # @example to include xmlns, you need to use the long format of this method # fields.[]= 'id', 'value', xmlns: {} # @return [Void] def []=(key, value, xmlns: nil) existing_field = find { |f| f.name == key } if existing_field existing_field.value = value else add Field.create name: key, value: value, xmlns: xmlns end end # Add a field object to the collection # @param [Field] field instantiated Field to include # @raise [ArgumentError] if field is not a Field # @return [Self] def add(field) return self if @collection.include? field Driver::Exceptions.raise_unless_argument_error? field, Field @collection.push field self end # Iterator method for self # @return [Field] next object in the list def each @collection.each { |c| yield c } end # Reset the field array to a blank state # @return [Void] def initialize reset end # Parse two hashes into a field array # @note this will also set the collection # @param [Hash] xmlns namespace # @param [Hash] data fields in hash form # @raise [ArgumentError] if xmlns is not a Hash # @return [Field[]] returns a collection of fields def parse(xmlns: nil, data: nil) Driver::Exceptions.raise_unless_argument_error? data, Hash data.delete :service data.delete :endpoint reset @collection = data.map { |k, v| Field.create name: k.to_s, value: v, xmlns: xmlns } end # Remove a field object from the collection # @param [String] name instantiated Field to remove # @return [Self] def remove(name) @collection.delete_if { |f| f.name == name } end # Reset the field array to a blank state # @return [Void] def reset @collection = [] end # return the fields as a hash # @return [Hash] key is name, value is value def to_h h = {} each { |f| h.store f.name, f.value } h end # Return the cumulative namespace of all Field's in the collection # @return [Hash] key is the namespace key, value is the value def xmlns a = collection.map(&:xmlns).uniq a.delete nil h = {} a.each { |e| h.merge! e } h end end end end
31.983471
110
0.601034
f70b820d81bdd4b4ce42149142271c633876723c
2,029
# coding: utf-8 require_relative 'lib/autotest-fsevent/version' Gem::Specification.new do |spec| spec.name = 'autotest-fsevent' spec.version = Autotest::FSEvent::VERSION spec.summary = 'Use FSEvent instead of filesystem polling' spec.description = <<~END Autotest relies on filesystem polling to detect modifications in source code files. This is expensive for the CPU, harddrive and battery - and unnecesary on Mac OS X 10.5 or higher which comes with the very efficient FSEvent core service for this very purpose. This gem teaches autotest how to use FSEvent. END spec.authors = ['Sven Schwyn'] spec.email = ['[email protected]'] spec.homepage = 'https://github.com/svoop/autotest-fsevent' spec.license = 'MIT' spec.metadata = { 'homepage_uri' => spec.homepage, 'changelog_uri' => 'https://github.com/svoop/autotest-fsevent/blob/main/CHANGELOG.md', 'source_code_uri' => 'https://github.com/svoop/autotest-fsevent', 'documentation_uri' => 'https://www.rubydoc.info/gems/autotest-fsevent', 'bug_tracker_uri' => 'https://github.com/svoop/autotest-fsevent/issues' } spec.files = Dir['lib/**/*', 'ext/**/*', 'prebuilt/*', 'post-install.txt'] spec.require_paths = %w(lib) spec.extensions = ['ext/fsevent/extconf.rb'] spec.cert_chain = ["certs/svoop.pem"] spec.signing_key = File.expand_path(ENV['GEM_SIGNING_KEY']) if ENV['GEM_SIGNING_KEY'] spec.extra_rdoc_files = Dir['README.md', 'CHANGELOG.md', 'LICENSE.txt'] spec.rdoc_options += [ '--title', 'FSEvent for Autotest', '--main', 'README.md', '--line-numbers', '--inline-source', '--quiet' ] spec.post_install_message = "\e[1;32m\n" + ('-' * 79) + "\n\n" + File.read('post-install.txt').strip + "\n\n" + ('-' * 79) + "\n\e[0m" spec.add_runtime_dependency 'sys-uname' spec.add_development_dependency 'rake' spec.add_development_dependency 'minitest' spec.add_development_dependency "minitest-autotest" end
39.019231
136
0.670281
d5992238f99f71b0a6916bd84579b0c2342a7209
300
# frozen_string_literal: true require 'test_helper' class ApplicationHelperTest < ActionView::TestCase test 'full title helper' do assert_equal full_title, 'Ruby on Rails Tutorial Sample App' assert_equal full_title('Help'), 'Help | Ruby on Rails Tutorial Sample App' end end
27.272727
80
0.74
f8d929d70c4ea5850b82a0a894bd5a694a474267
956
# encoding: UTF-8 version = File.read(File.expand_path("../../SOLIDUS_VERSION", __FILE__)).strip Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'solidus_backend' s.version = version s.summary = 'backend e-commerce functionality for the Spree project.' s.description = 'Required dependency for Spree' s.required_ruby_version = '>= 2.1.0' s.author = 'Solidus Team' s.email = '[email protected]' s.homepage = 'http://solidus.io' s.rubyforge_project = 'solidus_backend' s.files = Dir['LICENSE', 'README.md', 'app/**/*', 'config/**/*', 'lib/**/*', 'db/**/*', 'vendor/**/*'] s.require_path = 'lib' s.requirements << 'none' s.add_dependency 'solidus_api', version s.add_dependency 'solidus_core', version s.add_dependency 'jquery-rails' s.add_dependency 'jquery-ui-rails', '~> 5.0.0' s.add_dependency 'select2-rails', '3.5.9.1' # 3.5.9.2 breaks forms end
34.142857
111
0.642259
ff8f43baee75a7c05c8377dcfa9433cbc5b47728
4,754
# ~*~ encoding: utf-8 ~*~ module Gollum # FileView requires that: # - All files in root dir are processed first # - Then all the folders are sorted and processed class FileView # common use cases: # set pages to wiki.pages and show_all to false # set pages to wiki.pages + wiki.files and show_all to true def initialize(pages, options = {}) @pages = pages @wiki = @pages.first ? @pages.first.wiki : nil @show_all = options[:show_all] || false @checked = options[:collapse_tree] ? '' : "checked" end def enclose_tree(string) sanitize_html(%Q(<ol class="tree">\n) + string + %Q(</ol>)) end def new_page(page) name = page.name url, valid_page = url_for_page page %Q( <li class="file"><a href="#{url}"><span class="icon"></span>#{name}</a>#{valid_page ? "" : delete_file(url, valid_page)}</li>) end def delete_file(url, valid_page) %Q(<form method="POST" action="/deleteFile/#{url}" onsubmit="return confirm('Do you really want to delete the file #{url}?');"><button type="submit" name="delete" value="true"></button></form>) end def new_folder(folder_path) new_sub_folder folder_path end def new_sub_folder(path) <<-HTML <li> <label>#{path}</label> <input type="checkbox" #{@checked} /> <ol> HTML end def end_folder "</ol></li>\n" end def url_for_page(page) url = '' valid_page_name = false if @show_all # Remove ext for valid pages. filename = page.filename valid_page_name = Page::valid_page_name?(filename) filename = valid_page_name ? filename.chomp(::File.extname(filename)) : filename url = ::File.join(::File.dirname(page.path), filename) else url = ::File.join(::File.dirname(page.path), page.filename_stripped) end url = url[2..-1] if url[0, 2] == './' return url, valid_page_name end def render_files html = '' count = @pages.size folder_start = -1 # Process all pages until folders start count.times do |index| page = @pages[index] path = page.path unless path.include? '/' # Page processed (not contained in a folder) html += new_page page else # Folders start at the next index folder_start = index break # Pages finished, move on to folders end end # If there are no folders, then we're done. return enclose_tree(html) if folder_start <= -1 # Handle special case of only one folder. if (count - folder_start == 1) page = @pages[folder_start] html += <<-HTML <li> <label>#{::File.dirname(page.path)}</label> <input type="checkbox" #{@checked} /> <ol> #{new_page page} </ol> </li> HTML return enclose_tree(html) end sorted_folders = [] (folder_start).upto count - 1 do |index| sorted_folders += [[@pages[index].path, index]] end # http://stackoverflow.com/questions/3482814/sorting-list-of-string-paths-in-vb-net sorted_folders.sort! do |first, second| a = first[0] b = second[0] # use :: operator because gollum defines its own conflicting File class dir_compare = ::File.dirname(a) <=> ::File.dirname(b) # Sort based on directory name unless they're equal (0) in # which case sort based on file name. if dir_compare == 0 ::File.basename(a) <=> ::File.basename(b) else dir_compare end end # keep track of folder depth, 0 = at root. cwd_array = [] changed = false # process rest of folders (0...sorted_folders.size).each do |i| page = @pages[sorted_folders[i][1]] path = page.path folder = ::File.dirname path tmp_array = folder.split '/' (0...tmp_array.size).each do |index| if cwd_array[index].nil? || changed html += new_sub_folder tmp_array[index] next end if cwd_array[index] != tmp_array[index] changed = true (cwd_array.size - index).times do html += end_folder end html += new_sub_folder tmp_array[index] end end html += new_page page cwd_array = tmp_array changed = false end enclose_tree(html) end # end render_files def sanitize_html(data) @wiki ? @wiki.sanitizer.clean(data) : data end end # end FileView class end # end Gollum module
28.812121
199
0.567732
618d75b5cf8557eebec2de4b341f5c9256c4af3e
5,701
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. require 'date' # rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength module OCI # MoveCompartmentDetails model. class Identity::Models::MoveCompartmentDetails # **[Required]** The [OCID](https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the destination compartment # into which to move the compartment. # # @return [String] attr_accessor :target_compartment_id # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { # rubocop:disable Style/SymbolLiteral 'target_compartment_id': :'targetCompartmentId' # rubocop:enable Style/SymbolLiteral } end # Attribute type mapping. def self.swagger_types { # rubocop:disable Style/SymbolLiteral 'target_compartment_id': :'String' # 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 [String] :target_compartment_id The value to assign to the {#target_compartment_id} 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.target_compartment_id = attributes[:'targetCompartmentId'] if attributes[:'targetCompartmentId'] raise 'You cannot provide both :targetCompartmentId and :target_compartment_id' if attributes.key?(:'targetCompartmentId') && attributes.key?(:'target_compartment_id') self.target_compartment_id = attributes[:'target_compartment_id'] if attributes[:'target_compartment_id'] 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 && target_compartment_id == other.target_compartment_id 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 [target_compartment_id].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
36.312102
245
0.684792
e2a61411db290e308266d992a9f55c1ac4a82e3c
95
# desc "Explaining what the task does" # task :database_counters do # # Task goes here # end
19
38
0.705263
1a0b258f608a15e3197c5786727f754719a4d736
1,415
# # Cookbook Name:: cloudcli # Resources:: aws_s3_file # # Copyright 2016 Nick Downs # Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. # actions :get default_action :get attribute :bucket, :kind_of => String attribute :path, :kind_of => String, :name_attribute => true attribute :key, :kind_of => String attribute :aws_access_key_id, :kind_of => [String, NilClass], :default => nil attribute :aws_secret_access_key, :kind_of => [String, NilClass], :default => nil attribute :checksum, :kind_of => [String, NilClass], :default => nil attribute :region, :kind_of => String, :default => 'us-east-1' attribute :timeout, :kind_of => Integer, :default => 900 attribute :owner, :kind_of => String, :default => 'root' attribute :group, :kind_of => String, :default => 'root' attribute :mode, :kind_of => [String, Integer, NilClass], :default => nil attribute :profile, :kind_of => String, :default => nil
39.305556
81
0.724382
1c9796ee77568331e9f8afe5c1af720b14a28d34
13,967
require 'util/xml/xml_utils' require 'util/miq-xml' require 'util/miq-logger' module MiqWin32 class System attr_reader :os, :account_policy, :networks OS_MAPPING = [ 'ProductName', :product_name, 'CurrentVersion', :version, 'CurrentBuildNumber', :build, 'SystemRoot', :system_root, 'CSDVersion', :service_pack, 'ProductId', :productid, 'DigitalProductId', :product_key, 'Vendor', :distribution, 'EditionID', :edition_id, ] COMPUTER_NAME_MAPPING = [ 'ComputerName', :machine_name, ] PRODUCT_OPTIONS_MAPPING = [ 'ProductType', :product_type, 'ProductSuite', :product_suite, ] ENVIRONMENT_MAPPING = [ 'PROCESSOR_ARCHITECTURE', :architecture ] TCPIP_MAPPING = [ "Hostname", :hostname, ] NETWORK_CARDS_MAPPING = [ "ServiceName", :guid, "Description", :description, ] DHCP_MAPPING = [ "EnableDHCP", :dhcp_enabled, "DhcpIPAddress", :ipaddress, "DhcpSubnetMask", :subnet_mask, "LeaseObtainedTime", :lease_obtained, "LeaseTerminatesTime", :lease_expires, "DhcpDefaultGateway", :default_gateway, "DhcpServer", :dhcp_server, "DhcpNameServer", :dns_server, "DhcpDomain", :domain, ] STATIC_MAPPING = [ "EnableDHCP", :dhcp_enabled, "IPAddress", :ipaddress, "SubnetMask", :subnet_mask, "DefaultGateway", :default_gateway, "NameServer", :dns_server, "Domain", :domain, ] # Software registry value filters OS_MAPPING_VALUES, NETWORK_CARDS_VALUES = [], [] (0...OS_MAPPING.length).step(2) { |i| OS_MAPPING_VALUES << OS_MAPPING[i] } (0...NETWORK_CARDS_MAPPING.length).step(2) { |i| NETWORK_CARDS_VALUES << NETWORK_CARDS_MAPPING[i] } # System registry value filters PRODUCT_OPTIONS_VALUES, ENVIRONMENT_VALUES, COMPUTER_NAME_VALUES, TCPIP_VALUES = [], [], [], [] (0...PRODUCT_OPTIONS_MAPPING.length).step(2) { |i| PRODUCT_OPTIONS_VALUES << PRODUCT_OPTIONS_MAPPING[i] } (0...ENVIRONMENT_MAPPING.length).step(2) { |i| ENVIRONMENT_VALUES << ENVIRONMENT_MAPPING[i] } (0...COMPUTER_NAME_MAPPING.length).step(2) { |i| COMPUTER_NAME_VALUES << COMPUTER_NAME_MAPPING[i] } (0...TCPIP_MAPPING.length).step(2) { |i| TCPIP_VALUES << TCPIP_MAPPING[i] } (0...DHCP_MAPPING.length).step(2) { |i| TCPIP_VALUES << DHCP_MAPPING[i] } (0...STATIC_MAPPING.length).step(2) { |i| TCPIP_VALUES << STATIC_MAPPING[i] } def initialize(_c, fs) @networks = [] regHnd = RemoteRegistry.new(fs, true) software_doc = regHnd.loadHive("software", [ {:key => "Microsoft/Windows NT/CurrentVersion", :depth => 1, :value => OS_MAPPING_VALUES}, {:key => "Microsoft/Windows NT/CurrentVersion/NetworkCards", :depth => 0, :value => NETWORK_CARDS_VALUES} ]) regHnd.close regHnd = RemoteRegistry.new(fs, true) sys_doc = regHnd.loadHive("system", [ {:key => 'CurrentControlSet/Control/ComputerName/ComputerName', :value => COMPUTER_NAME_VALUES}, {:key => 'CurrentControlSet/Control/Session Manager/Environment', :value => ENVIRONMENT_VALUES}, {:key => 'CurrentControlSet/Control/ProductOptions', :value => PRODUCT_OPTIONS_VALUES}, {:key => 'CurrentControlSet/Services/Tcpip/Parameters', :value => TCPIP_VALUES}, ]) regHnd.close # Get the OS information attrs = {:type => "windows"} reg_node = MIQRexml.findRegElement("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", software_doc.root) attrs.merge!(XmlFind.decode(reg_node, OS_MAPPING)) if reg_node reg_node = MIQRexml.findRegElement("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\ComputerName", sys_doc.root) attrs.merge!(XmlFind.decode(reg_node, COMPUTER_NAME_MAPPING)) if reg_node reg_node = MIQRexml.findRegElement("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\ProductOptions", sys_doc.root) attrs.merge!(XmlFind.decode(reg_node, PRODUCT_OPTIONS_MAPPING)) if reg_node reg_node = MIQRexml.findRegElement("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", sys_doc.root) attrs.merge!(XmlFind.decode(reg_node, ENVIRONMENT_MAPPING)) if reg_node attrs[:product_key] = MiqWin32::Software.DecodeProductKey(attrs[:product_key]) if attrs[:product_key] attrs[:architecture] = architecture_to_string(attrs[:architecture]) # Parse product edition and append to product_name if needed. os_product_suite(attrs) @os = attrs # Get the network card information # Hold onto the parameters common to all network cards reg_tcpip = MIQRexml.findRegElement("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters", sys_doc.root) if reg_tcpip tcpip_params = XmlFind.decode(reg_tcpip, TCPIP_MAPPING) tcpip_params[:domain] = XmlFind.findNamedElement_hash("Domain", reg_tcpip) tcpip_params[:domain] = XmlFind.findNamedElement_hash("DhcpDomain", reg_tcpip) if tcpip_params[:domain].blank? tcpip_params[:domain] = nil if tcpip_params[:domain].blank? # Find each netword card, and get it's individual parameters reg_networkCards = MIQRexml.findRegElement("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards", software_doc.root) if reg_networkCards.kind_of?(Hash) reg_networkCards.each_element do |networkCard| attrs = XmlFind.decode(networkCard, NETWORK_CARDS_MAPPING) params = XmlFind.findElement("Interfaces/#{attrs[:guid]}", reg_tcpip) next if params.nil? # Add the common parameters attrs.merge!(tcpip_params) # Blank out fields that are not shared between network types attrs[:lease_obtained] = attrs[:lease_expires] = attrs[:dhcp_server] = nil # Get the rest of the parameters based on whether this network is DHCP enabled dhcp = XmlFind.findNamedElement_hash("EnableDHCP", params) attrs.merge!(XmlFind.decode(params, dhcp.to_i == 1 ? DHCP_MAPPING : STATIC_MAPPING)) # Remove the extra curly braces from the guid attrs[:guid] = attrs[:guid][1..-2] unless attrs[:guid].nil? # Clean the lease times and check they are in a reasonable range [:lease_obtained, :lease_expires].each do |t| attrs[t] = Time.at(attrs[t].to_i).getutc.iso8601 if attrs[t] && attrs[t].to_i >= 0 && attrs[t].to_i < 0x80000000 end @networks << attrs end end end # Extracted data also built into a human-readable format if uncommented # @debug_str = '' # Force memory cleanup software_doc = nil; sys_doc = nil; GC.start regHnd = RemoteRegistry.new(fs, true) sam_doc = regHnd.loadHive("sam", [{:key => "SAM/Domains/Account", :depth => 1, :value => ['F']}]) regHnd.close # Extract the local account policy from the registry @debug_str += "Account Policy:\n" if @debug_str reg_node = MIQRexml.findRegElement("HKEY_LOCAL_MACHINE\\SAM\\SAM\\Domains\\Account", sam_doc.root) if reg_node reg_node.each_element(:value) do |e| acct_policy_f = process_acct_policy_f(e.text) if e.attributes[:name] == "F" unless acct_policy_f.nil? # Remove unused elements acct_policy_f.delete(:auto_increment) acct_policy_f.delete(:next_rid) acct_policy_f.delete(:pw_encrypt_pw_complex) acct_policy_f.delete(:syskey) @account_policy = acct_policy_f end end end # Dump the debug string to a file if we are collecting that data # File.open('C:/Temp/reg_extract_full_system.txt', 'w') { |f| f.write(@debug_str) } if @debug_str if $log os_dup = @os.dup [:productid, :product_key].each { |k| os_dup.delete(k) } $log.info "VM OS information: [#{os_dup.inspect}]" end end def to_xml(doc = nil) doc = MiqXml.createDoc(nil) unless doc osToXml(doc) accountPolicyToXml(doc) networksToXml(doc) doc end def osToXml(doc = nil) doc = MiqXml.createDoc(nil) unless doc doc.add_element(:os, @os) unless @os.empty? doc end def accountPolicyToXml(doc = nil) doc = MiqXml.createDoc(nil) unless doc doc.add_element(:account_policy, @account_policy) unless @account_policy.blank? doc end def networksToXml(doc = nil) doc = MiqXml.createDoc(nil) unless doc unless @networks.empty? node = doc.add_element(:networks) @networks.each { |n| node.add_element(:network, n) } end doc end def architecture_to_string(architecture) case architecture when "x86" then 32 when "AMD64" then 64 end end # Parse product edition and append to product_name if needed. def os_product_suite(hash) eid = hash.delete(:edition_id) ps = hash.delete(:product_suite) # If edition_id is populated then the edition will already be part of the product_name string if eid.nil? && !hash[:product_name].nil? ps = ps.to_s.split("\n") if ps.length > 1 && !hash[:product_name].include?(ps.first) hash[:product_name] = "#{hash[:product_name].strip} #{ps.first} Edition" end end end # Definition derived from http://www.beginningtoseethelight.org/ntsecurity/#BB4F910C0FFA1E43 # \HKEY_LOCAL_MACHINE\SAM\SAM\Domains\Account\F SAM_STRUCT_ACCT_POLICY = BinaryStruct.new([ 'a16', nil, # UNKNOWN 'Q', :auto_increment, # Auto-increment 'Q', :max_pw_age, # Maximum password age (>=0 & <=999) days - minus from qword:ff + 1 = seconds x 10 million 'Q', :min_pw_age, # Minimum password age (>=0 & <=999) days - minus from qword:ff + 1 = seconds x 10 million 'a8', nil, # UNKNOWN 'Q', :lockout_duration, # Account lockout duration (>=0 & <=99,999) minutes - minus from qword:ff + 1 = seconds x 10 million 'Q', :reset_lockout_counter, # Reset account lockout counter after (>=1 & <=99,999) minutes - minus from qword:ff + 1 = seconds x 10 million 'a8', nil, # UNKNOWN 'I', :next_rid, # Next created users RID 'C', :pw_encrypt_pw_complex, # High nibble # Store password using reversible encryption for all users in the domain (enabled=1/disabled=0) # Low nibble # Password must meet complexity requirements (enabled=1/disabled=0) 'a3', nil, # UNKNOWN 'C', :min_pw_len, # Minimum password length (>=0 & <=14) characters 'a1', nil, # UNKNOWN 'C', :pw_hist, # Enforce password history (>=0 & <=24) passwords remembered 'a1', nil, # UNKNOWN 'S', :lockout_threshold, # Account lockout threshold (>=0 & <=999) attempts 'a26', nil, # UNKNOWN 'a48', :syskey, # Part of syskey 'a8', nil, # UNKNOWN ]) def process_acct_policy_f(data) bin = MSRegHive.regBinaryToRawBinary(data) f = SAM_STRUCT_ACCT_POLICY.decode(bin) @debug_str += " auto_increment - %s\n" % f[:auto_increment] if @debug_str @debug_str += " max_pw_age - %s - " % f[:max_pw_age] if @debug_str f[:max_pw_age] = process_acct_policy_f_date(f[:max_pw_age]) / 86400 @debug_str += "%s days\n" % f[:max_pw_age] if @debug_str @debug_str += " min_pw_age - %s - " % f[:min_pw_age] if @debug_str f[:min_pw_age] = process_acct_policy_f_date(f[:min_pw_age]) / 86400 @debug_str += "%s days\n" % f[:min_pw_age] if @debug_str @debug_str += " lockout_duration - %s - " % f[:lockout_duration] if @debug_str f[:lockout_duration] = process_acct_policy_f_date(f[:lockout_duration]) / 60 @debug_str += "%s minutes\n" % f[:lockout_duration] if @debug_str @debug_str += " reset_lockout_counter - %s - " % f[:reset_lockout_counter] if @debug_str f[:reset_lockout_counter] = process_acct_policy_f_date(f[:reset_lockout_counter]) / 60 @debug_str += "%s minutes\n" % f[:reset_lockout_counter] if @debug_str @debug_str += " next_rid - %s\n" % f[:next_rid] if @debug_str @debug_str += " pw_encrypt_pw_complex - 0x%02x\n" % f[:pw_encrypt_pw_complex] if @debug_str f[:pw_encrypt], f[:pw_complex] = process_acct_policy_f_pw_encrypt_pw_complex(f[:pw_encrypt_pw_complex]) @debug_str += " pw_encrypt - %s\n" % f[:pw_encrypt] if @debug_str @debug_str += " pw_complex - %s\n" % f[:pw_complex] if @debug_str if @debug_str @debug_str += " min_pw_len - %s characters\n" % f[:min_pw_len] @debug_str += " pw_hist - %s passwords remembered\n" % f[:pw_hist] @debug_str += " lockout_threshold - %s attempts\n" % f[:lockout_threshold] @debug_str += " syskey - %s\n" % Accounts.rawBinaryToRegBinary(f[:syskey]) end f end def process_acct_policy_f_date(data) return 0 if data == 0 || data == 0x8000000000000000 # minus from qword:ff + 1 = seconds x 10 million (0x10000000000000000 - data) / 10000000 end def process_acct_policy_f_pw_encrypt_pw_complex(data) pw_encrypt = data >> 4 pw_encrypt = (pw_encrypt == 1) pw_complex = data & 0x0F pw_complex = (pw_complex == 1) return pw_encrypt, pw_complex end end end
41.817365
154
0.629054
6262d34b1e41e23f714c17ef399cbb9a9b96401d
347
# frozen_string_literal: true # typed: true # compiled: true # Many of our benchmarks use a while loop with `+=` over 100M items. # # Use this benchmark as a baseline to check how much time is spent in an # operation vs spent in the while loop & loop counter. i = 0 while i < 100_000_000 # ... potential extra stuff ... i += 1 end puts i
18.263158
72
0.691643
bb6a2fd1614f8ee1985d7b06c3b50f3909f658a2
6,588
require 'abstract_unit' require 'fixtures/article' require 'fixtures/product' require 'fixtures/tariff' require 'fixtures/product_tariff' require 'fixtures/suburb' require 'fixtures/street' require 'fixtures/restaurant' require 'fixtures/dorm' require 'fixtures/room' require 'fixtures/room_attribute' require 'fixtures/room_attribute_assignment' require 'fixtures/student' require 'fixtures/room_assignment' require 'fixtures/user' require 'fixtures/reading' class TestAssociations < ActiveSupport::TestCase fixtures :articles, :products, :tariffs, :product_tariffs, :suburbs, :streets, :restaurants, :restaurants_suburbs, :dorms, :rooms, :room_attributes, :room_attribute_assignments, :students, :room_assignments, :users, :readings def test_has_many_through_with_conditions_when_through_association_is_not_composite user = User.find(:first) assert_equal 1, user.articles.find(:all, :conditions => ["articles.name = ?", "Article One"]).size end def test_has_many_through_with_conditions_when_through_association_is_composite room = Room.find(:first) assert_equal 0, room.room_attributes.find(:all, :conditions => ["room_attributes.name != ?", "keg"]).size end def test_has_many_through_on_custom_finder_when_through_association_is_composite_finder_when_through_association_is_not_composite user = User.find(:first) assert_equal 1, user.find_custom_articles.size end def test_has_many_through_on_custom_finder_when_through_association_is_composite room = Room.find(:first) assert_equal 0, room.find_custom_room_attributes.size end def test_count assert_equal 2, Product.count(:include => :product_tariffs) assert_equal 3, Tariff.count(:include => :product_tariffs) assert_equal 2, Tariff.count(:group => :start_date).size end def test_products assert_not_nil products(:first_product).product_tariffs assert_equal 2, products(:first_product).product_tariffs.length assert_not_nil products(:first_product).tariffs assert_equal 2, products(:first_product).tariffs.length assert_not_nil products(:first_product).product_tariff end def test_product_tariffs assert_not_nil product_tariffs(:first_flat).product assert_not_nil product_tariffs(:first_flat).tariff assert_equal Product, product_tariffs(:first_flat).product.class assert_equal Tariff, product_tariffs(:first_flat).tariff.class end def test_tariffs assert_not_nil tariffs(:flat).product_tariffs assert_equal 1, tariffs(:flat).product_tariffs.length assert_not_nil tariffs(:flat).products assert_equal 1, tariffs(:flat).products.length assert_not_nil tariffs(:flat).product_tariff end # Its not generating the instances of associated classes from the rows def test_find_includes_products assert @products = Product.find(:all, :include => :product_tariffs) assert_equal 2, @products.length assert_not_nil @products.first.instance_variable_get('@product_tariffs'), '@product_tariffs not set; should be array' assert_equal 3, @products.inject(0) {|sum, tariff| sum + tariff.instance_variable_get('@product_tariffs').length}, "Incorrect number of product_tariffs returned" end def test_find_includes_tariffs assert @tariffs = Tariff.find(:all, :include => :product_tariffs) assert_equal 3, @tariffs.length assert_not_nil @tariffs.first.instance_variable_get('@product_tariffs'), '@product_tariffs not set; should be array' assert_equal 3, @tariffs.inject(0) {|sum, tariff| sum + tariff.instance_variable_get('@product_tariffs').length}, "Incorrect number of product_tariffs returnedturned" end def test_find_includes_product assert @product_tariffs = ProductTariff.find(:all, :include => :product) assert_equal 3, @product_tariffs.length assert_not_nil @product_tariffs.first.instance_variable_get('@product'), '@product not set' end def test_find_includes_comp_belongs_to_tariff assert @product_tariffs = ProductTariff.find(:all, :include => :tariff) assert_equal 3, @product_tariffs.length assert_not_nil @product_tariffs.first.instance_variable_get('@tariff'), '@tariff not set' end def test_find_includes_extended assert @products = Product.find(:all, :include => {:product_tariffs => :tariff}) assert_equal 3, @products.inject(0) {|sum, product| sum + product.instance_variable_get('@product_tariffs').length}, "Incorrect number of product_tariffs returned" assert @tariffs = Tariff.find(:all, :include => {:product_tariffs => :product}) assert_equal 3, @tariffs.inject(0) {|sum, tariff| sum + tariff.instance_variable_get('@product_tariffs').length}, "Incorrect number of product_tariffs returned" end def test_join_where_clause @product = Product.find(:first, :include => :product_tariffs) where_clause = @product.product_tariffs.composite_where_clause( ['foo','bar'], [1,2] ) assert_equal('(foo=1 AND bar=2)', where_clause) end def test_has_many_through @products = Product.find(:all, :include => :tariffs) assert_equal 3, @products.inject(0) {|sum, product| sum + product.instance_variable_get('@tariffs').length}, "Incorrect number of tariffs returned" end def test_has_many_through_when_not_pre_loaded student = Student.find(:first) rooms = student.rooms assert_equal 1, rooms.size assert_equal 1, rooms.first.dorm_id assert_equal 1, rooms.first.room_id end def test_has_many_through_when_through_association_is_composite dorm = Dorm.find(:first) assert_equal 1, dorm.rooms.length assert_equal 1, dorm.rooms.first.room_attributes.length assert_equal 'keg', dorm.rooms.first.room_attributes.first.name end def test_associations_with_conditions @suburb = Suburb.find([2, 1]) assert_equal 2, @suburb.streets.size @suburb = Suburb.find([2, 1]) assert_equal 1, @suburb.first_streets.size @suburb = Suburb.find([2, 1], :include => :streets) assert_equal 2, @suburb.streets.size @suburb = Suburb.find([2, 1], :include => :first_streets) assert_equal 1, @suburb.first_streets.size end def test_has_and_belongs_to_many @restaurant = Restaurant.find([1,1]) assert_equal 2, @restaurant.suburbs.size @restaurant = Restaurant.find([1,1], :include => :suburbs) assert_equal 2, @restaurant.suburbs.size end end
40.919255
132
0.735276
113d8f76023c4590ec76d60e76cfb3b8f92c7f96
1,208
module EmailService::SES class Logger def log_request(method, params) request_id = SecureRandom.uuid Rails.logger.info(to_json_log_entry(:request, method, params, request_id)) request_id end def log_result(result, method, request_id) if result.success Rails.logger.info(to_json_log_entry(:response, method, { successful: true }, request_id)) unless result.nil? else Rails.logger.warn(to_json_log_entry(:response, method, { successful: false, error_msg: result.error_msg }, request_id)) unless result.nil? end end def to_json_log_entry(type, method, params, request_id = nil) { tag: :aws_ses, type: type, method: method, params: params, request_id: request_id }.to_json end end end
30.2
95
0.44702
d51b702cd34f11c2fce7162b25c7d609b3cdf179
970
# # Cookbook:: isc_kea # Resource:: config_dhcp6_control_socket # # Copyright:: Ben Hughes <[email protected]> # # 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. # unified_mode true use 'partial/_config_auto_accumulator_kea' use 'partial/_config_parameters_common' def auto_accumulator_options_override { config_path_override: %w(Dhcp6 control-socket), }.freeze end property :socket_type, String, equal_to: %w(unix) property :socket_name, String
27.714286
74
0.762887
bb67f62d76d00aa97278052d7266a1df97544b53
4,023
require_relative 'sequence_renderer' require_relative 'thing' require_relative 'process' module Dogviz class Flow FLOW_RENDERERS = { sequence: WebSequenceDiagramsSequenceRenderer, plantuml: PlantUmlSequenceRenderer, png: PngSequenceRenderer } attr_reader :sys attr_accessor :executor def initialize(sys, name) @sys = sys @name = name @commands = [] @actors = [] @caller_stack = [] @executor = nil end def make_connections commands.each { |type, from, to, label| thing_of(from).points_to(thing_of(to), name: label.split('\n').first) if type == :call } end def involves(*actors) @actors += actors self end def from(initial_actor, &flowspec) @actors.each { |actor| actor.start_flow self } @caller_stack << initial_actor begin flowspec.call rescue NoMethodError => nme raise "Did you call #involves for all actors? It's a common cause of the caught exception: #{nme}" ensure @caller_stack.pop @actors.each { |actor| actor.stop_flow } end end def add_note(from, where, what) # TODO yukk next lets move to command classes, e.g. OptCommand, NoteCommand, CallCommand etc. commands << [:note, from, where, what] end def process(process) commands.last[2] = process # TODO yukk again - last[2] is "other"" @caller_stack[-1] = process end def optional(text, &block) commands << [:opt, nil, nil, text] block.call commands << [:end, nil, nil, nil] end def divider(text) commands << [:divider, nil, nil, text] end alias :opt :optional def add_call(from, to, label) commands << [:call, from, to, label] end def add_return(from, to, label) commands << [:return, from, to, label] end def next_call(to, label) add_call @caller_stack.last, to, label @caller_stack << to end def end_call(label) current_actor = @caller_stack.pop add_return(current_actor, @caller_stack.last, label) unless label.nil? end def flows(*steps) sys.warn_on_exit 'deprecation warning: flow#flows deprecated, should use flow#from(actor) { <nested flow spec> }' from = nil to = nil label = nil steps.each do |step| if from.nil? from = ensure_is_thing(step) elsif label.nil? && step.is_a?(String) label = step elsif to.nil? to = ensure_is_thing(step) end unless to.nil? add_call from, to, label from = to to = label = nil end end end def ensure_is_thing(step) raise "Expected some thing or process: '#{step}' already got: #{commands}" unless step.is_a?(Thing) || step.is_a?(Process) step end def output(type_to_file) type = type_to_file.keys.first raise "Only support #{FLOW_RENDERERS.keys}, not: '#{type}'" unless FLOW_RENDERERS.has_key?(type) render(FLOW_RENDERERS[type]).output(type_to_file, executor) end def render(renderer_class = SequenceRenderer) renderer = renderer_class.new(@name, sys) commands.each do |type, from, to, label| if type == :call renderer.render_edge(from, to, {label: label}) elsif type == :return renderer.render_return_edge(from, to, {label: label}) elsif type == :end renderer.end_combination elsif type == :note renderer.note(from, to, label) elsif type == :divider renderer.divider(label) else renderer.start_combination(type, label) end end renderer.rendered end def suppress_messages! sys.suppress_messages! end private attr_reader :commands def thing_of(it) return it.processor if it.is_a?(Process) it end end end
25.301887
128
0.598807
014c1deab3452d3fd406f08cd78a9fa85316d6f6
5,160
require "spec_helper" module Nyanko describe Invoker do let(:view) do Class.new(ActionView::Base) do include Nyanko::Invoker include Nyanko::Helper include Nyanko::UnitProxyProvider end.new end let(:controller) do Class.new(ActionController::Base) do include Nyanko::Invoker include Nyanko::Helper include Nyanko::UnitProxyProvider end.new end describe "#invoke" do it "invokes in the same context with receiver" do view.invoke(:example_unit, :self, :type => :plain).should == view end it "invokes with locals option" do view.invoke(:example_unit, :locals, :locals => { :key => "value" }, :type => :plain). should == "value" end it "invokes with falsy locals" do view.invoke(:example_unit, :falsy, :locals => { :key => nil }, :type => :plain). should == true end it "invokes with shared method" do view.invoke(:example_unit, :shared, :type => :plain).should == "shared args" end it "invokes with helper method in view context" do view.invoke(:example_unit, :helper, :type => :plain).should == "helper" end context "when invoked in view" do it "invokes with partial view" do view.invoke(:example_unit, :render, :type => :plain).should == "test\n" end end context "when invoked in controller" do it "invokes with unit views path" do controller.invoke(:example_unit, :render, :type => :plain).should == "test\n" end end context "when short-hand style args is passed" do it "recognizes args as locals option" do view.invoke(:example_unit, :locals, :key => "value").should == '<div class="unit unit__example_unit unit__example_unit__locals">value</div>' end end context "when type is not specified" do it "invokes and returns result surrounded by div" do view.invoke(:example_unit, :test).should == '<div class="unit unit__example_unit unit__example_unit__test">test</div>' end end context "when Config.compatible_css_class is true" do before do Config.compatible_css_class = true end it "invokes and returns result surrounded by div" do view.invoke(:example_unit, :test).should == '<div class="extension ext_example_unit ext_example_unit-test">test</div>' end end context "when type is :plain" do it "does not surround result with html element" do view.invoke(:example_unit, :test, :type => :plain).should == "test" end end context "when the result is blank" do it "does not surround result with html element" do view.invoke(:example_unit, :blank).should == " " end end context "when type is :inline" do it "invokes and returns result surrounded by span" do view.invoke(:example_unit, :test, :type => :inline).should == '<span class="unit unit__example_unit unit__example_unit__test">test</span>' end end context "when context is not a view" do it "does not surround result with html tag" do controller.invoke(:example_unit, :test).should == "test" end end context "when run_default is called in function" do it "invokes given block as a fallback" do controller.invoke(:example_unit, :default) { "default" }.should == "default" end end context "when run_default is called but no block given" do it "invokes given block as a fallback" do controller.invoke(:example_unit, :default).should == nil end end context "when non-existent unit is specified" do it "does nothing" do view.invoke(:non_existent_unit, :test, :type => :plain).should == nil end end context "when function is not found" do it "runs default but not handled by ExceptionHandler" do ExceptionHandler.should_not_receive(:handle) view.invoke(:example_unit, :non_existent_function) { "default" }.should == "default" end end context "when an error is raised in invoking" do context "when block is given" do context "when context is a view" do it "captures given block as a fallback" do view.should_receive(:capture).and_call_original view.invoke(:example_unit, :error) { "error" }.should == "error" end end context "when context is not a view" do it "calls given block as a fallback" do controller.should_not_receive(:capture) controller.invoke(:example_unit, :error) { "error" }.should == "error" end end end context "when no block is given" do it "rescues the error and does nothing" do view.invoke(:example_unit, :error).should == nil end end end end end end
32.866242
94
0.600969
1123c00a4bcffa1e21f24e9360380baedbee7ecd
422
# == Schema Information # # Table name: nc_category_groups # # id :bigint(8) not null, primary key # name :string not null # created_at :datetime not null # updated_at :datetime not null # module NationalCircumstance class CategoryGroup < ApplicationRecord self.table_name = 'nc_category_groups' validates_presence_of :name has_many :categories end end
22.210526
53
0.661137
ff59fb24c721066d0c2253c9fb7d25aab0b37658
639
class Beer < ActiveRecord::Base attr_accessible :ibus, :srm, :abv, :name, :brewery, :manufacturer_id has_many :kegs has_many :votes has_many :ratings belongs_to :manufacturer validates_presence_of :name def rating ratings.average(:value) end def serializable_hash(options={}) options[:only] = [:id, :created_at, :updated_at, :name, :ibus, :srm, :abv, :brewery] options[:methods] = [:rating] super end def email_order email = "mailto:#{manufacturer.email}?" email << "subject=" email << %w(Shopify would like to place an order for).join(' ') email << " #{name}" email end end
22.821429
88
0.657277
7ac526cf2a1670309513b198f5cbd1231af5e3cc
813
class SfPwgen < Formula desc "Generate passwords using SecurityFoundation framework" homepage "https://github.com/anders/pwgen/" url "https://github.com/anders/pwgen/archive/1.5.tar.gz" sha256 "e1f1d575638f216c82c2d1e9b52181d1d43fd05e7169db1d6f9f5d8a2247b475" head "https://github.com/anders/pwgen.git" bottle do cellar :any_skip_relocation sha256 "50e87a417ac3d9b5be7318c7e2983db1a1f90759fab02a898f9cd257b15ac6e2" => :mojave sha256 "2ebd137c58bd8d20a50251e159b6074e65009a265aa351cf6eb0afd39d59edc1" => :high_sierra sha256 "01cf1ff26d304c0cbb0072130ba2476ddeebd8933040092b937ced1ede06c2a2" => :sierra end def install system "make" bin.install "sf-pwgen" end test do assert_equal 20, shell_output("#{bin}/sf-pwgen -a memorable -c 1 -l 20").chomp.length end end
33.875
93
0.777368
262c8673f054a84a0084565a5366e101f1cd4f38
131
require_relative 'base_icann_compliant' module Whois class Parsers class WhoisNicAnz < BaseIcannCompliant end end end
14.555556
42
0.778626
b97d07b526bc4bb39ebad89b430140cc30407e37
227
class ConfigurationProfileDecorator < MiqDecorator def fonticon if id.nil? 'pficon pficon-folder-close' else 'fa fa-list-ul' end end def quadicon { :fonticon => fonticon } end end
14.1875
50
0.61674
39d1aebe8ae0420a6887bfeebb1d489d7a232ff8
871
require 'rails_helper' RSpec.describe EarlyAllocationEventJob, type: :job do let(:prison) { create(:prison) } let(:offender) { build(:offender) } context 'when the offender exists in NOMIS' do before do stub_offender(build(:nomis_offender, prisonerNumber: offender.nomis_offender_id, prisonId: prison.code)) expect(EarlyAllocationEventService).to receive(:send_early_allocation) end it 'sends the event via the job' do described_class.perform_now offender.nomis_offender_id end end context 'when that offender ID no longer exists in NOMIS' do before do stub_non_existent_offender(offender.nomis_offender_id) expect(EarlyAllocationEventService).not_to receive(:send_early_allocation) end it 'does not send the event' do described_class.perform_now offender.nomis_offender_id end end end
30.034483
110
0.748565
d50d012548d8f2cadec01b5bde2503503bbacb8d
1,444
Brakeman.load_brakeman_dependency 'multi_json' require 'brakeman/report/initializers/multi_json' class Brakeman::Report::JSON < Brakeman::Report::Base def generate_report errors = tracker.errors.map{|e| { :error => e[:error], :location => e[:backtrace][0] }} app_path = tracker.options[:app_path] warnings = convert_to_hashes all_warnings ignored = convert_to_hashes ignored_warnings scan_info = { :app_path => File.expand_path(tracker.options[:app_path]), :rails_version => rails_version, :security_warnings => all_warnings.length, :start_time => tracker.start_time.to_s, :end_time => tracker.end_time.to_s, :duration => tracker.duration, :checks_performed => checks.checks_run.sort, :number_of_controllers => tracker.controllers.length, # ignore the "fake" model :number_of_models => tracker.models.length - 1, :number_of_templates => number_of_templates(@tracker), :ruby_version => RUBY_VERSION, :brakeman_version => Brakeman::Version } report_info = { :scan_info => scan_info, :warnings => warnings, :ignored_warnings => ignored, :errors => errors } MultiJson.dump(report_info, :pretty => true) end def convert_to_hashes warnings warnings.map do |w| hash = w.to_hash hash[:file] = warning_file w hash end.sort_by { |w| "#{w[:fingerprint]}#{w[:line]}" } end end
30.723404
91
0.668283
7a00e380023b1aed6dafd27ce1047087ff0be0b3
979
class Odo < Formula desc "Atomic odometer for the command-line" homepage "https://github.com/atomicobject/odo" url "https://github.com/atomicobject/odo/archive/v0.2.2.tar.gz" sha256 "52133a6b92510d27dfe80c7e9f333b90af43d12f7ea0cf00718aee8a85824df5" bottle do cellar :any_skip_relocation rebuild 1 sha256 "f2bee7fa62ba66589fb75b3eb9b32c843e0bfc4f054521876fd891388765eec9" => :mojave sha256 "0bfc54617186d149c98593c74dfaa59a42b2edcc7df1855fd452594ec42f1476" => :high_sierra sha256 "06af025b0a2df201a9b79944dcc4809708b305242622a90c92a9906a18adf2d6" => :sierra sha256 "979cc7131a35180614e848fa5fa12a72f734da7321358c89dfbd425fc8dff837" => :el_capitan sha256 "ebfc6a2e616694a3862b1d6d11dda1a2c1cb4c966447678b342457490e0e0abc" => :yosemite end def install system "make" man1.mkpath bin.mkpath system "make", "test" system "make", "install", "PREFIX=#{prefix}" end test do system "#{bin}/odo", "testlog" end end
33.758621
93
0.772217
034eb583ad2d3446e82a729fd618c449f31d29e8
196
# # ${TM_NEW_FILE_BASENAME} # # Created by ${TM_FULLNAME} on ${TM_DATE}. # Copyright (c) ${TM_YEAR} ${TM_ORGANIZATION_NAME}. All rights reserved. # Shoes.app do # Just a simple app, yes? end
17.818182
73
0.678571
ed7a67134d8468a774f3c8db7cf702d510215a44
196
Fabricator(:app, from: OpsWorks::App) do initialize_with { @_klass.new(opsworks_stub) } id { SecureRandom.uuid } name { Fabricate.sequence(:name) { |i| "app#{i}" } } revision 'master' end
28
54
0.673469
e2c4fe3b70977d97a10dbda1e86706df5f6ae713
1,047
class Area < ActiveRecord::Base has_enumeration_for :status, with: AreaStatus, create_scopes: true, create_helpers: true has_many :areas, dependent: :delete_all has_many :resources, -> { order(:code) }, dependent: :delete_all has_many :activities, dependent: :delete_all belongs_to :institute belongs_to :area accepts_nested_attributes_for :resources, reject_if: :all_blank, allow_destroy: true scope :available, -> { where(status: AreaStatus::AVAILABLE) } scope :maintenance, -> { where(status: AreaStatus::MAINTENANCE) } scope :disjointed, -> { where(status: AreaStatus::DISJOINTED) } scope :reservable, -> { where(reservable: true) } scope :disponible, -> { reservable.available } before_save :up_case_code before_create :normalize_code validates :name, :code, :institute_id, presence: true validates :code, :uniqueness => { :case_sensitive => false } def normalize_code self.code = "#{institute.code}-#{self.code}" if institute.present? end def up_case_code code.upcase! end end
29.914286
90
0.722063
081577eddcdf8f4279c381fd23c9175c4ce7bd18
2,910
require 'test_helper' class PasswordResetsTest < ActionDispatch::IntegrationTest def setup ActionMailer::Base.deliveries.clear @user = users(:michael) end test "password resets" do get new_password_reset_path assert_template 'password_resets/new' assert_select 'input[name=?]', 'password_reset[email]' # メールアドレスが無効 post password_resets_path, params: { password_reset: { email: "" } } assert_not flash.empty? assert_template 'password_resets/new' # メールアドレスが有効 post password_resets_path, params: { password_reset: { email: @user.email } } assert_not_equal @user.reset_digest, @user.reload.reset_digest assert_equal 1, ActionMailer::Base.deliveries.size assert_not flash.empty? assert_redirected_to root_url # パスワード再設定フォームのテスト user = assigns(:user) # メールアドレスが無効 get edit_password_reset_path(user.reset_token, email: "") assert_redirected_to root_url # 無効なユーザー user.toggle!(:activated) get edit_password_reset_path(user.reset_token, email: user.email) assert_redirected_to root_url user.toggle!(:activated) # メールアドレスが有効で、トークンが無効 get edit_password_reset_path('wrong token', email: user.email) assert_redirected_to root_url # メールアドレスもトークンも有効 get edit_password_reset_path(user.reset_token, email: user.email) assert_template 'password_resets/edit' assert_select "input[name=email][type=hidden][value=?]", user.email # 無効なパスワードとパスワード確認 patch password_reset_path(user.reset_token), params: { email: user.email, user: { password: "foobaz", password_confirmation: "barquux" } } assert_select 'div#error_explanation' # パスワードが空 patch password_reset_path(user.reset_token), params: { email: user.email, user: { password: "", password_confirmation: "" } } assert_select 'div#error_explanation' # 有効なパスワードとパスワード確認 patch password_reset_path(user.reset_token), params: { email: user.email, user: { password: "foobaz", password_confirmation: "foobaz" } } assert is_logged_in? assert_not flash.empty? assert_redirected_to user assert_nil user.reload.reset_digest end test "expired token" do get new_password_reset_path post password_resets_path, params: { password_reset: { email: @user.email } } @user = assigns(:user) @user.update_attribute(:reset_sent_at, 3.hours.ago) patch password_reset_path(@user.reset_token), params: { email: @user.email, user: { password: "foobar", password_confirmation: "foobar" } } assert_response :redirect follow_redirect! assert_match /expired/i, response.body end end
36.375
72
0.657388
e81a89ac4c87f079c6cb2309be7486e03a13c231
298
class FontMiama < Formula head "https://github.com/google/fonts/raw/main/ofl/miama/Miama-Regular.ttf", verified: "github.com/google/fonts/" desc "Miama" homepage "https://fonts.google.com/specimen/Miama" def install (share/"fonts").install "Miama-Regular.ttf" end test do end end
27.090909
115
0.718121
d5ef87d7081b8eab119278d6840012fe56b41ad5
229
class CreateDeployments < ActiveRecord::Migration[5.0] def change create_table :deployments do |t| t.string :name t.references :app, foreign_key: true t.string :image t.timestamps end end end
19.083333
54
0.663755
d539606712f673c6f3219d741c41367f9fb5aa8a
703
require 'spec_helper' class Convection::Model::Template::Resource describe ElastiCacheSecurityGroup do let(:elasticache_template) do Convection.template do description 'Elasticache Test Template' elasticache_security_group 'MyRedisSecGroup' do description 'Redis cache security group' end end end subject do template_json .fetch('Resources') .fetch('MyRedisSecGroup') .fetch('Properties') end it 'has a description' do expect(subject['Description']).to eq('Redis cache security group') end private def template_json JSON.parse(elasticache_template.to_json) end end end
21.30303
72
0.665718
6a3ab826e0db53324886e0efef008c9ecc2a84dd
1,933
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::TimeSeriesInsights::Mgmt::V2018_08_15_preview module Models # # Properties required to create any resource tracked by Azure Resource # Manager. # class CreateOrUpdateTrackedResourceProperties include MsRestAzure # @return [String] The location of the resource. attr_accessor :location # @return [Hash{String => String}] Key-value pairs of additional # properties for the resource. attr_accessor :tags # # Mapper for CreateOrUpdateTrackedResourceProperties class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'CreateOrUpdateTrackedResourceProperties', type: { name: 'Composite', class_name: 'CreateOrUpdateTrackedResourceProperties', model_properties: { location: { client_side_validation: true, required: true, serialized_name: 'location', type: { name: 'String' } }, tags: { client_side_validation: true, required: false, serialized_name: 'tags', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } } } } } end end end end
28.850746
78
0.523021
bb3b43b5b2e15a34489a3e8554317f15d935ab61
2,588
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::RecoveryServicesSiteRecovery::Mgmt::V2016_08_10 module Models # # This class represents the details for a failover job. # class FailoverJobDetails < JobDetails include MsRestAzure def initialize @instanceType = "FailoverJobDetails" end attr_accessor :instanceType # @return [Array<FailoverReplicationProtectedItemDetails>] The test VM # details. attr_accessor :protected_item_details # # Mapper for FailoverJobDetails class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'FailoverJobDetails', type: { name: 'Composite', class_name: 'FailoverJobDetails', model_properties: { affected_object_details: { client_side_validation: true, required: false, serialized_name: 'affectedObjectDetails', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } }, instanceType: { client_side_validation: true, required: true, serialized_name: 'instanceType', type: { name: 'String' } }, protected_item_details: { client_side_validation: true, required: false, serialized_name: 'protectedItemDetails', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'FailoverReplicationProtectedItemDetailsElementType', type: { name: 'Composite', class_name: 'FailoverReplicationProtectedItemDetails' } } } } } } } end end end end
29.747126
92
0.493431
03be955ddcdbf102d8092a113dc947f282e353f7
2,573
# frozen_string_literal: true module Api::V2 class InputMappingsController < BaseController before_action :check_whodunnit!, only: %i[create update delete] def create activity = current_activity state_code = input_params[:attributes][:code] state = if state_code # ease client work allowing to pass the state code activity.project.state(state_code) else # find by relationships ? end activity_state = activity.activity_states.create!(input_attributes.merge(state_id: state.id)) # make stable id visible activity_state.reload render_activity_state(activity_state) end def index inputs = current_activity.activity_states render json: serializer_class.new(inputs, include: default_relationships).serialized_json end def update activity_state = current_activity.activity_states.find(params[:id]) state_code = input_params[:attributes][:code] state = if state_code # ease client work allowing to pass the state code activity_state.activity.project.state(state_code) else activity_state.state end activity_state.update!(input_attributes.merge(state_id: state.id)) render_activity_state(activity_state) end private def render_activity_state(activity_state) render( json: serializer_class.new( activity_state, include: default_relationships ).serialized_json ) end def default_relationships %i[input external_ref] end def current_project current_project_anchor.project end def current_activity current_project.activities.find(params[:topic_id]) end def serializer_class ::V2::ActivityStateSerializer end def input_params params.require(:data) .permit(:type, attributes: %i[ code formula name origin kind externalReference ]) end def input_attributes att = input_params[:attributes] { formula: att[:formula].presence, name: att[:name].presence, origin: att[:origin].presence, kind: att[:kind].presence, external_reference: att[:externalReference].presence } end end end
27.666667
99
0.598523
03b000476b171844483160a8616f06421ce12182
4,471
# frozen_string_literal: true module Jekyll module RemoteTheme class Downloader PROJECT_URL = "https://github.com/benbalter/jekyll-remote-theme" USER_AGENT = "Jekyll Remote Theme/#{VERSION} (+#{PROJECT_URL})" MAX_FILE_SIZE = 1 * (1024 * 1024 * 1024) # Size in bytes (1 GB) NET_HTTP_ERRORS = [ Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::OpenTimeout, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, ].freeze def initialize(theme, remote_headers) @theme = theme @remote_headers = remote_headers end def run if downloaded? Jekyll.logger.debug LOG_KEY, "Using existing #{theme.name_with_owner}" return end download unzip end def downloaded? @downloaded ||= theme_dir_exists? && !theme_dir_empty? end def remote_headers default_headers = { "User-Agent" => USER_AGENT, "Accept" => "application/vnd.github.v3+json", } @remote_headers ||= default_headers @remote_headers.merge(default_headers) end private attr_reader :theme def zip_file @zip_file ||= Tempfile.new([TEMP_PREFIX, ".zip"], :binmode => true) end def create_request(url) req = Net::HTTP::Get.new url.path remote_headers&.each do |key, value| req[key] = value unless value.nil? end req end def handle_response(response) raise_unless_success(response) enforce_max_file_size(response.content_length) response.read_body do |chunk| zip_file.write chunk end end def fetch(uri_str, limit = 10) Jekyll.logger.debug LOG_KEY, "Finding redirect of #{uri_str}" raise DownloadError, "Too many redirect" if limit.zero? url = URI.parse(uri_str) req = create_request(url) Net::HTTP.start(url.host, url.port, :use_ssl => true) do |http| http.request(req) do |response| case response when Net::HTTPSuccess handle_response(response) when Net::HTTPRedirection fetch(response["location"], limit - 1) else raise DownloadError, "#{response.code} - #{response.message}" end end end end def download Jekyll.logger.debug LOG_KEY, "Downloading #{zip_url} to #{zip_file.path}" fetch(zip_url) @downloaded = true rescue *NET_HTTP_ERRORS => e raise DownloadError, e.message end def raise_unless_success(response) return if response.is_a?(Net::HTTPSuccess) raise DownloadError, "#{response.code} - #{response.message}" end def enforce_max_file_size(size) return unless size && size > MAX_FILE_SIZE raise DownloadError, "Maximum file size of #{MAX_FILE_SIZE} bytes exceeded" end def unzip Jekyll.logger.debug LOG_KEY, "Unzipping #{zip_file.path} to #{theme.root}" # File IO is already open, rewind pointer to start of file to read zip_file.rewind Zip::File.open(zip_file) do |archive| archive.each { |file| file.extract path_without_name_and_ref(file.name) } end ensure zip_file.close zip_file.unlink end # Full URL to codeload zip download endpoint for the given theme def zip_url @zip_url ||= Addressable::URI.new( :scheme => theme.scheme, :host => theme.host, :path => [theme.owner, theme.name, "archive", theme.git_ref + ".zip"].join("/") ).normalize end def theme_dir_exists? theme.root && Dir.exist?(theme.root) end def theme_dir_empty? Dir["#{theme.root}/*"].empty? end # Codeload generated zip files contain a top level folder in the form of # THEME_NAME-GIT_REF/. While requests for Git repos are case insensitive, # the zip subfolder will respect the case in the repository's name, thus # making it impossible to predict the true path to the theme. In case we're # on a case-sensitive file system, strip the parent folder from all paths. def path_without_name_and_ref(path) Jekyll.sanitized_path theme.root, path.split("/").drop(1).join("/") end end end end
29.222222
91
0.607694
622b5da3539fe5902a7e4d641c33a5fbcd9ce785
8,273
# encoding: utf-8 require "rubygems/package" require "logstash/util/loggable" require "logstash/plugin" require "logstash/plugins/hooks_registry" module LogStash module Plugins class Registry include LogStash::Util::Loggable # Add a bit more sanity with when interacting with the rubygems' # specifications database, most of out code interact directly with really low level # components of bundler/rubygems we need to encapsulate that and this is a start. class GemRegistry LOGSTASH_METADATA_KEY = "logstash_plugin" class << self def installed_gems ::Gem::Specification end def logstash_plugins installed_gems .select { |spec| spec.metadata && spec.metadata[LOGSTASH_METADATA_KEY] } .collect { |spec| PluginRawContext.new(spec) } end end end class PluginRawContext HOOK_FILE = "logstash_registry.rb" NAME_DELIMITER = "-" attr_reader :spec def initialize(spec) @spec = spec @destructured_name = spec.name.split(NAME_DELIMITER) end def name @destructured_name[2..-1].join(NAME_DELIMITER) end def type @destructured_name[1] end # In the context of the plugin, the hook file available need to exist in any top level # required paths. # # Example for the logstash-output-elasticsearch we have this line in the gemspec. # # s.require_paths = ["lib"], so the we will expect to have a `logstash_registry.rb` file in the `lib` # directory. def hooks_file @hook_file ||= spec.full_require_paths.collect do |path| f = ::File.join(path, HOOK_FILE) ::File.exist?(f) ? f : nil end.compact.first end def has_hooks? !hooks_file.nil? end def execute_hooks! require hooks_file end end class PluginSpecification attr_reader :type, :name, :klass def initialize(type, name, klass) @type = type.to_sym @name = name @klass = klass end end class UniversalPluginSpecification < PluginSpecification def initialize(type, name, klass) super(type, name, klass) @instance = klass.new end def register(hooks, settings) @instance.register_hooks(hooks) @instance.additionals_settings(settings) end end attr_reader :hooks def initialize @registry = {} @hooks = HooksRegistry.new end def setup! load_available_plugins execute_universal_plugins end def execute_universal_plugins @registry.values .select { |specification| specification.is_a?(UniversalPluginSpecification) } .each { |specification| specification.register(hooks, LogStash::SETTINGS) } end def load_available_plugins GemRegistry.logstash_plugins.each do |plugin_context| # When a plugin has a HOOK_FILE defined, its the responsibility of the plugin # to register itself to the registry of available plugins. # # Legacy plugin will lazy register themselves if plugin_context.has_hooks? begin logger.debug("Executing hooks", :name => plugin_context.name, :type => plugin_context.type, :hooks_file => plugin_context.hooks_file) plugin_context.execute_hooks! rescue => e logger.error("error occured when loading plugins hooks file", :name => plugin_context.name, :type => plugin_context.type, :exception => e.message, :stacktrace => e.backtrace ) end end end end def lookup(type, plugin_name, &block) plugin = get(type, plugin_name) # Assume that we have a legacy plugin if plugin.nil? plugin = legacy_lookup(type, plugin_name) end if block_given? # if provided pass a block to do validation raise LoadError, "Block validation fails for plugin named #{plugin_name} of type #{type}," unless block.call(plugin.klass, plugin_name) end return plugin.klass end # The legacy_lookup method uses the 1.5->5.0 file structure to find and match # a plugin and will do a lookup on the namespace of the required class to find a matching # plugin with the appropriate type. def legacy_lookup(type, plugin_name) begin path = "logstash/#{type}s/#{plugin_name}" begin require path rescue LoadError # Plugin might be already defined in the current scope # This scenario often happen in test when we write an adhoc class end klass = namespace_lookup(type, plugin_name) plugin = lazy_add(type, plugin_name, klass) rescue => e logger.error("Problems loading a plugin with", :type => type, :name => plugin_name, :path => path, :error_message => e.message, :error_class => e.class, :error_backtrace => e.backtrace) raise LoadError, "Problems loading the requested plugin named #{plugin_name} of type #{type}. Error: #{e.class} #{e.message}" end plugin end def lookup_pipeline_plugin(type, name) LogStash::PLUGIN_REGISTRY.lookup(type, name) do |plugin_klass, plugin_name| is_a_plugin?(plugin_klass, plugin_name) end rescue LoadError, NameError => e logger.debug("Problems loading the plugin with", :type => type, :name => name) raise(LogStash::PluginLoadingError, I18n.t("logstash.pipeline.plugin-loading-error", :type => type, :name => name, :error => e.to_s)) end def lazy_add(type, name, klass) logger.debug("On demand adding plugin to the registry", :name => name, :type => type, :class => klass) add_plugin(type, name, klass) end def add(type, name, klass) logger.debug("Adding plugin to the registry", :name => name, :type => type, :class => klass) add_plugin(type, name, klass) end def get(type, plugin_name) @registry[key_for(type, plugin_name)] end def exists?(type, name) @registry.include?(key_for(type, name)) end def size @registry.size end private # lookup a plugin by type and name in the existing LogStash module namespace # ex.: namespace_lookup("filter", "grok") looks for LogStash::Filters::Grok # @param type [String] plugin type, "input", "output", "filter" # @param name [String] plugin name, ex.: "grok" # @return [Class] the plugin class or raises NameError # @raise NameError if plugin class does not exist or is invalid def namespace_lookup(type, name) type_const = "#{type.capitalize}s" namespace = LogStash.const_get(type_const) # the namespace can contain constants which are not for plugins classes (do not respond to :config_name) # namespace.constants is the shallow collection of all constants symbols in namespace # note that below namespace.const_get(c) should never result in a NameError since c is from the constants collection klass_sym = namespace.constants.find { |c| is_a_plugin?(namespace.const_get(c), name) } klass = klass_sym && namespace.const_get(klass_sym) raise(NameError) unless klass klass end # check if klass is a valid plugin for name # @param klass [Class] plugin class # @param name [String] plugin name # @return [Boolean] true if klass is a valid plugin for name def is_a_plugin?(klass, name) klass.ancestors.include?(LogStash::Plugin) && klass.respond_to?(:config_name) && klass.config_name == name end def add_plugin(type, name, klass) if !exists?(type, name) specification_klass = type == :universal ? UniversalPluginSpecification : PluginSpecification @registry[key_for(type, name)] = specification_klass.new(type, name, klass) else logger.debug("Ignoring, plugin already added to the registry", :name => name, :type => type, :klass => klass) end end def key_for(type, plugin_name) "#{type}-#{plugin_name}" end end end PLUGIN_REGISTRY = Plugins::Registry.new end
33.2249
187
0.646924
115a12f33bc87f85e7710ad129bae586970b1e40
1,439
# frozen_string_literal: true describe "POST /db/trailers/:id/publishing", type: :request do context "user does not sign in" do let!(:trailer) { create(:trailer, :unpublished) } it "user can not access this page" do post "/db/trailers/#{trailer.id}/publishing" trailer.reload expect(response.status).to eq(302) expect(flash[:alert]).to eq("ログインしてください") expect(trailer.published?).to eq(false) end end context "user who is not editor signs in" do let!(:user) { create(:registered_user) } let!(:trailer) { create(:trailer, :unpublished) } before do login_as(user, scope: :user) end it "user can not access" do post "/db/trailers/#{trailer.id}/publishing" trailer.reload expect(response.status).to eq(302) expect(flash[:alert]).to eq("アクセスできません") expect(trailer.published?).to eq(false) end end context "user who is editor signs in" do let!(:user) { create(:registered_user, :with_editor_role) } let!(:trailer) { create(:trailer, :unpublished) } before do login_as(user, scope: :user) end it "user can publish trailer" do expect(trailer.published?).to eq(false) post "/db/trailers/#{trailer.id}/publishing" trailer.reload expect(response.status).to eq(302) expect(flash[:notice]).to eq("公開しました") expect(trailer.published?).to eq(true) end end end
24.810345
63
0.641418
1a503b42c09ad815a9992261f254c60b2aa46758
4,511
# frozen_string_literal: true require "dry/monads/do" module Dry module Monads module Do # Do::All automatically wraps methods defined in a class with an unwrapping block. # Similar to what `Do.for(...)` does except wraps every method so you don't have # to list them explicitly. # # @example annotated example # # require 'dry/monads/do/all' # require 'dry/monads/result' # # class CreateUser # include Dry::Monads::Do::All # include Dry::Monads::Result::Mixin # # def call(params) # # Unwrap a monadic value using an implicitly passed block # # if `validates` returns Failure, the execution will be halted # values = yield validate(params) # user = create_user(values) # # If another block is passed to a method then takes # # precedence over the unwrapping block # safely_subscribe(values[:email]) { Logger.info("Already subscribed") } # # Success(user) # end # # def validate(params) # if params.key?(:email) # Success(email: params[:email]) # else # Failure(:no_email) # end # end # # def create_user(user) # # Here a block is passed to the method but we don't use it # UserRepo.new.add(user) # end # # def safely_subscribe(email) # repo = SubscriptionRepo.new # # if repo.subscribed?(email) # # This calls the logger because a block # # explicitly passed from `call` # yield # else # repo.subscribe(email) # end # end # end # module All # @private class MethodTracker < ::Module attr_reader :wrappers def initialize(wrappers) super() @wrappers = wrappers tracker = self module_eval do private define_method(:method_added) do |method| super(method) tracker.wrap_method(self, method) end define_method(:inherited) do |base| super(base) base.prepend(wrappers[base]) end def included(base) super All.included(base) end end end def extend_object(target) super target.prepend(wrappers[target]) end def wrap_method(target, method) visibility = Do.method_visibility(target, method) Do.wrap_method(wrappers[target], method, visibility) end end class << self # @api private def included(base) super wrappers = ::Hash.new { |h, k| h[k] = ::Module.new } tracker = MethodTracker.new(wrappers) base.extend(tracker) base.extend(InstanceMixin) unless base.is_a?(::Class) wrap_defined_methods(base, wrappers[base]) end # @api private def wrap_defined_methods(klass, target) klass.public_instance_methods(false).each do |m| Do.wrap_method(target, m, :public) end klass.protected_instance_methods(false).each do |m| Do.wrap_method(target, m, :protected) end klass.private_instance_methods(false).each do |m| Do.wrap_method(target, m, :private) end end end # @api private module InstanceMixin # @api private def extended(object) super wrapper = ::Module.new eigenclass = object.singleton_class eigenclass.prepend(wrapper) object.define_singleton_method(:singleton_method_added) do |method| super(method) next if method.equal?(:singleton_method_added) visibility = Do.method_visibility(eigenclass, method) Do.wrap_method(wrapper, method, visibility) end All.wrap_defined_methods(eigenclass, wrapper) end end extend InstanceMixin end end require "dry/monads/registry" register_mixin(:do, Do::All) end end
28.19375
88
0.522279
f890a7db0cce2465d577ad7e9f83eef3b602eae6
1,548
module NetSuite module Records class VendorBillItem include Support::Fields include Support::RecordRefs include Support::Records include Namespaces::TranPurch fields :amortization_end_date, :amortization_residual, :amortiz_start_date, :bin_numbers, :bill_variance_status, :description, :expiration_date, :gross_amt, :is_billable, :landed_cost, :line, :order_doc, :order_line, :quantity, :serial_numbers, :tax_rate_1, :tax_rate_2, :tax_1_amt, :vendor_name, :rate field :bill_receipts_list, RecordRefList field :custom_field_list, CustomFieldList field :options, CustomFieldList field :inventory_detail, InventoryDetail read_only_fields :amount record_refs :amortization_sched, :klass, :customer, :department, :item, :landed_cost_category, :location, :tax_code, :units def initialize(attributes_or_record = {}) case attributes_or_record when Hash initialize_from_attributes_hash(attributes_or_record) when self.class initialize_from_record(attributes_or_record) end end def initialize_from_record(record) self.attributes = record.send(:attributes) end def to_record rec = super if rec["#{record_namespace}:customFieldList"] rec["#{record_namespace}:customFieldList!"] = rec.delete("#{record_namespace}:customFieldList") end rec end end end end
32.25
120
0.664083
bf8c612e5770aaad7d002000ff228520ed450d2c
209
class String def is_binary_data? self.count( "^ -~", "^\r\n" ).fdiv(self.size) > 0.3 || self.index( "\x00" ) end if RUBY_VERSION.to_f < 1.9 def force_encoding(enc) self end end end
19
79
0.578947
9101d40be66218b9c033cd9d3b4f2e825cbd600e
937
require "anyway_config" module Seatrain # PRE-RELEASE: To be removed once the anyway_config 2.1 becomes available Anyway.loaders.override :yml, Anyway::Loaders::YAML class Config < Anyway::Config DOCR_URL = "registry.digitalocean.com" attr_config( :ruby_version, :pg_major_version, :node_major_version, :yarn_version, :bundler_version, :app_name, :production_image_name, :docker_registry, :docker_username, :docker_password, :docker_repository, :do_cluster_name, :hostname, :certificate_email, use_sidekiq: true, use_webpacker: true, release_namespace: "default", helm_timeout: "3m0s", required_secrets: [], secrets: {}, with_apt_packages: [] ) def uses_docr? docker_registry == DOCR_URL end def app_name super || Rails.root.to_s.split("/").last end end end
21.790698
75
0.640342
e8549094e08a54be6194b01b09eb65958d3589ff
965
# # Author:: Joshua Timberman (<[email protected]>) # Author:: Graeme Mathieson (<[email protected]>) # Cookbook Name:: homebrew # Resources:: tap # # Copyright 2011-2016, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # actions :tap, :untap default_action :tap attribute :name, name_attribute: true, kind_of: String, regex: %r{^[\w-]+(?:\/[\w-]+)+$} attribute :tapped, kind_of: [TrueClass, FalseClass]
30.15625
74
0.701554
9142ed7bdd1280a877d7b655ce7be034f944f072
213
::Sequel.migration do up do create_table(:snp_assays) do primary_key :id String :name String :allele_x String :allele_y end end down do drop_table(:snp_assays) end end
14.2
32
0.629108
bb79ac54819e9cb3b4b0472b9626adeef557810f
128
class RemoveBookColumnFromBooks < ActiveRecord::Migration[5.1] def change remove_column :books, :book, :boolean end end
21.333333
62
0.757813
79f393f05702afee74b59301bfb2cc11a00691c4
331
#!/usr/bin/env ruby dir = File.dirname(File.expand_path(__FILE__)) $LOAD_PATH.unshift dir + "/../lib" require "coremidi" require "pp" # This will output a big list of Endpoint objects. Endpoint objects are what's used to input # and output MIDI messages pp CoreMIDI::Device.all.map { |device| device.endpoints.values }.flatten
25.461538
92
0.743202
39c59b04ccdd4012be757b3afba9887c2ff41e88
1,162
class Crypto::Scraper def self.scrape_coinranking doc = Nokogiri::HTML(open("https://coinranking.com/")) #create an array of all the coins along with their attributes set that to a variable @coins = doc.css(".coin-list__body .coin-list__body__row").collect do |row| each_coin = row.css("span").collect do |text| text.text #binding.pry end #this opens up the link for each page and within that link i grab the description of each coin and shovel that into the each_coin array page2 = Nokogiri::HTML(open(row.attr("href"))) each_coin << page2.css(".coin-page__description").text #binding.pry end self.new_coin_scrape end def self.new_coin_scrape #iterate through coins variable and take an individual coin and assign each of its attributes to their corresponding attributes @coins.each do |coin| #binding.pry new_coin = Crypto::Coin.new(name = coin[2], price = coin[3], market_cap = coin[6], change = coin[9].gsub("\t","").gsub("\n",""), description = coin[11]) Crypto::Coin.all << new_coin #@all_coins << new_coin end Crypto::Coin.all end end
35.212121
156
0.674699
b916d9d1ca0d5a9fad808bcc2a00b4f8483ef408
510
require 'bundler' Bundler.setup require 'rspec' require 'jschematic' RSpec::Matchers.define :accept do |instance_value| match do |validator| begin validator.accepts?(instance_value) rescue Jschematic::ValidationError false end end end module Jschematic class Parent include Jschematic::Composite def initialize(opts) self.id = opts["id"] end end class Child include Jschematic::Element def accepts?(instance) !!instance end end end
15
50
0.684314
edc74ec6d8f64c11d0b964ba6c49cfc92163f793
4,232
# frozen_string_literal: true # It probably makes sense to configure PUMA_CLOUDWATCH_DIMENSION_VALUE to include your application name. # For example if you're application is named "myapp", this would be a good value to use: # # PUMA_CLOUDWATCH_DIMENSION_VALUE=myapp-puma # # Then you can get all the metrics for the pool_capacity for your myapp-puma app. # # Summing the metric tells you the total available pool_capacity for the myapp-puma app. # module PumaCloudwatch class Metrics class Sender def initialize @namespace = ENV['PUMA_CLOUDWATCH_NAMESPACE'] || "WebServer" @dimension_name = ENV['PUMA_CLOUDWATCH_DIMENSION_NAME'] || "App" @dimension_value = ENV['PUMA_CLOUDWATCH_DIMENSION_VALUE'] || "puma" @enabled = ENV['PUMA_CLOUDWATCH_ENABLED'] || false @dimensions = [ { name: @dimension_name, value: @dimension_value }, { name: 'Host', value: Socket.gethostname } ] end def call(metrics) put_metric_data( namespace: @namespace, metric_data: build_metric_data(metrics) ) end # Input @metrics example: # # [{:backlog=>[0, 0], # :running=>[0, 0], # :pool_capacity=>[16, 16], # :max_threads=>[16, 16]}] # # Output example: # # [{:metric_name=>"backlog", # :statistic_values=>{:sample_count=>2, :sum=>0, :minimum=>0, :maximum=>0}}, # {:metric_name=>"running", # :statistic_values=>{:sample_count=>2, :sum=>0, :minimum=>0, :maximum=>0}}, # {:metric_name=>"pool_capacity", # :statistic_values=>{:sample_count=>2, :sum=>32, :minimum=>16, :maximum=>16}}, # {:metric_name=>"max_threads", # :statistic_values=>{:sample_count=>2, :sum=>32, :minimum=>16, :maximum=>16}}] # # Resources: # pool_capcity and max_threads are the important metrics # https://dev.to/amplifr/monitoring-puma-web-server-with-prometheus-and-grafana-5b5o # def build_metric_data(metrics) metric_data = metrics.collect do |metric_name, values| { metric_name: metric_name, dimensions: @dimensions, statistic_values: { sample_count: values.length, sum: values.sum, minimum: values.min, maximum: values.max } } end metric_data << build_busy_percentage_metric_datum(metrics) metric_data end private def build_busy_percentage_metric_datum(metrics) values = [] metrics['Running'].length.times do |i| values << (1.0 - metrics['PoolCapacity'][i].to_f / metrics['MaxThreads'][i].to_f) * 100.0 end { metric_name: 'LoadAverage', dimensions: @dimensions, statistic_values: { sample_count: values.length, sum: values.sum, minimum: values.min, maximum: values.max } } end def put_metric_data(params) if ENV['PUMA_CLOUDWATCH_DEBUG'] message = "sending data to cloudwatch:" message = "NOOP: #{message}" unless enabled? puts message pp params end if enabled? begin cloudwatch.put_metric_data(params) rescue Aws::CloudWatch::Errors::AccessDenied => e puts "WARN: #{e.class} #{e.message}" puts "Unable to send metrics to CloudWatch" rescue PumaCloudwatch::Error => e puts "WARN: #{e.class} #{e.message}" puts "Unable to send metrics to CloudWatch" end end end def enabled? !!@enabled end def cloudwatch @cloudwatch ||= Aws::CloudWatch::Client.new rescue Aws::Errors::MissingRegionError => e # Happens when: # 1. ~/.aws/config is not also setup locally # 2. On EC2 instance when AWS_REGION not set puts "WARN: #{e.class} #{e.message}" raise PumaCloudwatch::Error.new(e.message) end end end end
30.666667
104
0.568762
03c43dc6d9ee569352dd127bd3fc5c57f428d39c
942
# frozen_string_literal: true require "test_helper" # Tests to assure reviewers can mark agreement variables for resubmission. class Reviewer::AgreementVariablesControllerTest < ActionDispatch::IntegrationTest setup do @reviewer = users(:reviewer_on_released) @submitted = data_requests(:submitted) @specific_purpose = agreement_variables(:submitted_specific_purpose) end def agreement_variable_params { reviewer_comment: "Please be more specific." } end test "should update review" do login(@reviewer) patch reviewer_agreement_variable_url(@submitted, @specific_purpose, format: "js"), params: { agreement_variable: agreement_variable_params } @specific_purpose.reload assert_equal true, @specific_purpose.resubmission_required? assert_equal "Please be more specific.", @specific_purpose.reviewer_comment assert_template "show" assert_response :success end end
30.387097
97
0.766454
e8910c1455559aa043b8be0b37b7585c1825448e
20,986
=begin * Name: newtabbedpane.rb * Description : This is radically simplified tabbedpane. The earlier version was too complex with multiple forms and pads, and a scrollform. This uses the external form and has some very simple programming to handle the whole thing. * Author: rkumar (http://github.com/rkumar/rbcurse/) * Date: 2011-10-20 * License: Same as Ruby's License (http://www.ruby-lang.org/LICENSE.txt) * Last update: 2014-03-28 20:39 == CHANGES As of 1.5.0, this replaces the earlier TabbedPane which now lies in lib/rbhex/deprecated/widgets in the rbhex repo. == TODO on start first buttons bottom should not be lined. Alt-1-9 to goto tabs add remove tabs at any time - started, untested events for tab add/remove/etc =end require 'rbhex/core' ## module Rbhex class TabbedPane < Widget dsl_property :title, :title_attrib # what kind of buttons, if this is a window, :ok :ok_camcel :ok_apply_cancel dsl_accessor :button_type attr_reader :button_row # index of tab that is currently open attr_reader :current_tab def initialize form=nil, config={}, &block @_events ||= [] @_events.push(:PRESS) @button_gap = 2 init_vars super @focusable = true @editable = true @col_offset = 2 raise ArgumentError, "NewTabbedPane : row or col not set: r: #{@row} c: #{@col} " unless @row && @col end # Add a tab # @param String name of tab, may have ampersand for hotkey/accelerator def tab title, config={}, &block #@tab_components[title]=[] #@tabs << Tab.new(title, self, config, &block) insert_tab @tabs.count, title, config, &block self end alias :add_tab :tab # a shortcut for binding a command to a press of an action button # The block will be passed # This is only relevant if you have asked for buttons to be created, which is # only relevant in a TabbedWindow # ActionEvent has source event and action_command def command *args, &block bind :PRESS, *args, &block end # -------------- tab maintenance commands ------------------ # # insert a tab at index, with title def insert_tab index, title, config={}, &block @tabs.insert(index, Tab.new(title, self, config, &block) ) end # remove given tab def remove_tab tab @tabs.delete tab self end # remove all tabs def remove_all @tabs = [] self end # remove tab at given index, defaulting to current def remove_tab_at index = @current_tab @tabs.delete_at index end def repaint @current_tab ||= 0 @button_row ||= @row + 2 @separator_row = @button_row + 1 # hope we have it by now, where to print separator @separator_row0 = @button_row - 1 unless @button_row == @row + 1 @separator_row2 = @row + @height - 3 # hope we have it by now, where to print separator #return unless @repaint_required if @buttons.empty? _create_buttons @components = @buttons.dup @components.push(*@tabs[@current_tab].items) create_action_buttons @components.push(*@action_buttons) elsif @tab_changed @components = @buttons.dup @components.push(*@tabs[@current_tab].items) @components.push(*@action_buttons) @tab_changed = false end # if some major change has happened then repaint everything if @repaint_required $log.debug " NEWTAB repaint graphic #{@graphic} " print_borders unless @suppress_borders # do this once only, unless everything changes print_separator1 @components.each { |e| e.repaint_all(true); e.repaint } else @components.each { |e| e.repaint } end # if repaint_required print_border if (@suppress_borders == false && @repaint_all) # do this once only, unless everything changes @repaint_required = false end def handle_key ch $log.debug " NEWTABBED handle_key #{ch} " return if @components.empty? _multiplier = ($multiplier == 0 ? 1 : $multiplier ) # should this go here 2011-10-19 unless @_entered $log.warn "WARN: calling ON_ENTER since in this situation it was not called" on_enter end #if ch == KEY_TAB #$log.debug "NEWTABBED GOTO NEXT" #return goto_next_component #elsif ch == KEY_BTAB #return goto_prev_component #end comp = @current_component $log.debug " NEWTABBED handle_key #{ch}: #{comp}" if comp ret = comp.handle_key(ch) $log.debug " NEWTABBED handle_key#{ch}: #{comp} returned #{ret} " if ret != :UNHANDLED comp.repaint # NOTE: if we don;t do this, then it won't get repainted. I will have to repaint ALL # in repaint of this. return ret end $log.debug "XXX NEWTABBED key unhandled by comp #{comp.name} " else Ncurses.beep $log.warn "XXX NEWTABBED key unhandled NULL comp" end case ch when ?\C-c.getbyte(0) $multiplier = 0 return 0 when ?0.getbyte(0)..?9.getbyte(0) $log.debug " VIM coming here to set multiplier #{$multiplier} " $multiplier *= 10 ; $multiplier += (ch-48) return 0 end ret = process_key ch, self # allow user to map left and right if he wants if ret == :UNHANDLED case ch when KEY_UP, KEY_BTAB # form will pick this up and do needful return goto_prev_component #unless on_first_component? when KEY_LEFT # if i don't check for first component, key will go back to form, # but not be processes. so focussed remain here, but be false. # In case of returnign an unhandled TAB, on_leave will happen and cursor will move to # previous component outside of this. return goto_prev_component unless on_first_component? when KEY_RIGHT, KEY_TAB return goto_next_component #unless on_last_component? when KEY_DOWN if on_a_button? return goto_first_item else return goto_next_component #unless on_last_component? end else #@_entered = false return :UNHANDLED end end $multiplier = 0 return 0 end # on enter processing # Very often the first may be a label ! def on_enter # if BTAB, the last comp if $current_key == KEY_BTAB @current_component = @components.last else @current_component = @components.first end return unless @current_component $log.debug " NEWTABBED came to ON_ENTER #{@current_component} " set_form_row @_entered = true end def on_leave @_entered = false super end # takes focus to first item (after buttons) def goto_first_item bc = @buttons.count @components[bc..-1].each { |c| if c.focusable leave_current_component @current_component = c set_form_row break end } end # takes focus to last item def goto_last_item bc = @buttons.count f = nil @components[bc..-1].each { |c| if c.focusable f = c end } if f leave_current_component @current_component = f set_form_row end end # take focus to the next component or item # Called from DOWN, RIGHT or Tab def goto_next_component if @current_component != nil leave_current_component if on_last_component? @_entered = false return :UNHANDLED end @current_index = @components.index(@current_component) index = @current_index + 1 index.upto(@components.length-1) do |i| f = @components[i] if f.focusable @current_index = i @current_component = f return set_form_row end end end @_entered = false return :UNHANDLED end # take focus to prev component or item # Called from LEFT, UP or Back Tab def goto_prev_component if @current_component != nil leave_current_component if on_first_component? @_entered = false return :UNHANDLED end @current_index = @components.index(@current_component) index = @current_index -= 1 index.downto(0) do |i| f = @components[i] if f.focusable @current_index = i @current_component = f return set_form_row end end end return :UNHANDLED end # private def set_form_row return :UNHANDLED if @current_component.nil? $log.debug " NEWTABBED on enter sfr #{@current_component} " @current_component.on_enter @current_component.set_form_row # why was this missing in vimsplit. is it # that on_enter does a set_form_row @current_component.set_form_col # XXX @current_component.repaint # XXX compo should do set_form_row and col if it has that end # private def set_form_col return if @current_component.nil? $log.debug " #{@name} NEWTABBED set_form_col calling sfc for #{@current_component.name} " @current_component.set_form_col end # leave the component we are on. # This should be followed by all containers, so that the on_leave action # of earlier comp can be displayed, such as dimming components selections def leave_current_component @current_component.on_leave # NOTE this is required, since repaint will just not happen otherwise # Some components are erroneously repainting all, after setting this to true so it is # working there. @current_component.repaint_required true $log.debug " after on_leave VIMS XXX #{@current_component.focussed} #{@current_component.name}" @current_component.repaint end # is focus on first component def on_first_component? @current_component == @components.first end # is focus on last component def on_last_component? @current_component == @components.last end # returns true if user on an action button # @return true or false def on_a_button? @components.index(@current_component) < @buttons.count end # set focus on given component # Sometimes you have the handle to component, and you want to move focus to it def goto_component comp return if comp == @current_component leave_current_component @current_component = comp set_form_row end # set current tab to given tab # @return self def set_current_tab t return if @current_tab == t @current_tab = t goto_component @components[t] @tab_changed = true @repaint_required = true self end def DEPRECATED_handle_key ch # :nodoc map_keys unless @keys_mapped ret = process_key ch, self @multiplier = 0 return :UNHANDLED if ret == :UNHANDLED return 0 end # Put all the housekeeping stuff at the end private def init_vars @buttons = [] @tabs = [] #@tab_components = {} @bottombuttons = [] # # I'll keep current tabs comps in this to simplify @components = [] @_entered = false end def map_keys @keys_mapped = true #bind_key(?q, :myproc) #bind_key(32, :myproc) end # creates the tab buttons (which are radio buttons) def _create_buttons $log.debug "XXX: INSIDE create_buttons col_offset #{@col_offset} " v = Variable.new r = @button_row # @row + 1 col = @col + @col_offset @tabs.each_with_index { |t, i| txt = t.text @buttons << TabButton.new(nil) do variable v text txt name txt #value txt row r col col surround_chars ['',''] selected_background 'green' selected_foreground 'white' end b = @buttons.last b.command do set_current_tab i end b.form = @form b.override_graphic @graphic col += txt.length + @button_gap } end # _create_buttons private def print_borders width = @width height = @height-1 window = @graphic startcol = @col startrow = @row @color_pair = get_color($datacolor) $log.debug "NTP #{name}: window.print_border #{startrow}, #{startcol} , h:#{height}, w:#{width} , @color_pair, @attr " window.print_border startrow, startcol, height, width, @color_pair, @attr print_title end def print_separator1 width = @width height = @height-1 window = @graphic startcol = @col startrow = @row @color_pair = get_color($datacolor) r = @separator_row c = @col + @col_offset urcorner = [] #window.printstring r, c, '-' * (@width-2), @color_pair, @attr window.mvwhline( r, @col+1, Ncurses::ACS_HLINE, @width-2) @buttons.each_with_index do |b, i| l = b.text.length if b.selected? if false #c == @col + @col_offset cc = c ll = l+1 else cc = c-1 ll = l+2 end #rr = r -1 #unless rr == @col window.printstring r, cc, " "*ll, @color_pair, @attr #window.printstring r, cc-1, FFI::NCurses::ACS_HLINE.chr*ll, @color_pair, @attr #window.printstring r-2, cc, FFI::NCurses::ACS_HLINE.chr*ll, @color_pair, @attr window.mvwaddch r, cc-1, FFI::NCurses::ACS_LRCORNER unless cc-1 <= @col window.mvwaddch r, c+l+1, FFI::NCurses::ACS_LLCORNER else window.mvwaddch r, c+l+1, FFI::NCurses::ACS_BTEE end #window.printstring r-2, c, FFI::NCurses::ACS_HLINE*l, @color_pair, @attr #tt = b.text #window.printstring r, c, tt, @color_pair, @attr c += l + 1 #window.mvwaddch r, c, '+'.ord window.mvwaddch r-1, c, FFI::NCurses::ACS_VLINE window.mvwaddch r-2, c, FFI::NCurses::ACS_URCORNER #ACS_TTEE #window.mvwaddch r-2, c+1, '/'.ord urcorner << c c+=@button_gap end window.mvwhline( @separator_row0, @col + 1, Ncurses::ACS_HLINE, c-@col-1-@button_gap) window.mvwhline( @separator_row2, @col + 1, Ncurses::ACS_HLINE, @width-2) urcorner.each do |c| window.mvwaddch r-2, c, FFI::NCurses::ACS_URCORNER #ACS_TTEE end end def print_title return unless @title _title = @title if @title.length > @width - 2 _title = @title[0..@width-2] end @graphic.printstring( @row, @col+(@width-_title.length)/2, _title, @color_pair, @title_attrib) unless @title.nil? end # # Decides which buttons are to be created # create the buttons at the bottom OK/ APPLY/ CANCEL def create_action_buttons return unless @button_type case @button_type.to_s.downcase when "ok" make_buttons ["&OK"] when "ok_cancel" #, "input", "list", "field_list" make_buttons %w[&OK &Cancel] when "ok_apply_cancel" #, "input", "list", "field_list" make_buttons %w[&OK &Apply &Cancel] when "yes_no" make_buttons %w[&Yes &No] when "yes_no_cancel" make_buttons ["&Yes", "&No", "&Cancel"] when "custom" raise "Blank list of buttons passed to custom" if @buttons.nil? or @buttons.size == 0 make_buttons @buttons else $log.warn "No buttontype passed for creating tabbedpane. Not creating any" #make_buttons ["&OK"] end end # actually creates the action buttons def make_buttons names @action_buttons = [] $log.debug "XXX: came to NTP make buttons FORM= #{@form.name} names #{names} " total = names.inject(0) {|total, item| total + item.length + 4} bcol = center_column total # this craps out when height is zero brow = @row + @height-2 brow = FFI::NCurses.LINES-2 if brow < 0 $log.debug "XXX: putting buttons :on #{brow} : #{@row} , #{@height} " button_ct=0 tpp = self names.each_with_index do |bname, ix| text = bname #underline = @underlines[ix] if [email protected]? button = Button.new nil do text text name bname row brow col bcol #underline underline highlight_background $reversecolor color $datacolor bgcolor $datacolor end @action_buttons << button button.form = @form button.override_graphic @graphic index = button_ct tpp = self button.command { |form| @selected_index = index; @stop = true; # ActionEvent has source event and action_command fire_handler :PRESS, ActionEvent.new(tpp, index, button.text) #throw(:close, @selected_index) } button_ct += 1 bcol += text.length+6 end end def center_column textlen width = @col + @width return (width-textlen)/2 end ## ADD ABOVE end # class class Tab attr_accessor :text attr_reader :config attr_reader :items attr_accessor :parent_component attr_accessor :index attr_accessor :button # so you can set an event on it 2011-10-4 attr_accessor :row_offset attr_accessor :col_offset def initialize text, parent_component, aconfig={}, &block @text = text @items = [] @config = aconfig @parent_component = parent_component @row_offset ||= 2 @col_offset ||= 2 @config.each_pair { |k,v| variable_set(k,v) } instance_eval &block if block_given? end def item widget widget.form = @parent_component.form widget.override_graphic @parent_component.form.window # these will fail if TP put inside some other container. NOTE widget.row ||= 0 widget.col ||= 0 # If we knew it was only widget we could expand it if widget.kind_of?(Rbhex::Container) #|| widget.respond_to?(:width) widget.width ||= @parent_component.width-3 end # Darn ! this was setting Label to fully height if widget.kind_of?(Rbhex::Container) #|| widget.respond_to?(:height) widget.height ||= @parent_component.height-3 end # i don't know button_offset as yet widget.row += @row_offset + @parent_component.row + 1 widget.col += @col_offset + @parent_component.col @items << widget end end # class tab class TabButton < RadioButton attr_accessor :display_tab_on_traversal def getvalue_for_paint @text end def selected? @variable.value == @value end end end # module if __FILE__ == $PROGRAM_NAME require 'rbhex/core/util/app' require 'rbhex/core/widgets/rcontainer' App.new do #r = Container.new nil, :row => 1, :col => 2, :width => 40, :height => 10, :title => "A container" r = Container.new nil, :suppress_borders => true f1 = field "name", :maxlen => 20, :display_length => 20, :bgcolor => :white, :color => :black, :text => "abc", :label => ' Name: ' f2 = field "email", :display_length => 20, :bgcolor => :white, :color => :blue, :text => "[email protected]", :label => 'Email: ' f3 = radio :group => :grp, :text => "red", :value => "RED", :color => :red f4 = radio :group => :grp, :text => "blue", :value => "BLUE", :color => :blue f5 = radio :group => :grp, :text => "green", :value => "GREEN", :color => :green r.add(f1) r.add(f2) r.add(f3,f4,f5) TabbedPane.new @form, :row => 3, :col => 5, :width => 60, :height => 20 do title "User Setup" button_type :ok_apply_cancel tab "&Profile" do item Field.new nil, :row => 2, :col => 2, :text => "enter your name", :label => ' Name: ' item Field.new nil, :row => 3, :col => 2, :text => "enter your email", :label => 'Email: ' end tab "&Settings" do item CheckBox.new nil, :row => 2, :col => 2, :text => "Use HTTPS", :mnemonic => 'u' item CheckBox.new nil, :row => 3, :col => 2, :text => "Quit with confirm", :mnemonic => 'q' end tab "&Term" do radio = Variable.new item RadioButton.new nil, :row => 2, :col => 2, :text => "&xterm", :value => "xterm", :variable => radio item RadioButton.new nil, :row => 3, :col => 2, :text => "sc&reen", :value => "screen", :variable => radio radio.update_command() {|rb| ENV['TERM']=rb.value } end tab "Conta&iner" do item r end end end # app end
33.048819
124
0.601115
b9b62c8373ebb2885f459c8479f1a054e9355ebd
757
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. before_filter :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :password, :admin, :password_confirmation, :remember_me) } devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login, :username, :password, :admin, :remember_me) } devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :password, :admin, :password_confirmation, :current_password) } end protect_from_forgery with: :exception before_action :authenticate_user! end
47.3125
141
0.772787
38c64a82b1d9356597dcceeceeb67f18b474049d
495
class ReviewsController < ApplicationController def create @review = Review.create(review_params) @review.project.user.notifications = true @review.project.user.save render 'reviews/show', :layout => false end def destroy @review = Review.find(params[:id]) project = @review.project @review.destroy redirect_to user_project_path(project.user, project) end private def review_params params.require(:review).permit(:author_id, :project_id, :content, :rating) end end
21.521739
76
0.749495
e8ce1be394a8bc842576501bda19a9ec51ef15f2
1,899
require 'rubygems' require 'colors' require 'columnize' require 'net/http' require 'json' class Falconstock def initialize() @lookup_response = [] @quote_response = [] @lookup_url = 'http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?' @quote_url = 'http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?' end def config_dir_exists? return File.directory?('~/.falconstock') end def config_file_exists? return File.exists?('~/.falcon-stock/.falconstock.yml') end def lookup_company(company) uri = URI("#{@lookup_url}input=#{company}") @lookup_response = JSON.parse(Net::HTTP.get(uri)) if @lookup_response.count == 0 puts "Could not find #{company}".colorize(:red) exit 1 end end def lookup_quote(company) uri = URI("#{@quote_url}symbol=#{company}") @quote_response = JSON.parse(Net::HTTP.get(uri)) if @quote_response['Status'] != 'SUCCESS' puts @quote_response['Message'].split('.').first.colorize(:red) exit 1 end end def lookup_company_display(company) lookup_company(company) @lookup_response.each do |resp| puts "#{resp['Symbol']} - #{resp['Name']} - #{resp['Exchange']}" end end def lookup_quote_display(company) lookup_quote(company) company_name = "#{@quote_response['Name']} - #{@quote_response['Symbol']}" puts company_name.colorize(:blue) puts "Last Price: $#{@quote_response['LastPrice']} - #{@quote_response['Timestamp']}".colorize(:green) if @quote_response['Change'].to_s.include?('-') puts "Price Change: $#{@quote_response['Change']}".colorize(:red) puts "% Change: #{@quote_response['ChangePercent']}".colorize(:red) else puts "Price Change: $#{@quote_response['Change']}".colorize(:green) puts "% Change: #{@quote_response['ChangePercent']}".colorize(:green) end puts '' end end
27.521739
106
0.656135
1dc54eacd46c002550c2231e50225c59b2540248
2,064
require 'bundler/setup' Bundler.setup(:default, 'test', 'development') require 'tempfile' require 'pp' require 'shoulda' require 'matchy' require 'mocha' require 'mongo_mapper' require File.expand_path(File.dirname(__FILE__) + '/../lib/joint') MongoMapper.database = "testing" class Test::Unit::TestCase def setup MongoMapper.database.collections.each(&:remove) end def assert_difference(expression, difference = 1, message = nil, &block) b = block.send(:binding) exps = Array.wrap(expression) before = exps.map { |e| eval(e, b) } yield exps.each_with_index do |e, i| error = "#{e.inspect} didn't change by #{difference}" error = "#{message}.\n#{error}" if message after = eval(e, b) assert_equal(before[i] + difference, after, error) end end def assert_no_difference(expression, message = nil, &block) assert_difference(expression, 0, message, &block) end def assert_grid_difference(difference=1, &block) assert_difference("MongoMapper.database['fs.files'].find().count", difference, &block) end def assert_no_grid_difference(&block) assert_grid_difference(0, &block) end end class Asset include MongoMapper::Document plugin Joint key :title, String attachment :image attachment :file has_many :embedded_assets end class EmbeddedAsset include MongoMapper::EmbeddedDocument plugin Joint key :title, String attachment :image attachment :file end class BaseModel include MongoMapper::Document plugin Joint attachment :file end class Image < BaseModel; attachment :image end class Video < BaseModel; attachment :video end module JointTestHelpers def all_files [@file, @image, @image2, @test1, @test2] end def rewind_files all_files.each { |file| file.rewind } end def open_file(name) f = File.open(File.join(File.dirname(__FILE__), 'fixtures', name), 'r') f.binmode f end def grid @grid ||= Mongo::Grid.new(MongoMapper.database) end def key_names [:id, :name, :type, :size] end end
21.5
90
0.698643
8713acf822f9ebf539340b520c0a525f20abf9f8
279
require('rspec') require('scrabble') describe('String#scrabble') do it('returns a scrabble score for a letter') do expect("a".scrabble()).to(eq(1)) end it('returns a scrabble score for a word') do expect("abciou".scrabble()).to(eq(10)) end end
19.928571
50
0.623656
ab733fb2de1fa5a4b163a66bdbaeb54c867dfa2e
1,228
# frozen_string_literal: true require 'test_helper' class StorefrontAccessTokenTest < Test::Unit::TestCase def test_create_storefront_access_token fake("storefront_access_tokens", method: :post, body: load_fixture('storefront_access_token')) storefront_access_token = ShopifyAPI::StorefrontAccessToken.create(title: 'Test') assert_equal(1, storefront_access_token.id) assert_equal("Test", storefront_access_token.title) end def test_delete_storefront_access_token fake('storefront_access_tokens/1', method: :get, status: 200, body: load_fixture('storefront_access_token')) fake('storefront_access_tokens/1', method: :delete, status: 200, body: 'destroyed') storefront_access_tokens = ShopifyAPI::StorefrontAccessToken.find(1) assert(storefront_access_tokens.destroy) end def test_get_storefront_access_tokens fake("storefront_access_tokens", method: :get, status: 201, body: load_fixture('storefront_access_tokens')) tokens = ShopifyAPI::StorefrontAccessToken.all assert_equal(2, tokens.size) assert_equal(1, tokens.first.id) assert_equal(2, tokens.last.id) assert_equal('Test 1', tokens.first.title) assert_equal('Test 2', tokens.last.title) end end
39.612903
112
0.775244