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
ffb252dbd4b425d5a2da069b325c267dc0d2196a
15,527
test_name 'Calling all functions.. test in progress!' tag 'audit:medium', 'audit:acceptance' # create single manifest calling all functions step 'Apply manifest containing all function calls' def manifest_call_each_function_from_array(functions) manifest = '' # use index to work around oregano's immutable variables # use variables so we can concatenate strings functions.each_with_index do |function,index| if function[:rvalue] manifest << "$pre#{index} = \"sayeth #{function[:name].capitalize}: Scope(Class[main]): \" " manifest << "$output#{index} = #{function[:name]}(#{function[:args]}) " manifest << "#{function[:lambda]} notice \"${pre#{index}}${output#{index}}\"\n" else manifest << "$pre#{index} = \"sayeth #{function[:name].capitalize}: \" " manifest << "notice \"${pre#{index}}\"\n" manifest << "#{function[:name]}(#{function[:args]}) " manifest << "#{function[:lambda]}\n" end end manifest end generator = '' agents.each do |agent| testdir = agent.tmpdir('calling_all_functions') if agent["platform"] =~ /win/ generator = {:args => '"c:/windows/system32/tasklist.exe"', :expected => /\nImage Name/} else generator = {:args => '"/bin/date"', :expected => /\w\w\w.*?\d\d:\d\d\:\d\d/} end # create list of 3x functions and args # notes: hiera functions are well tested elsewhere, included for completeness # special cases: contain (call this from call_em_all) # do fail last because it errors out functions_3x = [ {:name => :alert, :args => '"consider yourself on alert"', :lambda => nil, :expected => 'consider yourself on alert', :rvalue => false}, {:name => :binary_file, :args => '"call_em_all/rickon.txt"', :lambda => nil, :expected => '', :rvalue => true}, #{:name => :break, :args => '', :lambda => nil, :expected => '', :rvalue => false}, # this is explicitly called from call_em_all module which is included below #{:name => :contain, :args => 'call_em_all', :lambda => nil, :expected => '', :rvalue => true}, # below doens't instance the resource. no output {:name => :create_resources, :args => 'notify, {"w"=>{message=>"winter is coming"}}', :lambda => nil, :expected => '', :rvalue => false}, {:name => :crit, :args => '"consider yourself critical"', :lambda => nil, :expected => 'consider yourself critical', :rvalue => false}, {:name => :debug, :args => '"consider yourself bugged"', :lambda => nil, :expected => '', :rvalue => false}, # no output expected unless run with debug {:name => :defined, :args => 'File["/tmp"]', :lambda => nil, :expected => 'false', :rvalue => true}, {:name => :digest, :args => '"Sansa"', :lambda => nil, :expected => 'f16491bf0133c6103918b2edcd00cf89', :rvalue => true}, {:name => :dig, :args => '[100]', :lambda => nil, :expected => '[100]', :rvalue => true}, {:name => :emerg, :args => '"consider yourself emergent"', :lambda => nil, :expected => 'consider yourself emergent', :rvalue => false}, {:name => :err, :args => '"consider yourself in err"', :lambda => nil, :expected => 'consider yourself in err', :rvalue => false}, {:name => :file, :args => '"call_em_all/rickon.txt"', :lambda => nil, :expected => 'who?', :rvalue => true}, {:name => :fqdn_rand, :args => '100000', :lambda => nil, :expected => /Fqdn_rand: Scope\(Class\[main\]\): \d{1,5}/, :rvalue => true}, # generate requires a fully qualified exe; which requires specifics for windows vs posix #{:name => :generate, :args => generator[:args], :lambda => nil, :expected => generator[:expected], :rvalue => true}, {:name => :hiera_array, :args => 'date,default_array', :lambda => nil, :expected => 'default_array', :rvalue => true}, {:name => :hiera_hash, :args => 'date,default_hash', :lambda => nil, :expected => 'default_hash', :rvalue => true}, {:name => :hiera_include, :args => 'date,call_em_all', :lambda => nil, :expected => '', :rvalue => false}, {:name => :hiera, :args => 'date,default_date', :lambda => nil, :expected => 'default_date', :rvalue => true}, {:name => :include, :args => 'call_em_all', :lambda => nil, :expected => '', :rvalue => false}, {:name => :info, :args => '"consider yourself informed"', :lambda => nil, :expected => '', :rvalue => false}, # no ouput unless in debug mode {:name => :inline_template, :args => '\'empty<%= @x %>space\'', :lambda => nil, :expected => 'emptyspace', :rvalue => true}, # test the living life out of this thing in lookup.rb, and it doesn't allow for a default value #{:name => :lookup, :args => 'date,lookup_date', :lambda => nil, :expected => '', :rvalue => true}, # well tested elsewhere {:name => :md5, :args => '"Bran"', :lambda => nil, :expected => '723f9ac32ceb881ddf4fb8fc1020cf83', :rvalue => true}, # Integer.new {:name => :Integer, :args => '"100"', :lambda => nil, :expected => '100', :rvalue => true}, {:name => :notice, :args => '"consider yourself under notice"', :lambda => nil, :expected => 'consider yourself under notice', :rvalue => false}, {:name => :realize, :args => 'User[arya]', :lambda => nil, :expected => '', :rvalue => false}, # TODO: create a virtual first {:name => :regsubst, :args => '"Cersei","Cer(\\\\w)ei","Daenery\\\\1"',:lambda => nil, :expected => 'Daenerys', :rvalue => true}, # explicitly called in call_em_all; implicitly called by the include above #{:name => :require, :args => '[4,5,6]', :lambda => nil, :expected => '', :rvalue => true}, # 4x output contains brackets around scanf output {:name => :scanf, :args => '"Eddard Stark","%6s"', :lambda => nil, :expected => '[Eddard]', :rvalue => true}, {:name => :sha1, :args => '"Sansa"', :lambda => nil, :expected => '4337ce5e4095e565d51e0ef4c80df1fecf238b29', :rvalue => true}, {:name => :shellquote, :args => '["-1", "--two"]', :lambda => nil, :expected => '-1 --two', :rvalue => true}, # 4x output contains brackets around split output and commas btwn values {:name => :split, :args => '"9,8,7",","', :lambda => nil, :expected => '[9, 8, 7]', :rvalue => true}, {:name => :sprintf, :args => '"%b","123"', :lambda => nil, :expected => '1111011', :rvalue => true}, {:name => :step, :args => '[100,99],1', :lambda => nil, :expected => 'Iterator[Integer]-Value', :rvalue => true}, # explicitly called in call_em_all #{:name => :tag, :args => '[4,5,6]', :lambda => nil, :expected => '', :rvalue => true}, {:name => :tagged, :args => '"yer_it"', :lambda => nil, :expected => 'false', :rvalue => true}, {:name => :template, :args => '"call_em_all/template.erb"', :lambda => nil, :expected => 'no defaultsno space', :rvalue => true}, {:name => :type, :args => '42', :lambda => nil, :expected => 'Integer[42, 42]', :rvalue => true}, {:name => :versioncmp, :args => '"1","2"', :lambda => nil, :expected => '-1', :rvalue => true}, {:name => :warning, :args => '"consider yourself warned"', :lambda => nil, :expected => 'consider yourself warned', :rvalue => false}, # do this one last or it will not allow the others to run. {:name => :fail, :args => '"Jon Snow"', :lambda => nil, :expected => /Error:.*Jon Snow/, :rvalue => false}, ] oregano_version = on(agent, oregano('--version')).stdout.chomp functions_4x = [ {:name => :assert_type, :args => '"String[1]", "Valar morghulis"', :lambda => nil, :expected => 'Valar morghulis', :rvalue => true}, {:name => :each, :args => '[1,2,3]', :lambda => '|$x| {$x}', :expected => '[1, 2, 3]', :rvalue => true}, {:name => :epp, :args => '"call_em_all/template.epp",{x=>droid}', :lambda => nil, :expected => 'This is the droid you are looking for!', :rvalue => true}, {:name => :filter, :args => '[4,5,6]', :lambda => '|$x| {true}', :expected => '[4, 5, 6]', :rvalue => true}, # find_file() called by binary_file #{:name => :find_file, :args => '[4,5,6]', :lambda => '|$x| {true}', :expected => '[4, 5, 6]', :rvalue => true}, {:name => :inline_epp, :args => '\'<%= $x %>\',{x=>10}', :lambda => nil, :expected => '10', :rvalue => true}, #{:name => :lest, :args => '100', :lambda => '"100"', :expected => '100', :rvalue => true}, {:name => :map, :args => '[7,8,9]', :lambda => '|$x| {$x * $x}', :expected => '[49, 64, 81]', :rvalue => true}, {:name => :match, :args => '"abc", /b/', :lambda => nil, :expected => '[b]', :rvalue => true}, #{:name => :next, :args => '100', :lambda => nil, :expected => '100', :rvalue => true}, {:name => :reduce, :args => '[4,5,6]', :lambda => '|$sum, $n| { $sum+$n }', :expected => '15', :rvalue => true}, #{:name => :return, :args => '100', :lambda => nil, :expected => '100', :rvalue => true}, {:name => :reverse_each, :args => '[100,99]', :lambda => nil, :expected => 'Iterator[Integer]-Value', :rvalue => true}, # :reuse,:recycle {:name => :slice, :args => '[1,2,3,4,5,6], 2', :lambda => nil, :expected => '[[1, 2], [3, 4], [5, 6]]', :rvalue => true}, {:name => :strftime, :args => 'Timestamp("4216-09-23T13:14:15.123 UTC"), "%C"', :lambda => nil, :expected => '42', :rvalue => true}, {:name => :then, :args => '100', :lambda => '|$x| {$x}', :expected => '100', :rvalue => true}, {:name => :with, :args => '1, "Catelyn"', :lambda => '|$x, $y| {"$x, $y"}', :expected => '1, Catelyn', :rvalue => true}, ] module_manifest = <<PP File { ensure => directory, } file { '#{testdir}':; '#{testdir}/environments':; '#{testdir}/environments/production':; '#{testdir}/environments/production/modules':; '#{testdir}/environments/production/modules/tagged':; '#{testdir}/environments/production/modules/tagged/manifests':; '#{testdir}/environments/production/modules/contained':; '#{testdir}/environments/production/modules/contained/manifests':; '#{testdir}/environments/production/modules/required':; '#{testdir}/environments/production/modules/required/manifests':; '#{testdir}/environments/production/modules/call_em_all':; '#{testdir}/environments/production/modules/call_em_all/manifests':; '#{testdir}/environments/production/modules/call_em_all/templates':; '#{testdir}/environments/production/modules/call_em_all/files':; } file { '#{testdir}/environments/production/modules/tagged/manifests/init.pp': ensure => file, content => 'class tagged { notice tagged tag yer_it }', } file { '#{testdir}/environments/production/modules/required/manifests/init.pp': ensure => file, content => 'class required { notice required }', } file { '#{testdir}/environments/production/modules/contained/manifests/init.pp': ensure => file, content => 'class contained { notice contained }', } file { '#{testdir}/environments/production/modules/call_em_all/manifests/init.pp': ensure => file, content => 'class call_em_all { notice call_em_all contain contained require required tag yer_it }', } file { '#{testdir}/environments/production/modules/call_em_all/files/rickon.txt': ensure => file, content => 'who?', } file { '#{testdir}/environments/production/modules/call_em_all/templates/template.epp': ensure => file, content => 'This is the <%= $x %> you are looking for!', } file { '#{testdir}/environments/production/modules/call_em_all/templates/template.erb': ensure => file, content => 'no defaults<%= @x %>no space', } PP apply_manifest_on(agent, module_manifest, :catch_failures => true) scope = 'Scope(Class[main]):' # apply the 4x function manifest with future parser oregano_apply_options = {:modulepath => "#{testdir}/environments/production/modules/", :acceptable_exit_codes => 1} oregano_apply_options[:future_parser] = true if oregano_version =~ /\A3\./ apply_manifest_on(agent, manifest_call_each_function_from_array(functions_4x), oregano_apply_options) do |result| functions_4x.each do |function| expected = "#{function[:name].capitalize}: #{scope} #{function[:expected]}" unless agent['locale'] == 'ja' assert_match(expected, result.output, "#{function[:name]} output didn't match expected value") end end end file_path = agent.tmpfile('apply_manifest.pp') create_remote_file(agent, file_path, manifest_call_each_function_from_array(functions_3x)) trusted_3x = oregano_version =~ /\A3\./ ? '--trusted_node_data ' : '' on(agent, oregano("apply #{trusted_3x} --color=false --modulepath #{testdir}/environments/production/modules/ #{file_path}"), :acceptable_exit_codes => 1 ) do |result| functions_3x.each do |function| # append the function name to the matcher so it's more expressive if function[:expected].is_a?(String) if function[:name] == :fail expected = function[:expected] elsif function[:name] == :crit expected = "#{function[:name].capitalize}ical: #{scope} #{function[:expected]}" elsif function[:name] == :emerg expected = "#{function[:name].capitalize}ency: #{scope} #{function[:expected]}" elsif function[:name] == :err expected = "#{function[:name].capitalize}or: #{scope} #{function[:expected]}" elsif function[:expected] == '' expected = "#{function[:name].capitalize}: #{function[:expected]}" else expected = "#{function[:name].capitalize}: #{scope} #{function[:expected]}" end elsif function[:expected].is_a?(Regexp) expected = function[:expected] else raise 'unhandled function expectation type (we allow String or Regexp)' end unless agent['locale'] == 'ja' assert_match(expected, result.output, "#{function[:name]} output didn't match expected value") end end end end
66.354701
173
0.537515
e2fd777d13196d7a3ff7167d7f29f7537cf489a8
4,113
# frozen_string_literal: true require 'spec_helper' describe Clusters::Providers::Gcp do it { is_expected.to belong_to(:cluster) } it { is_expected.to validate_presence_of(:zone) } include_examples 'provider status', :cluster_provider_gcp describe 'default_value_for' do let(:gcp) { build(:cluster_provider_gcp) } it "has default value" do expect(gcp.zone).to eq('us-central1-a') expect(gcp.num_nodes).to eq(3) expect(gcp.machine_type).to eq('n1-standard-2') end end describe 'validation' do subject { gcp.valid? } context 'when validates gcp_project_id' do let(:gcp) { build(:cluster_provider_gcp, gcp_project_id: gcp_project_id) } context 'when gcp_project_id is shorter than 1' do let(:gcp_project_id) { '' } it { is_expected.to be_falsey } end context 'when gcp_project_id is longer than 63' do let(:gcp_project_id) { 'a' * 64 } it { is_expected.to be_falsey } end context 'when gcp_project_id includes invalid character' do let(:gcp_project_id) { '!!!!!!' } it { is_expected.to be_falsey } end context 'when gcp_project_id is valid' do let(:gcp_project_id) { 'gcp-project-1' } it { is_expected.to be_truthy } end end context 'when validates num_nodes' do let(:gcp) { build(:cluster_provider_gcp, num_nodes: num_nodes) } context 'when num_nodes is string' do let(:num_nodes) { 'A3' } it { is_expected.to be_falsey } end context 'when num_nodes is nil' do let(:num_nodes) { nil } it { is_expected.to be_falsey } end context 'when num_nodes is smaller than 1' do let(:num_nodes) { 0 } it { is_expected.to be_falsey } end context 'when num_nodes is valid' do let(:num_nodes) { 3 } it { is_expected.to be_truthy } end end end describe '#has_rbac_enabled?' do subject { gcp.has_rbac_enabled? } context 'when cluster is legacy_abac' do let(:gcp) { create(:cluster_provider_gcp, :abac_enabled) } it { is_expected.to be_falsey } end context 'when cluster is not legacy_abac' do let(:gcp) { create(:cluster_provider_gcp) } it { is_expected.to be_truthy } end end describe '#knative_pre_installed?' do subject { gcp.knative_pre_installed? } context 'when cluster is cloud_run' do let(:gcp) { create(:cluster_provider_gcp) } it { is_expected.to be_falsey } end context 'when cluster is not cloud_run' do let(:gcp) { create(:cluster_provider_gcp, :cloud_run_enabled) } it { is_expected.to be_truthy } end end describe '#api_client' do subject { gcp.api_client } context 'when status is creating' do let(:gcp) { build(:cluster_provider_gcp, :creating) } it 'returns Cloud Platform API clinet' do expect(subject).to be_an_instance_of(GoogleApi::CloudPlatform::Client) expect(subject.access_token).to eq(gcp.access_token) end end context 'when status is created' do let(:gcp) { build(:cluster_provider_gcp, :created) } it { is_expected.to be_nil } end context 'when status is errored' do let(:gcp) { build(:cluster_provider_gcp, :errored) } it { is_expected.to be_nil } end end describe '#nullify_credentials' do let(:provider) { create(:cluster_provider_gcp, :creating) } before do expect(provider.access_token).to be_present expect(provider.operation_id).to be_present end it 'removes access_token and operation_id' do provider.nullify_credentials expect(provider.access_token).to be_nil expect(provider.operation_id).to be_nil end end describe '#assign_operation_id' do let(:provider) { create(:cluster_provider_gcp, :scheduled) } let(:operation_id) { 'operation-123' } it 'sets operation_id' do provider.assign_operation_id(operation_id) expect(provider.operation_id).to eq(operation_id) end end end
24.927273
80
0.653781
281d360dcc5af79bb84a2dd81bc7ea4862f4313f
747
cask "font-sarasa-gothic" do version "0.34.6" sha256 "9a38c7a510b187446319891e96086efc03cf5dc4828e2956865a32915744bc78" url "https://github.com/be5invis/Sarasa-Gothic/releases/download/v#{version}/sarasa-gothic-ttc-#{version}.7z" name "Sarasa Gothic" name "更纱黑体" name "更紗黑體" name "更紗ゴシック" name "사라사고딕" desc "CJK programming font based on Iosevka and Source Han Sans" homepage "https://github.com/be5invis/Sarasa-Gothic" font "sarasa-bold.ttc" font "sarasa-bolditalic.ttc" font "sarasa-extralight.ttc" font "sarasa-extralightitalic.ttc" font "sarasa-italic.ttc" font "sarasa-light.ttc" font "sarasa-lightitalic.ttc" font "sarasa-regular.ttc" font "sarasa-semibold.ttc" font "sarasa-semibolditalic.ttc" end
29.88
111
0.745649
280807eec29fd089682b17e8e1dadc7d489f0b65
110
class HomeController < ApplicationController skip_before_action :authenticate_user! def index end end
13.75
44
0.809091
112491ed198469bfa6f23f7d3c7cf163947c2b3d
703
class CreateTogForumTables < ActiveRecord::Migration def self.up create_table :tog_forum_forums do |t| t.string :title t.integer :user_id t.timestamps end create_table :tog_forum_topics do |t| t.integer :forum_id t.integer :user_id t.string :title t.text :body t.datetime :last_post_at t.integer :last_post_by t.timestamps end create_table :tog_forum_posts do |t| t.integer :topic_id t.integer :user_id t.text :body t.timestamps end end def self.down drop_table :tog_forum_forums drop_table :tog_forum_topics drop_table :tog_forum_posts end end
20.676471
52
0.634424
bb5709a522e3635790911cf38d6ce3bf4cfd1015
10,577
# frozen_string_literal: true # # Cookbook Name:: icinga2 # Provider:: environment # # Copyright 2014, Virender Khatri # # 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. # # provider class Chef class Provider # provides icinga2_environment class Icinga2Environment < Chef::Provider::LWRPBase provides :icinga2_environment if respond_to?(:provides) def whyrun_supported? true end action :create do object_template end action :delete do object_template end protected def object_template search_pattern = new_resource.search_pattern || "chef_environment:#{new_resource.environment}" server_region = new_resource.server_region if new_resource.limit_region && !server_region server_region = node['ec2']['placement_availability_zone'].chop if node.key?('ec2') end env_resources = new_resource.env_resources || Icinga2::Search.new(:environment => new_resource.environment, :enable_cluster_hostgroup => new_resource.enable_cluster_hostgroup, :cluster_attribute => new_resource.cluster_attribute, :enable_application_hostgroup => new_resource.enable_application_hostgroup, :application_attribute => new_resource.application_attribute, :enable_role_hostgroup => new_resource.enable_role_hostgroup, :ignore_node_error => new_resource.ignore_node_error, :use_fqdn_resolv => new_resource.use_fqdn_resolv, :failover_fqdn_address => new_resource.failover_fqdn_address, :ignore_resolv_error => new_resource.ignore_resolv_error, :exclude_recipes => new_resource.exclude_recipes, :exclude_roles => new_resource.exclude_roles, :env_custom_vars => new_resource.env_custom_vars, :env_skip_node_vars => new_resource.env_skip_node_vars, :env_filter_node_vars => new_resource.env_filter_node_vars, :limit_region => new_resource.limit_region, :server_region => server_region, :search_pattern => search_pattern, :add_node_vars => new_resource.add_node_vars, :add_inet_custom_vars => new_resource.add_inet_custom_vars, :add_cloud_custom_vars => new_resource.add_cloud_custom_vars).environment_resources template_file_name = new_resource.zone ? "host_#{new_resource.environment}_#{new_resource.zone}_#{new_resource.name}.conf" : "host_#{new_resource.environment}_#{new_resource.name}.conf" env_hosts = {} env_hosts = env_resources['nodes'] if env_resources.key?('nodes') && env_resources['nodes'].is_a?(Hash) if new_resource.zone env_resources_path = ::File.join(node['icinga2']['zones_dir'], new_resource.zone, template_file_name) directory ::File.join(node['icinga2']['zones_dir'], new_resource.zone) do owner node['icinga2']['user'] group node['icinga2']['group'] action :create only_if { !env_hosts.empty? } end else env_resources_path = ::File.join(node['icinga2']['objects_dir'], template_file_name) end hosts_template = template env_resources_path do source new_resource.template cookbook new_resource.cookbook owner node['icinga2']['user'] group node['icinga2']['group'] mode 0o640 variables(:environment => new_resource.environment, :hosts => env_hosts, :host_display_name_attr => new_resource.host_display_name_attr, :import => new_resource.import, :check_command => new_resource.check_command, :max_check_attempts => new_resource.max_check_attempts, :check_period => new_resource.check_period, :notification_period => new_resource.notification_period, :check_interval => new_resource.check_interval, :retry_interval => new_resource.retry_interval, :enable_notifications => new_resource.enable_notifications, :enable_active_checks => new_resource.enable_active_checks, :enable_passive_checks => new_resource.enable_passive_checks, :enable_event_handler => new_resource.enable_event_handler, :enable_flapping => new_resource.enable_flapping, :enable_perfdata => new_resource.enable_perfdata, :event_command => new_resource.event_command, :flapping_threshold => new_resource.flapping_threshold, :volatile => new_resource.volatile, :command_endpoint => new_resource.command_endpoint, :notes => new_resource.notes, :notes_url => new_resource.notes_url, :action_url => new_resource.action_url, :icon_image => new_resource.icon_image, :icon_image_alt => new_resource.icon_image_alt) notifies platform?('windows') ? :restart : :reload, 'service[icinga2]' end return true if hosts_template.updated? || create_hostgroups(env_resources) if node['icinga2']['enable_env_pki'] return true if hosts_template.updated? || create_endpoints(env_resources) return true if hosts_template.updated? || create_zones(env_resources) unless node['icinga2']['enable_env_custom_pki'] return true if hosts_template.updated? || create_pki_tickets(env_resources) end end end def create_hostgroups(env_resources) env_hostgroups = [] # environment hostgroups env_hostgroups += env_resources['clusters'] if new_resource.enable_cluster_hostgroup && env_resources.key?('clusters') && env_resources['clusters'].is_a?(Array) env_hostgroups += env_resources['applications'] if new_resource.enable_application_hostgroup && env_resources.key?('applications') && env_resources['applications'].is_a?(Array) env_hostgroups += env_resources['roles'] if new_resource.enable_role_hostgroup && env_resources.key?('roles') && env_resources['roles'].is_a?(Array) env_hostgroups.uniq! hostgroup_template = icinga2_envhostgroup new_resource.environment do groups env_hostgroups zone new_resource.zone end hostgroup_template.updated? end def create_endpoints(env_resources) nodes = env_resources['nodes'] env_endpoints = nodes.map { |n| n[1]['fqdn'] } endpoint_template = icinga2_envendpoint new_resource.environment do endpoints env_endpoints port new_resource.endpoint_port log_duration new_resource.endpoint_log_duration zone new_resource.zone end endpoint_template.updated? end def create_zones(env_resources) nodes = env_resources['nodes'] env_zones = nodes.map { |n| n[1]['fqdn'] } zone_template = icinga2_envzone new_resource.environment do zones env_zones parent new_resource.zone_parent zone new_resource.zone end zone_template.updated? end def create_pki_tickets(env_resources) env = new_resource.environment salt = new_resource.pki_ticket_salt nodes = env_resources['nodes'] all_fqdns = nodes.map { |n| n[1]['fqdn'] } tickets = {} begin databag_item = data_bag_item('icinga2', "#{env}-pki-tickets") tickets = databag_item['tickets'] if tickets['salt'] != salt uncreated_tickets_fqdns = all_fqdns else tickets_fqdns = tickets.map { |k, _v| k } uncreated_tickets_fqdns = all_fqdns - tickets_fqdns end rescue uncreated_tickets_fqdns = all_fqdns end unless uncreated_tickets_fqdns.empty? uncreated_tickets_fqdns.each do |f| ruby_block "Create PKI-Ticket #{f}" do block do ticket_bash = Mixlib::ShellOut.new("icinga2 pki ticket --cn #{f} --salt #{salt}") ticket_bash.run_command tickets[f] = ticket_bash.stdout.chomp databag_item = Chef::DataBagItem.new databag_item.data_bag('icinga2') databag_item.raw_data = { 'id' => "#{env}-pki-tickets", 'tickets' => tickets, 'salt' => salt, } databag_item.save end action :create end end end end end end end
47.644144
193
0.563392
7ac22972a98dde2253017e75ad2c4b50241f9d60
432
#load File.dirname(__FILE__) + "/spec_helper.rb" # Don't include the spec helper here to determine describe "To run the app" do it "you should have the aws-s3 gem installed" do lambda{ require 'rubygems' gem 'aws-s3' }.should_not raise_error end it "you should have the capistrano gem installed" do lambda{ require 'rubygems' gem 'capistrano' }.should_not raise_error end end
21.6
54
0.668981
1ad8d694450c858422e47fba7ca90b911d4a4707
13,398
require 'spec_helper' describe 'responseModel' do include_context 'this api' def app ThisApi::ResponseModelApi end subject do get '/swagger_doc/something' JSON.parse(last_response.body) end it 'documents index action' do expect(subject['paths']['/something']['get']['responses']).to eq( '200' => { 'description' => 'OK', 'schema' => { 'type' => 'array', 'items' => { '$ref' => '#/definitions/ThisApi::Entities::Something' } } } ) end it 'should document specified models as show action' do expect(subject['paths']['/something/{id}']['get']['responses']).to eq( '200' => { 'description' => 'OK', 'schema' => { '$ref' => '#/definitions/ThisApi::Entities::Something' } }, '403' => { 'description' => 'Refused to return something', 'schema' => { '$ref' => '#/definitions/ThisApi::Entities::Error' } } ) expect(subject['definitions'].keys).to include 'ThisApi::Entities::Error' expect(subject['definitions']['ThisApi::Entities::Error']).to eq( 'type' => 'object', 'description' => 'This returns something or an error', 'properties' => { 'code' => { 'type' => 'string', 'description' => 'Error code' }, 'message' => { 'type' => 'string', 'description' => 'Error message' } } ) expect(subject['definitions'].keys).to include 'ThisApi::Entities::Something' expect(subject['definitions']['ThisApi::Entities::Something']).to eq( 'type' => 'object', 'description' => 'This returns something', 'properties' => { 'text' => { 'type' => 'string', 'description' => 'Content of something.' }, 'colors' => { 'type' => 'array', 'items' => { 'type' => 'string' }, 'description' => 'Colors' }, 'kind' => { '$ref' => '#/definitions/ThisApi::Entities::Kind', 'description' => 'The kind of this something.' }, 'kind2' => { '$ref' => '#/definitions/ThisApi::Entities::Kind', 'description' => 'Secondary kind.' }, 'kind3' => { '$ref' => '#/definitions/ThisApi::Entities::Kind', 'description' => 'Tertiary kind.' }, 'tags' => { 'type' => 'array', 'items' => { '$ref' => '#/definitions/ThisApi::Entities::Tag' }, 'description' => 'Tags.' }, 'relation' => { '$ref' => '#/definitions/ThisApi::Entities::Relation', 'description' => 'A related model.' }, 'code' => { 'type' => 'string', 'description' => 'Error code' }, 'message' => { 'type' => 'string', 'description' => 'Error message' }, 'attr' => { 'type' => 'string', 'description' => 'Attribute' } }, 'required' => ['attr'] ) expect(subject['definitions'].keys).to include 'ThisApi::Entities::Kind' expect(subject['definitions']['ThisApi::Entities::Kind']).to eq( 'type' => 'object', 'properties' => { 'title' => { 'type' => 'string', 'description' => 'Title of the kind.' } } ) expect(subject['definitions'].keys).to include 'ThisApi::Entities::Relation' expect(subject['definitions']['ThisApi::Entities::Relation']).to eq( 'type' => 'object', 'properties' => { 'name' => { 'type' => 'string', 'description' => 'Name' } } ) expect(subject['definitions'].keys).to include 'ThisApi::Entities::Tag' expect(subject['definitions']['ThisApi::Entities::Tag']).to eq( 'type' => 'object', 'properties' => { 'name' => { 'type' => 'string', 'description' => 'Name' } } ) end end describe 'building definitions from given entities' do before :all do module TheseApi module Entities class Values < Grape::Entity expose :guid, documentation: { desc: 'Some values', values: %w[a b c], default: 'c' } expose :uuid, documentation: { desc: 'customer uuid', type: String, format: 'own', example: 'e3008fba-d53d-4bcc-a6ae-adc56dff8020' } end class Kind < Grape::Entity expose :id, documentation: { type: Integer, desc: 'id of the kind.', values: [1, 2], read_only: true } expose :title, documentation: { type: String, desc: 'Title of the kind.', read_only: 'false' } expose :type, documentation: { type: String, desc: 'Type of the kind.', read_only: 'true' } end class Relation < Grape::Entity expose :name, documentation: { type: String, desc: 'Name' } end class Tag < Grape::Entity expose :name, documentation: { type: 'string', desc: 'Name', example: -> { 'random_tag' } } end class Nested < Grape::Entity expose :nested, documentation: { type: Hash, desc: 'Nested entity' } do expose :some1, documentation: { type: 'String', desc: 'Nested some 1' } expose :some2, documentation: { type: 'String', desc: 'Nested some 2' } end expose :nested_with_alias, as: :aliased do expose :some1, documentation: { type: 'String', desc: 'Alias some 1' } end expose :deep_nested, documentation: { type: 'Object', desc: 'Deep nested entity' } do expose :level_1, documentation: { type: 'Object', desc: 'More deepest nested entity' } do expose :level_2, documentation: { type: 'String', desc: 'Level 2' } end end expose :nested_required do expose :some1, documentation: { required: true, desc: 'Required some 1' } expose :attr, as: :some2, documentation: { required: true, desc: 'Required some 2' } expose :some3, documentation: { desc: 'Optional some 3' } end expose :nested_array, documentation: { type: 'Array', desc: 'Nested array' } do expose :id, documentation: { type: 'Integer', desc: 'Collection element id' } expose :name, documentation: { type: 'String', desc: 'Collection element name' } end end class Polymorphic < Grape::Entity expose :obj, as: :kind, if: ->(instance, _) { instance.type == 'kind' }, using: Kind, documentation: { desc: 'Polymorphic Kind' } expose :obj, as: :values, if: ->(instance, _) { instance.type == 'values' }, using: Values, documentation: { desc: 'Polymorphic Values' } expose :not_using_obj, as: :str, if: ->(instance, _) { instance.instance_of?(String) }, documentation: { desc: 'Polymorphic String' } expose :not_using_obj, as: :num, if: ->(instance, _) { instance.instance_of?(Number) }, documentation: { desc: 'Polymorphic Number', type: 'Integer' } end class SomeEntity < Grape::Entity expose :text, documentation: { type: 'string', desc: 'Content of something.' } expose :kind, using: Kind, documentation: { type: 'TheseApi::Kind', desc: 'The kind of this something.' } expose :kind2, using: Kind, documentation: { desc: 'Secondary kind.' } expose :kind3, using: TheseApi::Entities::Kind, documentation: { desc: 'Tertiary kind.' } expose :tags, using: TheseApi::Entities::Tag, documentation: { desc: 'Tags.', is_array: true } expose :relation, using: TheseApi::Entities::Relation, documentation: { type: 'TheseApi::Relation', desc: 'A related model.' } expose :values, using: TheseApi::Entities::Values, documentation: { desc: 'Tertiary kind.' } expose :nested, using: TheseApi::Entities::Nested, documentation: { desc: 'Nested object.' } expose :polymorphic, using: TheseApi::Entities::Polymorphic, documentation: { desc: 'Polymorphic Model' } expose :merged_attribute, using: ThisApi::Entities::Nested, merge: true end end class ResponseEntityApi < Grape::API format :json desc 'This returns something', is_array: true, entity: Entities::SomeEntity get '/some_entity' do something = OpenStruct.new text: 'something' present something, with: Entities::SomeEntity end add_swagger_documentation end end end def app TheseApi::ResponseEntityApi end subject do get '/swagger_doc' JSON.parse(last_response.body)['definitions'] end it 'prefers entity over other `using` values' do expect(subject['TheseApi::Entities::Values']).to eql( 'type' => 'object', 'properties' => { 'guid' => { 'type' => 'string', 'enum' => %w[a b c], 'default' => 'c', 'description' => 'Some values' }, 'uuid' => { 'type' => 'string', 'format' => 'own', 'description' => 'customer uuid', 'example' => 'e3008fba-d53d-4bcc-a6ae-adc56dff8020' } } ) expect(subject['TheseApi::Entities::Kind']).to eql( 'type' => 'object', 'properties' => { 'id' => { 'type' => 'integer', 'format' => 'int32', 'description' => 'id of the kind.', 'enum' => [1, 2], 'readOnly' => true }, 'title' => { 'type' => 'string', 'description' => 'Title of the kind.', 'readOnly' => false }, 'type' => { 'type' => 'string', 'description' => 'Type of the kind.', 'readOnly' => true } } ) expect(subject['TheseApi::Entities::Tag']).to eql( 'type' => 'object', 'properties' => { 'name' => { 'type' => 'string', 'description' => 'Name', 'example' => 'random_tag' } } ) expect(subject['TheseApi::Entities::Relation']).to eql( 'type' => 'object', 'properties' => { 'name' => { 'type' => 'string', 'description' => 'Name' } } ) expect(subject['TheseApi::Entities::Nested']).to eq( 'properties' => { 'nested' => { 'type' => 'object', 'properties' => { 'some1' => { 'type' => 'string', 'description' => 'Nested some 1' }, 'some2' => { 'type' => 'string', 'description' => 'Nested some 2' } }, 'description' => 'Nested entity' }, 'aliased' => { 'type' => 'object', 'properties' => { 'some1' => { 'type' => 'string', 'description' => 'Alias some 1' } } }, 'deep_nested' => { 'type' => 'object', 'properties' => { 'level_1' => { 'type' => 'object', 'properties' => { 'level_2' => { 'type' => 'string', 'description' => 'Level 2' } }, 'description' => 'More deepest nested entity' } }, 'description' => 'Deep nested entity' }, 'nested_required' => { 'type' => 'object', 'properties' => { 'some1' => { 'type' => 'string', 'description' => 'Required some 1' }, 'some2' => { 'type' => 'string', 'description' => 'Required some 2' }, 'some3' => { 'type' => 'string', 'description' => 'Optional some 3' } }, 'required' => %w[some1 some2] }, 'nested_array' => { 'type' => 'array', 'items' => { 'type' => 'object', 'properties' => { 'id' => { 'type' => 'integer', 'format' => 'int32', 'description' => 'Collection element id' }, 'name' => { 'type' => 'string', 'description' => 'Collection element name' } } }, 'description' => 'Nested array' } }, 'type' => 'object' ) expect(subject['TheseApi::Entities::Polymorphic']).to eql( 'type' => 'object', 'properties' => { 'kind' => { '$ref' => '#/definitions/TheseApi::Entities::Kind', 'description' => 'Polymorphic Kind' }, 'values' => { '$ref' => '#/definitions/TheseApi::Entities::Values', 'description' => 'Polymorphic Values' }, 'str' => { 'type' => 'string', 'description' => 'Polymorphic String' }, 'num' => { 'type' => 'integer', 'format' => 'int32', 'description' => 'Polymorphic Number' } } ) expect(subject['TheseApi::Entities::SomeEntity']).to eql( 'type' => 'object', 'properties' => { 'text' => { 'type' => 'string', 'description' => 'Content of something.' }, 'kind' => { '$ref' => '#/definitions/TheseApi::Entities::Kind', 'description' => 'The kind of this something.' }, 'kind2' => { '$ref' => '#/definitions/TheseApi::Entities::Kind', 'description' => 'Secondary kind.' }, 'kind3' => { '$ref' => '#/definitions/TheseApi::Entities::Kind', 'description' => 'Tertiary kind.' }, 'tags' => { 'type' => 'array', 'items' => { '$ref' => '#/definitions/TheseApi::Entities::Tag' }, 'description' => 'Tags.' }, 'relation' => { '$ref' => '#/definitions/TheseApi::Entities::Relation', 'description' => 'A related model.' }, 'values' => { '$ref' => '#/definitions/TheseApi::Entities::Values', 'description' => 'Tertiary kind.' }, 'nested' => { '$ref' => '#/definitions/TheseApi::Entities::Nested', 'description' => 'Nested object.' }, 'code' => { 'type' => 'string', 'description' => 'Error code' }, 'message' => { 'type' => 'string', 'description' => 'Error message' }, 'polymorphic' => { '$ref' => '#/definitions/TheseApi::Entities::Polymorphic', 'description' => 'Polymorphic Model' }, 'attr' => { 'type' => 'string', 'description' => 'Attribute' } }, 'required' => %w[attr], 'description' => 'This returns something' ) end end
47.510638
160
0.544484
b9bd9e0d7dfa1af8cc5268fceb555776cefdb06d
9,475
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. require 'date' # rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength module OCI # CreateIPSecConnectionTunnelDetails model. class Core::Models::CreateIPSecConnectionTunnelDetails ROUTING_ENUM = [ ROUTING_BGP = 'BGP'.freeze, ROUTING_STATIC = 'STATIC'.freeze ].freeze IKE_VERSION_ENUM = [ IKE_VERSION_V1 = 'V1'.freeze, IKE_VERSION_V2 = 'V2'.freeze ].freeze # A user-friendly name. Does not have to be unique, and it's changeable. Avoid # entering confidential information. # # @return [String] attr_accessor :display_name # The type of routing to use for this tunnel (either BGP dynamic routing or static routing). # # @return [String] attr_reader :routing # Internet Key Exchange protocol version. # # @return [String] attr_reader :ike_version # The shared secret (pre-shared key) to use for the IPSec tunnel. Only numbers, letters, and # spaces are allowed. If you don't provide a value, # Oracle generates a value for you. You can specify your own shared secret later if # you like with {#update_ip_sec_connection_tunnel_shared_secret update_ip_sec_connection_tunnel_shared_secret}. # # Example: `EXAMPLEToUis6j1cp8GdVQxcmdfMO0yXMLilZTbYCMDGu4V8o` # # @return [String] attr_accessor :shared_secret # Information for establishing a BGP session for the IPSec tunnel. Required if the tunnel uses # BGP dynamic routing. # # If the tunnel instead uses static routing, you may optionally provide # this object and set an IP address for one or both ends of the IPSec tunnel for the purposes # of troubleshooting or monitoring the tunnel. # # @return [OCI::Core::Models::CreateIPSecTunnelBgpSessionDetails] attr_accessor :bgp_session_config # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { # rubocop:disable Style/SymbolLiteral 'display_name': :'displayName', 'routing': :'routing', 'ike_version': :'ikeVersion', 'shared_secret': :'sharedSecret', 'bgp_session_config': :'bgpSessionConfig' # rubocop:enable Style/SymbolLiteral } end # Attribute type mapping. def self.swagger_types { # rubocop:disable Style/SymbolLiteral 'display_name': :'String', 'routing': :'String', 'ike_version': :'String', 'shared_secret': :'String', 'bgp_session_config': :'OCI::Core::Models::CreateIPSecTunnelBgpSessionDetails' # 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] :display_name The value to assign to the {#display_name} property # @option attributes [String] :routing The value to assign to the {#routing} property # @option attributes [String] :ike_version The value to assign to the {#ike_version} property # @option attributes [String] :shared_secret The value to assign to the {#shared_secret} property # @option attributes [OCI::Core::Models::CreateIPSecTunnelBgpSessionDetails] :bgp_session_config The value to assign to the {#bgp_session_config} 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.display_name = attributes[:'displayName'] if attributes[:'displayName'] raise 'You cannot provide both :displayName and :display_name' if attributes.key?(:'displayName') && attributes.key?(:'display_name') self.display_name = attributes[:'display_name'] if attributes[:'display_name'] self.routing = attributes[:'routing'] if attributes[:'routing'] self.ike_version = attributes[:'ikeVersion'] if attributes[:'ikeVersion'] raise 'You cannot provide both :ikeVersion and :ike_version' if attributes.key?(:'ikeVersion') && attributes.key?(:'ike_version') self.ike_version = attributes[:'ike_version'] if attributes[:'ike_version'] self.shared_secret = attributes[:'sharedSecret'] if attributes[:'sharedSecret'] raise 'You cannot provide both :sharedSecret and :shared_secret' if attributes.key?(:'sharedSecret') && attributes.key?(:'shared_secret') self.shared_secret = attributes[:'shared_secret'] if attributes[:'shared_secret'] self.bgp_session_config = attributes[:'bgpSessionConfig'] if attributes[:'bgpSessionConfig'] raise 'You cannot provide both :bgpSessionConfig and :bgp_session_config' if attributes.key?(:'bgpSessionConfig') && attributes.key?(:'bgp_session_config') self.bgp_session_config = attributes[:'bgp_session_config'] if attributes[:'bgp_session_config'] end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # Custom attribute writer method checking allowed values (enum). # @param [Object] routing Object to be assigned def routing=(routing) raise "Invalid value for 'routing': this must be one of the values in ROUTING_ENUM." if routing && !ROUTING_ENUM.include?(routing) @routing = routing end # Custom attribute writer method checking allowed values (enum). # @param [Object] ike_version Object to be assigned def ike_version=(ike_version) raise "Invalid value for 'ike_version': this must be one of the values in IKE_VERSION_ENUM." if ike_version && !IKE_VERSION_ENUM.include?(ike_version) @ike_version = ike_version end # 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 && display_name == other.display_name && routing == other.routing && ike_version == other.ike_version && shared_secret == other.shared_secret && bgp_session_config == other.bgp_session_config 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 [display_name, routing, ike_version, shared_secret, bgp_session_config].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
38.205645
161
0.688127
ff3aa56bbdc3cdd7ee82715c97582a171d7b0868
155
require 'ffi' module FFI module Mapscript class LabelBounds < FFI::Struct layout :poly, LineObj.ptr, :bbox, RectObj end end end
14.090909
35
0.63871
f711aee5cd4617fe8efebe4137ecffce12df2c51
11,254
# frozen_string_literal: true require 'thread' module Puma # Internal Docs for A simple thread pool management object. # # Each Puma "worker" has a thread pool to process requests. # # First a connection to a client is made in `Puma::Server`. It is wrapped in a # `Puma::Client` instance and then passed to the `Puma::Reactor` to ensure # the whole request is buffered into memory. Once the request is ready, it is passed into # a thread pool via the `Puma::ThreadPool#<<` operator where it is stored in a `@todo` array. # # Each thread in the pool has an internal loop where it pulls a request from the `@todo` array # and processes it. class ThreadPool class ForceShutdown < RuntimeError end # How long, after raising the ForceShutdown of a thread during # forced shutdown mode, to wait for the thread to try and finish # up its work before leaving the thread to die on the vine. SHUTDOWN_GRACE_TIME = 5 # seconds # Maintain a minimum of +min+ and maximum of +max+ threads # in the pool. # # The block passed is the work that will be performed in each # thread. # def initialize(name, min, max, *extra, &block) @not_empty = ConditionVariable.new @not_full = ConditionVariable.new @mutex = Mutex.new @todo = [] @spawned = 0 @waiting = 0 @name = name @min = Integer(min) @max = Integer(max) @block = block @extra = extra @shutdown = false @trim_requested = 0 @out_of_band_pending = false @workers = [] @auto_trim = nil @reaper = nil @mutex.synchronize do @min.times do spawn_thread @not_full.wait(@mutex) end end @clean_thread_locals = false @force_shutdown = false @shutdown_mutex = Mutex.new end attr_reader :spawned, :trim_requested, :waiting attr_accessor :clean_thread_locals attr_accessor :out_of_band_hook # @version 5.0.0 def self.clean_thread_locals Thread.current.keys.each do |key| # rubocop: disable Performance/HashEachMethods Thread.current[key] = nil unless key == :__recursive_key__ end end # How many objects have yet to be processed by the pool? # def backlog with_mutex { @todo.size } end # @!attribute [r] pool_capacity def pool_capacity waiting + (@max - spawned) end # @!attribute [r] busy_threads # @version 5.0.0 def busy_threads with_mutex { @spawned - @waiting + @todo.size } end # :nodoc: # # Must be called with @mutex held! # def spawn_thread @spawned += 1 th = Thread.new(@spawned) do |spawned| Puma.set_thread_name '%s threadpool %03i' % [@name, spawned] todo = @todo block = @block mutex = @mutex not_empty = @not_empty not_full = @not_full extra = @extra.map { |i| i.new } while true work = nil mutex.synchronize do while todo.empty? if @trim_requested > 0 @trim_requested -= 1 @spawned -= 1 @workers.delete th not_full.signal Thread.exit end @waiting += 1 if @out_of_band_pending && trigger_out_of_band_hook @out_of_band_pending = false end not_full.signal begin not_empty.wait mutex ensure @waiting -= 1 end end work = todo.shift end if @clean_thread_locals ThreadPool.clean_thread_locals end begin @out_of_band_pending = true if block.call(work, *extra) rescue Exception => e STDERR.puts "Error reached top of thread-pool: #{e.message} (#{e.class})" end end end @workers << th th end private :spawn_thread # @version 5.0.0 def trigger_out_of_band_hook return false unless out_of_band_hook && out_of_band_hook.any? # we execute on idle hook when all threads are free return false unless @spawned == @waiting out_of_band_hook.each(&:call) true rescue Exception => e STDERR.puts "Exception calling out_of_band_hook: #{e.message} (#{e.class})" true end private :trigger_out_of_band_hook # @version 5.0.0 def with_mutex(&block) @mutex.owned? ? yield : @mutex.synchronize(&block) end # Add +work+ to the todo list for a Thread to pickup and process. def <<(work) with_mutex do if @shutdown raise "Unable to add work while shutting down" end @todo << work if @waiting < @todo.size and @spawned < @max spawn_thread end @not_empty.signal end end # This method is used by `Puma::Server` to let the server know when # the thread pool can pull more requests from the socket and # pass to the reactor. # # The general idea is that the thread pool can only work on a fixed # number of requests at the same time. If it is already processing that # number of requests then it is at capacity. If another Puma process has # spare capacity, then the request can be left on the socket so the other # worker can pick it up and process it. # # For example: if there are 5 threads, but only 4 working on # requests, this method will not wait and the `Puma::Server` # can pull a request right away. # # If there are 5 threads and all 5 of them are busy, then it will # pause here, and wait until the `not_full` condition variable is # signaled, usually this indicates that a request has been processed. # # It's important to note that even though the server might accept another # request, it might not be added to the `@todo` array right away. # For example if a slow client has only sent a header, but not a body # then the `@todo` array would stay the same size as the reactor works # to try to buffer the request. In that scenario the next call to this # method would not block and another request would be added into the reactor # by the server. This would continue until a fully buffered request # makes it through the reactor and can then be processed by the thread pool. def wait_until_not_full with_mutex do while true return if @shutdown # If we can still spin up new threads and there # is work queued that cannot be handled by waiting # threads, then accept more work until we would # spin up the max number of threads. return if busy_threads < @max @not_full.wait @mutex end end end # @version 5.0.0 def wait_for_less_busy_worker(delay_s) return unless delay_s && delay_s > 0 # Ruby MRI does GVL, this can result # in processing contention when multiple threads # (requests) are running concurrently return unless Puma.mri? with_mutex do return if @shutdown # do not delay, if we are not busy return unless busy_threads > 0 # this will be signaled once a request finishes, # which can happen earlier than delay @not_full.wait @mutex, delay_s end end # If there are any free threads in the pool, tell one to go ahead # and exit. If +force+ is true, then a trim request is requested # even if all threads are being utilized. # def trim(force=false) with_mutex do free = @waiting - @todo.size if (force or free > 0) and @spawned - @trim_requested > @min @trim_requested += 1 @not_empty.signal end end end # If there are dead threads in the pool make them go away while decreasing # spawned counter so that new healthy threads could be created again. def reap with_mutex do dead_workers = @workers.reject(&:alive?) dead_workers.each do |worker| worker.kill @spawned -= 1 end @workers.delete_if do |w| dead_workers.include?(w) end end end class Automaton def initialize(pool, timeout, thread_name, message) @pool = pool @timeout = timeout @thread_name = thread_name @message = message @running = false end def start! @running = true @thread = Thread.new do Puma.set_thread_name @thread_name while @running @pool.public_send(@message) sleep @timeout end end end def stop @running = false @thread.wakeup end end def auto_trim!(timeout=30) @auto_trim = Automaton.new(self, timeout, "#{@name} threadpool trimmer", :trim) @auto_trim.start! end def auto_reap!(timeout=5) @reaper = Automaton.new(self, timeout, "#{@name} threadpool reaper", :reap) @reaper.start! end # Allows ThreadPool::ForceShutdown to be raised within the # provided block if the thread is forced to shutdown during execution. def with_force_shutdown t = Thread.current @shutdown_mutex.synchronize do raise ForceShutdown if @force_shutdown t[:with_force_shutdown] = true end yield ensure t[:with_force_shutdown] = false end # Tell all threads in the pool to exit and wait for them to finish. # Wait +timeout+ seconds then raise +ForceShutdown+ in remaining threads. # Next, wait an extra +grace+ seconds then force-kill remaining threads. # Finally, wait +kill_grace+ seconds for remaining threads to exit. # def shutdown(timeout=-1) threads = with_mutex do @shutdown = true @trim_requested = @spawned @not_empty.broadcast @not_full.broadcast @auto_trim.stop if @auto_trim @reaper.stop if @reaper # dup workers so that we join them all safely @workers.dup end if timeout == -1 # Wait for threads to finish without force shutdown. threads.each(&:join) else join = ->(inner_timeout) do start = Process.clock_gettime(Process::CLOCK_MONOTONIC) threads.reject! do |t| elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start t.join inner_timeout - elapsed end end # Wait +timeout+ seconds for threads to finish. join.call(timeout) # If threads are still running, raise ForceShutdown and wait to finish. @shutdown_mutex.synchronize do @force_shutdown = true threads.each do |t| t.raise ForceShutdown if t[:with_force_shutdown] end end join.call(SHUTDOWN_GRACE_TIME) # If threads are _still_ running, forcefully kill them and wait to finish. threads.each(&:kill) join.call(1) end @spawned = 0 @workers = [] end end end
28.347607
96
0.608672
62adcae50bd020cfe5a1a137f541465b14b0b5c9
2,421
=begin #Brainrex API Explorer #Welcome to the Brainrex API explorer, we make analytics tools for crypto and blockchain. Our currently propiertary models offer sentiment analysis, market making, blockchain monitoring and face-id verification. This AI models can be consumed from this API. We also offer integrations to open data and propietary data providers, as well as free test data we collect. There is a collection of data transformation tools. Join our Telegram group to get the latest news and ask questions [https://t.me/brainrex, #brainrex](https://t.me/brainrex). More about Brainrex at [https://brainrex.com](http://brainrex.com). Full Documentation can be found at [https://brainrexapi.github.io/docs](https://brainrexapi.github.io/docs) OpenAPI spec version: 0.1.1 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.8 =end require 'spec_helper' require 'json' # Unit tests for SwaggerClient::BlockchainApi # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'BlockchainApi' do before do # run before each test @instance = SwaggerClient::BlockchainApi.new end after do # run after each test end describe 'test an instance of BlockchainApi' do it 'should create an instance of BlockchainApi' do expect(@instance).to be_instance_of(SwaggerClient::BlockchainApi) end end # unit tests for blockchain_average_tx # Calculate average transccion fee of a given blockchain # Calculates the average trasnsaction fee of a given # @param request Name of the blockchain and date range. # @param [Hash] opts the optional parameters # @return [InlineResponse201] describe 'blockchain_average_tx test' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end # unit tests for blockchain_list # The blockchains data structure supported by the Brainrex API # List of supported blockchains networks for analysis. The full history of the networks are available. # @param [Hash] opts the optional parameters # @return [Array<Object>] describe 'blockchain_list test' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
41.033898
718
0.761669
6a9c8bb82a734df4075c01ccb4225b01484074e2
1,637
class PasswordResetsController < ApplicationController before_action :get_user, only: [:edit, :update] before_action :valid_user, only: [:edit, :update] before_action :check_expiration, only: [:edit, :update] # Case (1) def new end def create @user = User.find_by(email: params[:password_reset][:email].downcase) if @user @user.create_reset_digest @user.send_password_reset_email flash[:info] = "Email sent with password reset instructions" redirect_to root_url else flash.now[:danger] = "Email address not found" render 'new' end end def edit end def update if params[:user][:password].empty? # Case (3) @user.errors.add(:password, "can't be empty") render 'edit' elsif @user.update_attributes(user_params) # Case (4) log_in @user flash[:success] = "Password has been reset." redirect_to @user else render 'edit' # Case (2) end end private def user_params params.require(:user).permit(:password, :password_confirmation) end def get_user @user = User.find_by(email: params[:email]) end # Confirms a valid user. def valid_user unless (@user && @user.activated? && @user.authenticated?(:reset, params[:id])) redirect_to root_url end end # Checks expiration of reset token. def check_expiration if @user.password_reset_expired? flash[:danger] = "Password reset has expired." redirect_to new_password_reset_url end end end
25.578125
73
0.619426
01ba127c0cdef7c6b5cd5e3b7e848f77cbd80d9a
6,150
# encoding: utf-8 shared_examples 'IceNine.deep_freeze' do context 'with an Object' do let(:value) { Object.new } before do value.instance_eval { @a = '1' } end it 'returns the object' do should be(value) end it 'freezes the object' do expect { subject }.to change(value, :frozen?).from(false).to(true) end it 'freezes the instance variables in the Object' do expect(subject.instance_variable_get(:@a)).to be_frozen end context 'with a circular reference' do before do value.instance_eval { @self = self } end it 'returns the object' do should be(value) end it 'freezes the object' do expect { subject }.to change(value, :frozen?).from(false).to(true) end it 'freezes the instance variables in the Object' do expect(subject.instance_variable_get(:@a)).to be_frozen end end end context 'with an Array' do let(:value) { %w[a] } it 'returns the object' do should be(value) end it 'freezes the object' do expect { subject }.to change(value, :frozen?).from(false).to(true) end it 'freezes each element in the Array' do expect(subject.select(&:frozen?)).to eql(subject) end context 'with a circular reference' do before do value << value end it 'returns the object' do should be(value) end it 'freezes the object' do expect { subject }.to change(value, :frozen?).from(false).to(true) end it 'freezes each element in the Array' do expect(subject.select(&:frozen?)).to eql(subject) end end end context 'with a Hash' do let(:value) { { Object.new => Object.new } } it 'returns the object' do should be(value) end it 'freezes the object' do expect { subject }.to change(value, :frozen?).from(false).to(true) end it 'freezes each key in the Hash' do expect(subject.keys.select(&:frozen?)).to eql(subject.keys) end it 'freezes each value in the Hash' do expect(subject.values.select(&:frozen?)).to eql(subject.values) end context 'with a circular reference' do before do value[value] = value end it 'returns the object' do should be(value) end it 'freezes the object' do expect { subject }.to change(value, :frozen?).from(false).to(true) end it 'freezes each key in the Hash' do expect(subject.keys.select(&:frozen?)).to eql(subject.keys) end it 'freezes each value in the Hash' do expect(subject.values.select(&:frozen?)).to eql(subject.values) end end end context 'with a Range' do let(:value) { 'a'..'z' } it 'returns the object' do should be(value) end it 'freezes the object' do expect { subject }.to change(value, :frozen?).from(false).to(true) end it 'freeze the first object in the Range' do expect(subject.begin).to be_frozen end it 'freeze the last object in the Range' do expect(subject.end).to be_frozen end end context 'with a String' do let(:value) { '' } before do value.instance_eval { @a = '1' } end it 'returns the object' do should be(value) end it 'freezes the object' do expect { subject }.to change(value, :frozen?).from(false).to(true) end it 'freezes the instance variables in the String' do expect(subject.instance_variable_get(:@a)).to be_frozen end context 'with a circular reference' do before do value.instance_eval { @self = self } end it 'returns the object' do should be(value) end it 'freezes the object' do expect { subject }.to change(value, :frozen?).from(false).to(true) end it 'freezes the instance variables in the String' do expect(subject.instance_variable_get(:@a)).to be_frozen end end end context 'with a Struct' do let(:value) { klass.new(%w[ 1 2 ]) } let(:klass) { Struct.new(:a) } it 'returns the object' do should be(value) end it 'freezes the object' do expect { subject }.to change(value, :frozen?).from(false).to(true) end it 'freezes each value in the Struct' do expect(subject.values.select(&:frozen?)).to eql(subject.values) end context 'with a circular reference' do before do value.a = value end it 'returns the object' do should be(value) end it 'freezes the object' do expect { subject }.to change(value, :frozen?).from(false).to(true) end it 'freezes each value in the Struct' do expect(subject.values.select(&:frozen?)).to eql(subject.values) end end end context 'with an SimpleDelegator' do let(:value) { SimpleDelegator.new(nil) } before do value.instance_eval { @a = '1' } end it 'returns the object' do should be(value) end it 'freezes the object' do expect { subject }.to change(value, :frozen?).from(false).to(true) end it 'freezes the instance variables in the SimpleDelegator' do expect(subject.instance_variable_get(:@a)).to be_frozen end context 'with a circular reference' do before do value.instance_eval { @self = self } end it 'returns the object' do should be(value) end it 'freezes the object' do expect { subject }.to change(value, :frozen?).from(false).to(true) end it 'freezes the instance variables in the SimpleDelegator' do expect(subject.instance_variable_get(:@a)).to be_frozen end end end [0.0, 0, 0x7fffffffffffffff, true, false, nil, :symbol].each do |value| context "with a #{value.class}" do let(:value) { value } it 'returns the object' do should be(value) end it 'does not freeze the object' do expect { subject }.to_not change(value, :frozen?).from(false) end end end end
23.295455
74
0.606341
bf0d2150938463b11d6129c0308f9f1d59764509
262
module Folder class CheckPreconditions < Tasks def handle(fun, dir, args) raise StandardError, ":name must be set" if args[:name].nil? raise StandardError, ":srcs or :deps must be set" if args[:srcs].nil? and args[:deps].nil? end end end
29.111111
96
0.671756
088782d13e3bc4298b964b2c616c714ccb3e414e
737
class SessionsController < ApplicationController def new end def create user = User.find_by(email: params[:session][:email].downcase) if user && user.authenticate(params[:session][:password]) if user.activated? log_in user params[:session][:remember_me] == '1' ? remember(user) : forget(user) redirect_back_or user else message = "Account not activated. " message += "Check your email for the activation link." flash[:warning] = message redirect_to root_url end else flash.now[:danger] = 'Invalid email/password combination' render 'new' end end def destroy log_out if logged_in? redirect_to root_url end end
24.566667
77
0.640434
ac9220e1f0904dadff38559f5a2f94221685755b
2,845
# frozen_string_literal: true require 'openssl' require 'httpclient' require 'nokogiri' require 'json' module Handochogwa # 신한카드! class Shinhan def initialize(username = nil, password = nil) create_session @logged_in = false authorize(username, password) if username && password end def authorize(username, password) post( 'cmm/MOBFMLOGIN/CMMServiceMemLoginC.ajax', authorize_params(username, password) ) end def brief_data response = post('MOBFM006N/MOBFM006R0102.ajax') recent_usage = process_array( response['HPG01499'], 'alnc_amt' => 'amount', 'stl_du_dd' => 'date', 'mcht_nm' => 'metchant' ) { total_limit: response['r_tot_amt'], remaining_limit: response['x_tot_amt'], recent_usage: recent_usage } end private def post(url, body = {}) response_json = @client.post_content( "https://m.shinhancard.com/mob/#{url}", body: body ) response = JSON.parse(response_json) response['mbw_json'] end def process_array(data, replaces) Array.new(data.first[1].length) do |i| data.keys.map do |key| [ (replaces[key] || key), data[key][i] ] end.to_h end end def create_session @client = HTTPClient.new(agent_name: Handochogwa::USER_AGENT) response = @client.post_content( 'https://m.shinhancard.com/solution/nfilter/jsp/open_nFilter_keypad_manager.jsp', body: create_session_post_params ) html = Nokogiri::HTML(response) @modulus = parse_hex(html.css('#nfilter_modulus')[0]['value']) @exponent = parse_hex(html.css('#nfilter_exponent')[0]['value']) end def parse_hex(hexstring) OpenSSL::BN.new(hexstring.to_i(16)) end def create_session_post_params image_manager_url = 'solution/nfilter/jsp/open_nFilter_image_manager.jsp' { nfilter_enable_nosecret: true, nfilter_is_init: true, nfilter_is_mobile: true, nfilter_lang: 'ko', nFilter_screenKeyPadSize: 390, nFilter_screenSize: 400, nfilter_type: 15, ResponseImageManager: image_manager_url } end def authorize_params(username, password) rsa = OpenSSL::PKey::RSA.new rsa.n = @modulus rsa.e = @exponent encrypted_password = rsa.public_encrypt("no_secret_#{password}") hex_password = encrypted_password.unpack1('H*') { memid: username, mode: 'loginPersonWeb', channel: 'person', device: 'WI', nfilter: { type: 'mob', once: 'true', dash: '', encrypt: "pwd=#{hex_password}" }.to_json } end end end
24.110169
89
0.600703
1c2b7314e4ed8969a937a7e81015307cb1ef4ab7
42,950
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2019_06_01 # # ExpressRoutePorts # class ExpressRoutePorts include MsRestAzure # # Creates and initializes a new instance of the ExpressRoutePorts class. # @param client service class for accessing basic functionality. # def initialize(client) @client = client end # @return [NetworkManagementClient] reference to the NetworkManagementClient attr_reader :client # # Deletes the specified ExpressRoutePort resource. # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of the ExpressRoutePort # resource. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # def delete(resource_group_name, express_route_port_name, custom_headers:nil) response = delete_async(resource_group_name, express_route_port_name, custom_headers:custom_headers).value! nil end # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of the ExpressRoutePort # resource. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def delete_async(resource_group_name, express_route_port_name, custom_headers:nil) # Send request promise = begin_delete_async(resource_group_name, express_route_port_name, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Retrieves the requested ExpressRoutePort resource. # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of ExpressRoutePort. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ExpressRoutePort] operation results. # def get(resource_group_name, express_route_port_name, custom_headers:nil) response = get_async(resource_group_name, express_route_port_name, custom_headers:custom_headers).value! response.body unless response.nil? end # # Retrieves the requested ExpressRoutePort resource. # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of ExpressRoutePort. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def get_with_http_info(resource_group_name, express_route_port_name, custom_headers:nil) get_async(resource_group_name, express_route_port_name, custom_headers:custom_headers).value! end # # Retrieves the requested ExpressRoutePort resource. # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of ExpressRoutePort. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def get_async(resource_group_name, express_route_port_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'express_route_port_name is nil' if express_route_port_name.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'expressRoutePortName' => express_route_port_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2019_06_01::Models::ExpressRoutePort.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Creates or updates the specified ExpressRoutePort resource. # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of the ExpressRoutePort # resource. # @param parameters [ExpressRoutePort] Parameters supplied to the create # ExpressRoutePort operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ExpressRoutePort] operation results. # def create_or_update(resource_group_name, express_route_port_name, parameters, custom_headers:nil) response = create_or_update_async(resource_group_name, express_route_port_name, parameters, custom_headers:custom_headers).value! response.body unless response.nil? end # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of the ExpressRoutePort # resource. # @param parameters [ExpressRoutePort] Parameters supplied to the create # ExpressRoutePort operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def create_or_update_async(resource_group_name, express_route_port_name, parameters, custom_headers:nil) # Send request promise = begin_create_or_update_async(resource_group_name, express_route_port_name, parameters, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| result_mapper = Azure::Network::Mgmt::V2019_06_01::Models::ExpressRoutePort.mapper() parsed_response = @client.deserialize(result_mapper, parsed_response) end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Update ExpressRoutePort tags. # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of the ExpressRoutePort # resource. # @param parameters [TagsObject] Parameters supplied to update ExpressRoutePort # resource tags. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ExpressRoutePort] operation results. # def update_tags(resource_group_name, express_route_port_name, parameters, custom_headers:nil) response = update_tags_async(resource_group_name, express_route_port_name, parameters, custom_headers:custom_headers).value! response.body unless response.nil? end # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of the ExpressRoutePort # resource. # @param parameters [TagsObject] Parameters supplied to update ExpressRoutePort # resource tags. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def update_tags_async(resource_group_name, express_route_port_name, parameters, custom_headers:nil) # Send request promise = begin_update_tags_async(resource_group_name, express_route_port_name, parameters, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| result_mapper = Azure::Network::Mgmt::V2019_06_01::Models::ExpressRoutePort.mapper() parsed_response = @client.deserialize(result_mapper, parsed_response) end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # List all the ExpressRoutePort resources in the specified resource group. # # @param resource_group_name [String] The name of the resource group. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Array<ExpressRoutePort>] operation results. # def list_by_resource_group(resource_group_name, custom_headers:nil) first_page = list_by_resource_group_as_lazy(resource_group_name, custom_headers:custom_headers) first_page.get_all_items end # # List all the ExpressRoutePort resources in the specified resource group. # # @param resource_group_name [String] The name of the resource group. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_by_resource_group_with_http_info(resource_group_name, custom_headers:nil) list_by_resource_group_async(resource_group_name, custom_headers:custom_headers).value! end # # List all the ExpressRoutePort resources in the specified resource group. # # @param resource_group_name [String] The name of the resource group. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_by_resource_group_async(resource_group_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2019_06_01::Models::ExpressRoutePortListResult.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # List all the ExpressRoutePort resources in the specified subscription. # # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Array<ExpressRoutePort>] operation results. # def list(custom_headers:nil) first_page = list_as_lazy(custom_headers:custom_headers) first_page.get_all_items end # # List all the ExpressRoutePort resources in the specified subscription. # # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_with_http_info(custom_headers:nil) list_async(custom_headers:custom_headers).value! end # # List all the ExpressRoutePort resources in the specified subscription. # # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_async(custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePorts' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2019_06_01::Models::ExpressRoutePortListResult.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Deletes the specified ExpressRoutePort resource. # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of the ExpressRoutePort # resource. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def begin_delete(resource_group_name, express_route_port_name, custom_headers:nil) response = begin_delete_async(resource_group_name, express_route_port_name, custom_headers:custom_headers).value! nil end # # Deletes the specified ExpressRoutePort resource. # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of the ExpressRoutePort # resource. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def begin_delete_with_http_info(resource_group_name, express_route_port_name, custom_headers:nil) begin_delete_async(resource_group_name, express_route_port_name, custom_headers:custom_headers).value! end # # Deletes the specified ExpressRoutePort resource. # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of the ExpressRoutePort # resource. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def begin_delete_async(resource_group_name, express_route_port_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'express_route_port_name is nil' if express_route_port_name.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'expressRoutePortName' => express_route_port_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:delete, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 || status_code == 202 || status_code == 204 error_model = JSON.load(response_content) fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? result end promise.execute end # # Creates or updates the specified ExpressRoutePort resource. # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of the ExpressRoutePort # resource. # @param parameters [ExpressRoutePort] Parameters supplied to the create # ExpressRoutePort operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ExpressRoutePort] operation results. # def begin_create_or_update(resource_group_name, express_route_port_name, parameters, custom_headers:nil) response = begin_create_or_update_async(resource_group_name, express_route_port_name, parameters, custom_headers:custom_headers).value! response.body unless response.nil? end # # Creates or updates the specified ExpressRoutePort resource. # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of the ExpressRoutePort # resource. # @param parameters [ExpressRoutePort] Parameters supplied to the create # ExpressRoutePort operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def begin_create_or_update_with_http_info(resource_group_name, express_route_port_name, parameters, custom_headers:nil) begin_create_or_update_async(resource_group_name, express_route_port_name, parameters, custom_headers:custom_headers).value! end # # Creates or updates the specified ExpressRoutePort resource. # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of the ExpressRoutePort # resource. # @param parameters [ExpressRoutePort] Parameters supplied to the create # ExpressRoutePort operation. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def begin_create_or_update_async(resource_group_name, express_route_port_name, parameters, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'express_route_port_name is nil' if express_route_port_name.nil? fail ArgumentError, 'parameters is nil' if parameters.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::Network::Mgmt::V2019_06_01::Models::ExpressRoutePort.mapper() request_content = @client.serialize(request_mapper, parameters) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'expressRoutePortName' => express_route_port_name}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:put, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 || status_code == 201 error_model = JSON.load(response_content) fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2019_06_01::Models::ExpressRoutePort.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end # Deserialize Response if status_code == 201 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2019_06_01::Models::ExpressRoutePort.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Update ExpressRoutePort tags. # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of the ExpressRoutePort # resource. # @param parameters [TagsObject] Parameters supplied to update ExpressRoutePort # resource tags. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ExpressRoutePort] operation results. # def begin_update_tags(resource_group_name, express_route_port_name, parameters, custom_headers:nil) response = begin_update_tags_async(resource_group_name, express_route_port_name, parameters, custom_headers:custom_headers).value! response.body unless response.nil? end # # Update ExpressRoutePort tags. # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of the ExpressRoutePort # resource. # @param parameters [TagsObject] Parameters supplied to update ExpressRoutePort # resource tags. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def begin_update_tags_with_http_info(resource_group_name, express_route_port_name, parameters, custom_headers:nil) begin_update_tags_async(resource_group_name, express_route_port_name, parameters, custom_headers:custom_headers).value! end # # Update ExpressRoutePort tags. # # @param resource_group_name [String] The name of the resource group. # @param express_route_port_name [String] The name of the ExpressRoutePort # resource. # @param parameters [TagsObject] Parameters supplied to update ExpressRoutePort # resource tags. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def begin_update_tags_async(resource_group_name, express_route_port_name, parameters, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'express_route_port_name is nil' if express_route_port_name.nil? fail ArgumentError, 'parameters is nil' if parameters.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::Network::Mgmt::V2019_06_01::Models::TagsObject.mapper() request_content = @client.serialize(request_mapper, parameters) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'expressRoutePortName' => express_route_port_name}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:patch, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2019_06_01::Models::ExpressRoutePort.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # List all the ExpressRoutePort resources in the specified resource group. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ExpressRoutePortListResult] operation results. # def list_by_resource_group_next(next_page_link, custom_headers:nil) response = list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers).value! response.body unless response.nil? end # # List all the ExpressRoutePort resources in the specified resource group. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_by_resource_group_next_with_http_info(next_page_link, custom_headers:nil) list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers).value! end # # List all the ExpressRoutePort resources in the specified resource group. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_by_resource_group_next_async(next_page_link, custom_headers:nil) fail ArgumentError, 'next_page_link is nil' if next_page_link.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = '{nextLink}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], skip_encoding_path_params: {'nextLink' => next_page_link}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2019_06_01::Models::ExpressRoutePortListResult.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # List all the ExpressRoutePort resources in the specified subscription. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ExpressRoutePortListResult] operation results. # def list_next(next_page_link, custom_headers:nil) response = list_next_async(next_page_link, custom_headers:custom_headers).value! response.body unless response.nil? end # # List all the ExpressRoutePort resources in the specified subscription. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_next_with_http_info(next_page_link, custom_headers:nil) list_next_async(next_page_link, custom_headers:custom_headers).value! end # # List all the ExpressRoutePort resources in the specified subscription. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_next_async(next_page_link, custom_headers:nil) fail ArgumentError, 'next_page_link is nil' if next_page_link.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = '{nextLink}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], skip_encoding_path_params: {'nextLink' => next_page_link}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2019_06_01::Models::ExpressRoutePortListResult.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # List all the ExpressRoutePort resources in the specified resource group. # # @param resource_group_name [String] The name of the resource group. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ExpressRoutePortListResult] which provide lazy access to pages of # the response. # def list_by_resource_group_as_lazy(resource_group_name, custom_headers:nil) response = list_by_resource_group_async(resource_group_name, custom_headers:custom_headers).value! unless response.nil? page = response.body page.next_method = Proc.new do |next_page_link| list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers) end page end end # # List all the ExpressRoutePort resources in the specified subscription. # # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ExpressRoutePortListResult] which provide lazy access to pages of # the response. # def list_as_lazy(custom_headers:nil) response = list_async(custom_headers:custom_headers).value! unless response.nil? page = response.body page.next_method = Proc.new do |next_page_link| list_next_async(next_page_link, custom_headers:custom_headers) end page end end end end
44.23275
162
0.708452
088e654b36f7f9f589b63dc7e712fdd8a2ae42c0
261
module OdfCore module Element module Text class TocMark < AbstractElement XML_ELEMENT_NAME = 'text:toc-mark' CHILDREN = [].freeze ATTRIBUTES = ["text:outline-level", "text:string-value"].freeze end end end end
17.4
71
0.624521
f8ee9e5d93c03b789b70276cf15db95b903f9fce
2,262
# The MIT License # # Copyright (c) 2013 Marcelo Guimarães <[email protected]> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'optparse' require_relative '../lib/yummi' require_relative 'cash_flow_table_extensions.rb' opt = OptionParser::new tablebuilder = Yummi::TableBuilder::new('cash_flow_table.yaml') @table = tablebuilder.defaults.build_table @table.data = [['Initial', nil, 0, nil, nil], ['Deposit', 100.58, 100.58, true, 'QAWSEDRFTGH535'], ['Withdraw', -50.23, 50.35, true, '34ERDTF6GYU'], ['Withdraw', -100, -49.65, true, '2344EDRFT5'], ['Deposit', 50, 0.35, false, nil], ['Deposit', 600, 600.35, false, nil], ['Total', nil, 600.35, nil, nil]] opt.on '--layout LAYOUT', 'Defines the table layout (horizontal or vertical)' do |layout| @table.layout = layout end opt.on '--box', 'Prints the table inside a box' do @box = Yummi::TextBox::new @box.style.top_left = '/' @box.style.bottom_left = '\\' @box.style.top_right = '\\' @box.style.bottom_right = '/' end opt.on '--help', 'Prints this message' do puts opt exit 0 end opt.parse ARGV if @box @box << @table @box.print else @table.print end
34.8
89
0.690097
28c3219b37b4d6b2a5a45e1c64f07477d2dcf5bf
3,043
# frozen_string_literal: true module MergeRequests class BaseService < ::IssuableBaseService def create_note(merge_request, state = merge_request.state) SystemNoteService.change_status(merge_request, merge_request.target_project, current_user, state, nil) end def hook_data(merge_request, action, old_rev: nil, old_associations: {}) hook_data = merge_request.to_hook_data(current_user, old_associations: old_associations) hook_data[:object_attributes][:action] = action if old_rev && !Gitlab::Git.blank_ref?(old_rev) hook_data[:object_attributes][:oldrev] = old_rev end hook_data end def execute_hooks(merge_request, action = 'open', old_rev: nil, old_associations: {}) if merge_request.project merge_data = hook_data(merge_request, action, old_rev: old_rev, old_associations: old_associations) merge_request.project.execute_hooks(merge_data, :merge_request_hooks) merge_request.project.execute_services(merge_data, :merge_request_hooks) end end private def handle_wip_event(merge_request) if wip_event = params.delete(:wip_event) # We update the title that is provided in the params or we use the mr title title = params[:title] || merge_request.title params[:title] = case wip_event when 'wip' then MergeRequest.wip_title(title) when 'unwip' then MergeRequest.wipless_title(title) end end end def filter_params(merge_request) super unless merge_request.can_allow_collaboration?(current_user) params.delete(:allow_collaboration) end end def merge_request_metrics_service(merge_request) MergeRequestMetricsService.new(merge_request.metrics) end def create_assignee_note(merge_request) SystemNoteService.change_assignee( merge_request, merge_request.project, current_user, merge_request.assignee) end # Returns all origin and fork merge requests from `@project` satisfying passed arguments. # rubocop: disable CodeReuse/ActiveRecord def merge_requests_for(source_branch, mr_states: [:opened]) @project.source_of_merge_requests .with_state(mr_states) .where(source_branch: source_branch) .preload(:source_project) # we don't need #includes since we're just preloading for the #select .select(&:source_project) end # rubocop: enable CodeReuse/ActiveRecord def pipeline_merge_requests(pipeline) merge_requests_for(pipeline.ref).each do |merge_request| next unless pipeline == merge_request.head_pipeline yield merge_request end end def commit_status_merge_requests(commit_status) merge_requests_for(commit_status.ref).each do |merge_request| pipeline = merge_request.head_pipeline next unless pipeline next unless pipeline.sha == commit_status.sha yield merge_request end end end end
34.579545
108
0.708511
33ec1f24aadb106200df501057d36e6383c83e69
5,671
require 'time' require 'serialport' require 'phaserunner' class String def is_number? true if Float(self) rescue false end end module CycleAnalystLogger class CycleAnalyst # Cycle Analyst serial port Baudrate attr_reader :baudrate # Cycle Analyst serial port name attr_reader :tty # Hash that describes the names, values and units of the Cycle Analyst log data attr_reader :dict # Handle from the SerialPort object attr_reader :serial_io # If the phaserunner should be read attr_reader :enable_phaserunner # Handle of the Phaserunner::Modbus object attr_reader :phaserunner # If the gps should be read attr_reader :enable_gps # Handle of the Gps object attr_reader :gps # Shared data for gps data attr_reader :gps_data # Hash definition that describes the names, values and units of the Cycle Analyst log data CA_DICT = { 0 => {address: 0, name: "Amp Hours", units: "Ah", scale: 1}, 1 => { address: 1, name: "Volts", units: "V", scale: 1 }, 2 => { address: 2, name: "Current", units: "A", scale: 1}, 3 => { address: 3, name: "Speed", units: "Mph", scale: 1}, 4 => { address: 4, name: "Distance", units: "Miles", scale: 1}, 5 => { address: 5, name: "Motor Temp", units: "DegC", scale: 1}, 6 => { address: 6, name: "Human Cadence", units: "RPM", scale: 1}, 7 => { address: 7, name: "Human Power", units: "W", scale: 1}, 8 => { address: 8, name: "Human Torque", units: "Nm", scale: 1}, 9 => { address: 9, name: "Throttle In", units: "V", scale: 1}, 10 => { address: 10, name: "Throttle Out", units: "V", scale: 1}, 11 => { address: 11, name: "AuxA", units: "", scale: 1}, 12 => { address: 11, name: "AuxD", units: "", scale: 1}, 13 => { address: 12, name: "Limit Flags", units: "bit flags", scale: 1} } # CA_STD_HEADER CA_STD_HEADER = %w(Ah V A S D Deg RPM HW Nm ThI ThO AuxA AuxD Flgs) # CycleAnalyst New def initialize(opts) @baudrate = opts[:baud_ca] @tty = opts[:tty_ca] @dict = CA_DICT @serial_io = SerialPort.new @tty, @baudrate, 8, 1 @enable_phaserunner = opts[:enable_phaserunner] if @enable_phaserunner @phaserunner = Phaserunner::Modbus.new( tty: opts[:tty_pr], baudrate: opts[:baud_pr] ) end @enable_gps = opts[:enable_gps] if @enable_gps @gps_data = {} @gps = Gps.new(@gps_data, {tty: opts[:tty_gps], baudrate: opts[:baud_gps]}) end end # Forms the proper header line # @return [String] of a printable CSV header line def log_header hdr = dict.map do |(address, node)| "#{node[:name]} (#{node[:units]})" end if enable_phaserunner hdr += phaserunner.bulk_log_header.map { |name| "PR #{name}" } end if enable_gps hdr += gps.log_header end hdr.join(',') end # Converts a TSV string into an array def tsv2array(line) line.strip.split("\t") end # Get line from Cycle Analyst serial port, optionally also the Phaserunner and send to stdout and file # @param output_fd [File] File Descriptor of the output file to write to. Don't write to file if nil # @param loop_count [Integer, Symbol] Number of lines to output, or forever if :forever # @param quite [Boolean] Don't output to stdout if true def get_logs(loop_count, quiet, disable_nmea_out) timestamp = Time.now.strftime('%Y-%m-%d_%H-%M-%S') filename = "cycle_analyst-v#{VERSION}-#{timestamp}.csv" output_fd = File.open(filename, 'w') if enable_gps unless disable_nmea_out nmea_filename = "nmea.#{timestamp}.txt" nmea_fd = File.open(nmea_filename, 'w') else nmea_fd = nil end gps_thread = Thread.new { gps.run(nmea_fd, disable_nmea_out) } end line_number = 0 hdr = %Q(Timestamp,#{log_header}) puts hdr if not quiet output_fd.puts hdr if output_fd serial_io.each_line.with_index do |line, idx| output = ( [Time.now.utc.round(10).iso8601(6)] + tsv2array(line) ) output += phaserunner.bulk_log_data if enable_phaserunner output += gps.log_data if enable_gps output_line = output.flatten.join(',') puts output_line unless quiet output_fd.puts output_line if output_fd break if idx >= loop_count end end def self.valid_timestamp(input) begin Time.parse(input) rescue ArgumentError nil end end # Very basic test that the record is valid def self.validate_log_record(log_record) return false unless valid_timestamp log_record[0] log_record.each.with_index do |element, idx| next if [0,14,29,38].any? { |i| idx == i } #Skip Timestamps and CA Limit value return false unless element.is_number? || element.empty? end true end def self.log_to_ca_file(log_filename) output_filename = log_filename.sub( /cycle_analyst\.(\d\d\d\d\-\d\d\-\d\d_\d\d\-\d\d\-\d\d).csv/, 'CALog_\1.txt' ) out_fd = File.open(output_filename, 'w') File.readlines(log_filename).each.with_index do |log_line, idx| log_record = log_line.strip.split(',') if idx == 0 out_fd.puts CA_STD_HEADER.join("\t") next end log_end = CA_STD_HEADER.length log_segment = log_record[1..log_end] out_fd.puts log_segment.join("\t") if validate_log_record(log_record) end end end end
30.326203
106
0.61118
87a1bc72ed92cde113db4dcb0790c5f49649c293
3,499
#-- # Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others. # All rights reserved. # See LICENSE.txt for permissions. #++ require 'rubygems' ## # The Version class processes string versions into comparable values class Gem::Version include Comparable attr_reader :ints attr_reader :version ## # Checks if version string is valid format # # str:: [String] the version string # return:: [Boolean] true if the string format is correct, otherwise false # def self.correct?(version) case version when Integer, /\A\s*(\d+(\.\d+)*)*\s*\z/ then true else false end end ## # Factory method to create a Version object. Input may be a Version or a # String. Intended to simplify client code. # # ver1 = Version.create('1.3.17') # -> (Version object) # ver2 = Version.create(ver1) # -> (ver1) # ver3 = Version.create(nil) # -> nil # def self.create(input) if input.respond_to? :version then input elsif input.nil? then nil else new input end end ## # Constructs a version from the supplied string # # version:: [String] The version string. Format is digit.digit... # def initialize(version) raise ArgumentError, "Malformed version number string #{version}" unless self.class.correct?(version) self.version = version end def inspect # :nodoc: "#<#{self.class} #{@version.inspect}>" end # Dump only the raw version string, not the complete object def marshal_dump [@version] end # Load custom marshal format def marshal_load(array) self.version = array[0] end # Strip ignored trailing zeros. def normalize @ints = build_array_from_version_string return if @ints.length == 1 @ints.pop while @ints.last == 0 @ints = [0] if @ints.empty? end ## # Returns the text representation of the version # # return:: [String] version as string # def to_s @version end ## # Convert version to integer array # # return:: [Array] list of integers # def to_ints normalize unless @ints @ints end def to_yaml_properties ['@version'] end def version=(version) @version = version.to_s.strip normalize end def yaml_initialize(tag, values) self.version = values['version'] end ## # Compares two versions # # other:: [Version or .ints] other version to compare to # return:: [Fixnum] -1, 0, 1 # def <=>(other) return 1 unless other @ints <=> other.ints end alias eql? == # :nodoc: def hash # :nodoc: to_ints.inject { |hash_code, n| hash_code + n } end # Return a new version object where the next to the last revision # number is one greater. (e.g. 5.3.1 => 5.4) def bump ints = build_array_from_version_string ints.pop if ints.size > 1 ints[-1] += 1 self.class.new(ints.join(".")) end def build_array_from_version_string @version.to_s.scan(/\d+/).map { |s| s.to_i } end private :build_array_from_version_string #:stopdoc: require 'rubygems/requirement' # Gem::Requirement's original definition is nested in Version. # Although an inappropriate place, current gems specs reference the nested # class name explicitly. To remain compatible with old software loading # gemspecs, we leave a copy of original definition in Version, but define an # alias Gem::Requirement for use everywhere else. Requirement = ::Gem::Requirement # :startdoc: end
21.078313
78
0.655616
032e38d9fbb43d13eac6a2960eaad2658223fc46
77
# frozen_string_literal: true module EmailStylist VERSION = '0.1.1' end
9.625
29
0.727273
bb7ed2c993064aa2ba4d4f2871107ed70056e3b6
644
class Staff::PrioritiesController < Staff::BaseController def new @scheme = Scheme.find(scheme_id) @priority = Priority.new end def create @scheme = Scheme.find(scheme_id) @priority = Priority.new(priority_params) @priority.scheme = @scheme if @priority.valid? @priority.save flash[:success] = I18n.t('generic.notice.create.success', resource: 'priority') redirect_to estate_scheme_path(@scheme.estate, @scheme) else render :new end end private def scheme_id params[:scheme_id] end def priority_params params.require(:priority).permit(:name, :days) end end
20.774194
85
0.680124
1ae705de40c3605cf0b3fdea8c8669f06febe873
1,123
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::ResourcesManagement::Mgmt::V2018_03_01_preview module Models # # The error object. # class ErrorResponse include MsRestAzure # @return [ErrorDetails] Error. attr_accessor :error # # Mapper for ErrorResponse class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ErrorResponse', type: { name: 'Composite', class_name: 'ErrorResponse', model_properties: { error: { client_side_validation: true, required: false, serialized_name: 'error', type: { name: 'Composite', class_name: 'ErrorDetails' } } } } } end end end end
23.893617
70
0.536064
e9d1ea2026d8eae456326b1b74fc3927de1904d0
158
class CreatePatients < ActiveRecord::Migration[5.1] def change create_table :patients do |t| t.string :name t.timestamps end end end
15.8
51
0.664557
26ccbdcd41c1dea068ab10cd90732d15b8d3ff7f
647
module ApplicationHelper def resource_name :user end def resource @resource ||= User.new end def devise_mapping @devise_mapping ||= Devise.mappings[:user] end def link_to_add_fields(name, f, association) new_object = f.object.send(association).klass.new id = new_object.object_id fields = f.fields_for(association, new_object, child_index: id) do |builder| render(association.to_s.singularize + "_fields", f: builder) end link_to(name, "#", class: "add_rooms", data: {id: id, fields: fields.gsub("\n", "")}) end end
28.130435
93
0.604328
2688afa554ac6690e8a720b0064405b5527ac271
133
module CloudstackRubyClient module Api module S3 cmd_processor :add_s3, :list_s3s end end end
13.3
29
0.593985
87c25589b0ec2c3d82d920752c357cf633668b4c
6,546
# frozen_string_literal: true require "spec_helper" describe Doorkeeper::OAuth::PasswordAccessTokenRequest do let(:server) do double( :server, default_scopes: Doorkeeper::OAuth::Scopes.new, access_token_expires_in: 2.hours, refresh_token_enabled?: false, custom_access_token_expires_in: lambda { |context| context.grant_type == Doorkeeper::OAuth::PASSWORD ? 1234 : nil }, ) end let(:client) { Doorkeeper::OAuth::Client.new(FactoryBot.create(:application)) } let(:application) { client.application } let(:owner) { FactoryBot.build_stubbed(:resource_owner) } before do allow(server).to receive(:option_defined?).with(:custom_access_token_expires_in).and_return(true) end subject do described_class.new(server, client, owner) end it "issues a new token for the client" do expect do subject.authorize end.to change { application.reload.access_tokens.count }.by(1) expect(application.reload.access_tokens.max_by(&:created_at).expires_in).to eq(1234) end it "issues a new token without a client" do subject = described_class.new(server, nil, owner) expect(subject).to be_valid expect do subject.authorize end.to change { Doorkeeper::AccessToken.count }.by(1) end it "does not issue a new token with an invalid client" do subject = described_class.new(server, nil, owner, { client_id: "bad_id" }) expect do subject.authorize end.not_to(change { Doorkeeper::AccessToken.count }) expect(subject.error).to eq(:invalid_client) end it "requires the owner" do subject = described_class.new(server, client, nil) subject.validate expect(subject.error).to eq(:invalid_grant) end it "creates token even when there is already one (default)" do FactoryBot.create( :access_token, application_id: client.id, resource_owner_id: owner.id, resource_owner_type: owner.class.name, ) expect do subject.authorize end.to change { Doorkeeper::AccessToken.count }.by(1) end it "skips token creation if there is already one reusable" do allow(Doorkeeper.configuration).to receive(:reuse_access_token).and_return(true) FactoryBot.create( :access_token, application_id: client.id, resource_owner_id: owner.id, resource_owner_type: owner.class.name, ) expect do subject.authorize end.not_to(change { Doorkeeper::AccessToken.count }) end it "creates token when there is already one but non reusable" do allow(Doorkeeper.configuration).to receive(:reuse_access_token).and_return(true) FactoryBot.create( :access_token, application_id: client.id, resource_owner_id: owner.id, resource_owner_type: owner.class.name, ) allow_any_instance_of(Doorkeeper::AccessToken).to receive(:reusable?).and_return(false) expect do subject.authorize end.to change { Doorkeeper::AccessToken.count }.by(1) end it "calls configured request callback methods" do expect(Doorkeeper.configuration.before_successful_strategy_response) .to receive(:call).with(subject).once expect(Doorkeeper.configuration.after_successful_strategy_response) .to receive(:call).with(subject, instance_of(Doorkeeper::OAuth::TokenResponse)).once subject.authorize end describe "with scopes" do subject do described_class.new(server, client, owner, scope: "public") end context "when scopes_by_grant_type is not configured for grant_type" do it "returns error when scopes are invalid" do allow(server).to receive(:scopes).and_return(Doorkeeper::OAuth::Scopes.from_string("another")) subject.validate expect(subject.error).to eq(:invalid_scope) end it "creates the token with scopes if scopes are valid" do allow(server).to receive(:scopes).and_return(Doorkeeper::OAuth::Scopes.from_string("public")) expect do subject.authorize end.to change { Doorkeeper::AccessToken.count }.by(1) expect(Doorkeeper::AccessToken.last.scopes).to include("public") end end context "when scopes_by_grant_type is configured for grant_type" do it "returns error when scopes are valid but not permitted for grant_type" do allow(server) .to receive(:scopes).and_return(Doorkeeper::OAuth::Scopes.from_string("public")) allow(Doorkeeper.configuration) .to receive(:scopes_by_grant_type).and_return(password: "another") subject.validate expect(subject.error).to eq(:invalid_scope) end it "creates the token with scopes if scopes are valid and permitted for grant_type" do allow(server).to receive(:scopes).and_return(Doorkeeper::OAuth::Scopes.from_string("public")) allow(Doorkeeper.configuration) .to receive(:scopes_by_grant_type).and_return(password: [:public]) expect do subject.authorize end.to change { Doorkeeper::AccessToken.count }.by(1) expect(Doorkeeper::AccessToken.last.scopes).to include("public") end end end describe "with custom expiry" do let(:server) do double( :server, default_scopes: Doorkeeper::OAuth::Scopes.new, access_token_expires_in: 2.hours, refresh_token_enabled?: false, custom_access_token_expires_in: lambda { |context| if context.scopes.exists?("public") 222 elsif context.scopes.exists?("magic") Float::INFINITY end }, ) end before do allow(server).to receive(:option_defined?).with(:custom_access_token_expires_in).and_return(true) end it "checks scopes" do subject = described_class.new(server, client, owner, scope: "public") allow(server).to receive(:scopes).and_return(Doorkeeper::OAuth::Scopes.from_string("public")) expect do subject.authorize end.to change { Doorkeeper::AccessToken.count }.by(1) expect(Doorkeeper::AccessToken.last.expires_in).to eq(222) end it "falls back to the default otherwise" do subject = described_class.new(server, client, owner, scope: "private") allow(server).to receive(:scopes).and_return(Doorkeeper::OAuth::Scopes.from_string("private")) expect do subject.authorize end.to change { Doorkeeper::AccessToken.count }.by(1) expect(Doorkeeper::AccessToken.last.expires_in).to eq(2.hours) end end end
32.246305
103
0.690804
211190560a3c590f8dcc5b019fb841ac8d4bffa0
2,052
#-- # Copyright (c) 2004-2017 David Heinemeier Hansson # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ require "abstract_controller" require "action_mailer/version" # Common Active Support usage in Action Mailer require "active_support/rails" require "active_support/core_ext/class" require "active_support/core_ext/module/attr_internal" require "active_support/core_ext/string/inflections" require "active_support/lazy_load_hooks" module ActionMailer extend ::ActiveSupport::Autoload eager_autoload do autoload :Collector end autoload :Base autoload :DeliveryMethods autoload :InlinePreviewInterceptor autoload :MailHelper autoload :Parameterized autoload :Preview autoload :Previews, "action_mailer/preview" autoload :TestCase autoload :TestHelper autoload :MessageDelivery autoload :DeliveryJob end autoload :Mime, "action_dispatch/http/mime_type" ActiveSupport.on_load(:action_view) do ActionView::Base.default_formats ||= Mime::SET.symbols ActionView::Template::Types.delegate_to Mime end
34.2
72
0.789961
bbb6219c13eb92d3932bcc708b2113f93d45e731
13,516
require "rails_helper" RSpec.describe ApplicationHelper, :type => :helper do describe "#dob_in_words" do it "returns date of birth in words for < 1 year" do expect(helper.dob_in_words(0, "20/06/2015".to_date)).to eq time_ago_in_words("20/06/2015".to_date) expect(helper.dob_in_words(0, "20/07/2015".to_date)).to eq time_ago_in_words("20/07/2015".to_date) expect(helper.dob_in_words(0, "20/07/2014".to_date)).to eq time_ago_in_words("20/07/2014".to_date) end end describe "#display_carrier_logo" do let(:plan){ Maybe.new(FactoryGirl.build(:plan)) } let(:carrier_profile){ FactoryGirl.build(:carrier_profile, legal_name: "Kaiser")} let(:plan_1){ Maybe.new(FactoryGirl.build(:plan, hios_id: "89789DC0010006-01", carrier_profile: carrier_profile)) } it "should return uhic logo" do expect(helper.display_carrier_logo(plan)).to eq "<img width=\"50\" src=\"/assets/logo/carrier/uhic.jpg\" alt=\"Uhic\" />" end it "should return non united logo" do expect(helper.display_carrier_logo(plan_1)).to eq "<img width=\"50\" src=\"/assets/logo/carrier/kaiser.jpg\" alt=\"Kaiser\" />" end end describe "#format_time_display" do let(:timestamp){ Time.now.utc } it "should display the time in proper format" do expect(helper.format_time_display(timestamp)).to eq timestamp.in_time_zone('Eastern Time (US & Canada)') end it "should return empty if no timestamp is present" do expect(helper.format_time_display(nil)).to eq "" end end describe "#group_xml_transmitted_message" do let(:employer_profile_1){ double("EmployerProfile", xml_transmitted_timestamp: Time.now.utc, legal_name: "example1 llc.") } let(:employer_profile_2){ double("EmployerProfile", xml_transmitted_timestamp: nil, legal_name: "example2 llc.") } it "should display re-submit message if xml is being transmitted again" do expect(helper.group_xml_transmitted_message(employer_profile_1)).to eq "The group xml for employer #{employer_profile_1.legal_name} was transmitted on #{format_time_display(employer_profile_1.xml_transmitted_timestamp)}. Are you sure you want to transmit again?" end it "should display first time message if xml is being transmitted first time" do expect(helper.group_xml_transmitted_message(employer_profile_2)).to eq "Are you sure you want to transmit the group xml for employer #{employer_profile_2.legal_name}?" end end describe "#display_dental_metal_level" do let(:dental_plan_2015){FactoryGirl.create(:plan_template,:shop_dental, active_year: 2015)} let(:dental_plan_2016){FactoryGirl.create(:plan_template,:shop_dental, active_year: 2016)} it "should display metal level if its a 2015 plan" do expect(display_dental_metal_level(dental_plan_2015)).to eq dental_plan_2015.metal_level.titleize end it "should display metal level if its a 2016 plan" do expect(display_dental_metal_level(dental_plan_2016)).to eq dental_plan_2016.dental_level.titleize end end describe "#enrollment_progress_bar" do let(:employer_profile) { FactoryGirl.create(:employer_profile) } let(:plan_year) { FactoryGirl.create(:plan_year, employer_profile: employer_profile) } it "display progress bar" do expect(helper.enrollment_progress_bar(plan_year, 1, minimum: false)).to include('<div class="progress-wrapper employer-dummy">') end context ">100 census employees" do let!(:employees) { FactoryGirl.create_list(:census_employee, 101, employer_profile: employer_profile) } it "does not display" do expect(helper.enrollment_progress_bar(plan_year, 1, minimum: false)).to eq nil end end end describe "#fein helper methods" do it "returns fein with masked fein" do expect(helper.number_to_obscured_fein("111098222")).to eq "**-***8222" end it "returns formatted fein" do expect(helper.number_to_fein("111098222")).to eq "11-1098222" end end describe "date_col_name_for_broker_roaster" do context "for applicants controller" do before do expect(helper).to receive(:controller_name).and_return("applicants") end it "should return accepted date" do assign(:status, "active") expect(helper.date_col_name_for_broker_roaster).to eq 'Accepted Date' end it "should return terminated date" do assign(:status, "broker_agency_terminated") expect(helper.date_col_name_for_broker_roaster).to eq 'Terminated Date' end it "should return declined_date" do assign(:status, "broker_agency_declined") expect(helper.date_col_name_for_broker_roaster).to eq 'Declined Date' end end context "for other than applicants controller" do before do expect(helper).to receive(:controller_name).and_return("test") end it "should return certified" do assign(:status, "certified") expect(helper.date_col_name_for_broker_roaster).to eq 'Certified Date' end it "should return decertified" do assign(:status, "decertified") expect(helper.date_col_name_for_broker_roaster).to eq 'Decertified Date' end it "should return denied" do assign(:status, "denied") expect(helper.date_col_name_for_broker_roaster).to eq 'Denied Date' end end end describe "relationship_options" do let(:dependent) { double("FamilyMember") } context "consumer_portal" do it "should return correct options for consumer portal" do expect(helper.relationship_options(dependent, "consumer_role_id")).to match(/Domestic Partner/mi) expect(helper.relationship_options(dependent, "consumer_role_id")).to match(/other tax dependent/mi) end end context "employee portal" do it "should not match options that are in consumer portal" do expect(helper.relationship_options(dependent, "")).not_to match(/Domestic Partner/mi) expect(helper.relationship_options(dependent, "")).not_to match(/other tax dependent/mi) end end end describe "#may_update_census_employee?" do let(:user) { double("User") } let(:census_employee) { double("CensusEmployee", new_record?: false, is_eligible?: false) } before do expect(helper).to receive(:current_user).and_return(user) end it "census_employee can edit if it is new record" do expect(user).to receive(:roles).and_return(["employee"]) expect(helper.may_update_census_employee?(CensusEmployee.new)).to eq true # readonly -> false end it "census_employee cannot edit if linked to an employer" do expect(user).to receive(:roles).and_return(["employee"]) expect(helper.may_update_census_employee?(census_employee)).to eq false # readonly -> true end it "hbx admin edit " do expect(user).to receive(:roles).and_return(["hbx_staff"]) expect(helper.may_update_census_employee?(CensusEmployee.new)).to eq true # readonly -> false end end describe "#parse_ethnicity" do it "should return string of values" do expect(helper.parse_ethnicity(["test", "test1"])).to eq "test, test1" end it "should return empty value if ethnicity is not selected" do expect(helper.parse_ethnicity([""])).to eq "" end end describe "#calculate_participation_minimum" do let(:plan_year_1) { double("PlanYear", eligible_to_enroll_count: 5) } before do @current_plan_year = plan_year_1 end it "should return 0 when eligible_to_enroll_count is zero" do expect(@current_plan_year).to receive(:eligible_to_enroll_count).and_return(0) expect(helper.calculate_participation_minimum).to eq 0 end it "should calculate eligible_to_enroll_count when not zero" do expect(helper.calculate_participation_minimum).to eq 3 end end describe "get_key_and_bucket" do it "should return array with key and bucket" do uri = "urn:openhbx:terms:v1:file_storage:s3:bucket:dchbx-sbc#f21369fc-ae6c-4fa5-a299-370a555dc401" key, bucket = get_key_and_bucket(uri) expect(key).to eq("f21369fc-ae6c-4fa5-a299-370a555dc401") expect(bucket).to eq("dchbx-sbc") end end describe "current_cost" do it "should return cost without session" do expect(helper.current_cost(100, 0.9)).to eq 100 end context "with session" do before :each do session['elected_aptc'] = 100 session['max_aptc'] = 200 end it "when ehb_premium > aptc_amount" do expect(helper.current_cost(200, 0.9)).to eq (200 - 0.5*200) end it "when ehb_premium < aptc_amount" do expect(helper.current_cost(100, 0.9)).to eq (100 - 0.9*100) end it "should return 0" do session['elected_aptc'] = 160 expect(helper.current_cost(100, 1.2)).to eq 0 end it "when can_use_aptc is false" do expect(helper.current_cost(100, 1.2, nil, 'shopping', false)).to eq 100 end it "when can_use_aptc is true" do expect(helper.current_cost(100, 1.2, nil, 'shopping', true)).to eq 0 end end context "with hbx_enrollment" do let(:hbx_enrollment) {double(applied_aptc_amount: 10, total_premium: 100, coverage_kind: 'health')} it "should return cost from hbx_enrollment" do expect(helper.current_cost(100, 0.8, hbx_enrollment, 'account')).to eq 90 end end end describe "env_bucket_name" do it "should return bucket name with system name prepended and environment name appended" do bucket_name = "sample-bucket" expect(env_bucket_name(bucket_name)).to eq("dchbx-enroll-" + bucket_name + "-local") end end describe "disable_purchase?" do it "should return true when disabled is true" do expect(helper.disable_purchase?(true, nil)).to eq true end context "when disable is false" do let(:hbx_enrollment) { HbxEnrollment.new } it "should return true when hbx_enrollment is not allow select_coverage" do allow(hbx_enrollment).to receive(:can_select_coverage?).and_return false expect(helper.disable_purchase?(false, hbx_enrollment)).to eq true end it "should return false when hbx_enrollment is allow select_coverage" do allow(hbx_enrollment).to receive(:can_select_coverage?).and_return true expect(helper.disable_purchase?(false, hbx_enrollment)).to eq false end end end describe "qualify_qle_notice" do it "should return notice" do expect(helper.qualify_qle_notice).to include("In order to purchase benefit coverage, you must be in either an Open Enrollment or Special Enrollment period. ") end end describe "show_default_ga?", dbclean: :after_each do let(:general_agency_profile) { FactoryGirl.create(:general_agency_profile) } let(:broker_agency_profile) { FactoryGirl.create(:broker_agency_profile) } it "should return false without broker_agency_profile" do expect(helper.show_default_ga?(general_agency_profile, nil)).to eq false end it "should return false without general_agency_profile" do expect(helper.show_default_ga?(nil, broker_agency_profile)).to eq false end it "should return true" do broker_agency_profile.default_general_agency_profile = general_agency_profile expect(helper.show_default_ga?(general_agency_profile, broker_agency_profile)).to eq true end it "should return false when the default_general_agency_profile of broker_agency_profile is not general_agency_profile" do expect(helper.show_default_ga?(general_agency_profile, broker_agency_profile)).to eq false end end describe "find_plan_name", dbclean: :after_each do let(:family) { FactoryGirl.create(:family, :with_primary_family_member) } let(:shop_enrollment) { FactoryGirl.create(:hbx_enrollment, household: family.active_household, kind: "employer_sponsored", submitted_at: TimeKeeper.datetime_of_record - 3.days, created_at: TimeKeeper.datetime_of_record - 3.days )} let(:ivl_enrollment) { FactoryGirl.create(:hbx_enrollment, household: family.latest_household, coverage_kind: "health", effective_on: TimeKeeper.datetime_of_record - 10.days, enrollment_kind: "open_enrollment", kind: "individual", submitted_at: TimeKeeper.datetime_of_record - 20.days )} let(:valid_shop_enrollment_id) { shop_enrollment.id } let(:valid_ivl_enrollment_id) { ivl_enrollment.id } let(:invalid_enrollment_id) { } it "should return the plan name given a valid SHOP enrollment ID" do expect(helper.find_plan_name(valid_shop_enrollment_id)).to eq shop_enrollment.plan.name end it "should return the plan name given a valid INDIVIDUAL enrollment ID" do expect(helper.find_plan_name(valid_ivl_enrollment_id)).to eq ivl_enrollment.plan.name end it "should return nil given an invalid enrollment ID" do expect(helper.find_plan_name(invalid_enrollment_id)).to eq nil end end end
39.988166
269
0.691847
ffd2605e6e0f1790bb7755452422ff9029ca7e8c
233
# frozen_string_literal: true module PaymentProcessor module Exceptions class InvalidCurrency < ArgumentError; end class PaymentMethodNotFound < ArgumentError; end class CustomerNotFound < ArgumentError; end end end
23.3
52
0.7897
393b49cad760afa802018bbf1fba7a27413e92ba
1,543
class Cms::Node::CopyNodesController < ApplicationController include Cms::BaseFilter include SS::JobFilter navi_view "cms/node/main/navi" model Cms::CopyNodesTask private def job_class Cms::Node::CopyNodesJob end def job_bindings { site_id: @cur_site.id, node_id: @cur_node.id } end def job_options { target_node_name: params[:item][:target_node_name] } end def task_name job_class.task_name end def set_item @item = Cms::CopyNodesTask.find_or_initialize_by name: task_name, site_id: @cur_site.id, node_id: @cur_node.id end def get_params params.require(:item).permit(@model.permitted_fields).merge({}) end public def index set_item respond_to do |format| format.html { render } format.json { render file: "ss/tasks/index", content_type: json_content_type, locals: { item: @item } } end end def run set_item @item.attributes = get_params if @item.save job_class.bind(job_bindings).perform_later(job_options) respond_to do |format| format.html { redirect_to({ action: :index }, { notice: I18n.t('cms.copy_nodes.started_job') }) } format.json { render json: @item.to_json, status: :created, content_type: json_content_type } end else respond_to do |format| format.html { render action: :index } format.json { render json: @item.errors.full_messages, status: :unprocessable_entity, content_type: json_content_type } end end end end
22.362319
127
0.67466
082ffa855b755ab95c84f3a326ab6ba3dd1cd5b8
946
# frozen_string_literal: true require 'spec_helper' describe Gitlab::Template::Finders::GlobalTemplateFinder do let(:base_dir) { Dir.mktmpdir } def create_template!(name_with_category) full_path = File.join(base_dir, name_with_category) FileUtils.mkdir_p(File.dirname(full_path)) FileUtils.touch(full_path) end after do FileUtils.rm_rf(base_dir) end subject(:finder) { described_class.new(base_dir, '', 'Foo' => '', 'Bar' => 'bar') } describe '.find' do it 'finds a template in the Foo category' do create_template!('test-template') expect(finder.find('test-template')).to be_present end it 'finds a template in the Bar category' do create_template!('bar/test-template') expect(finder.find('test-template')).to be_present end it 'does not permit path traversal requests' do expect { finder.find('../foo') }.to raise_error(/Invalid path/) end end end
24.894737
85
0.689218
3372aa0b1f3d8e9756b4f1279e3b9cf1cd216a37
2,465
require "rails_helper" require "controller_helper" require "api_test_helper" require "support/list_size_matcher" describe AboutController do let(:identity_provider_display_decorator) { double(:IdentityProviderDisplayDecorator) } context "LOA1" do before(:each) do stub_request(:get, CONFIG.config_api_host + "/config/transactions/enabled") set_session_and_cookies_with_loa("LEVEL_1") stub_api_idp_list_for_registration(loa: "LEVEL_1") end context "GET about" do subject { get :about_verify, params: { locale: "en" } } before(:each) do stub_const("IDENTITY_PROVIDER_DISPLAY_DECORATOR", identity_provider_display_decorator) end it "renders the certified companies for on the combined about view" do expect(identity_provider_display_decorator).to receive(:decorate_collection).with(a_list_of_size(6)).and_return([]) expect(subject).to render_template(:how_verify_works) end end end context "LOA2" do before(:each) do stub_request(:get, CONFIG.config_api_host + "/config/transactions/enabled") set_session_and_cookies_with_loa("LEVEL_2") stub_api_idp_list_for_registration end context "GET about" do subject { get :about_verify, params: { locale: "en" } } before(:each) do stub_const("IDENTITY_PROVIDER_DISPLAY_DECORATOR", identity_provider_display_decorator) end it "renders the LOA2 certified companies for the combined about view" do expect(identity_provider_display_decorator).to receive(:decorate_collection).with(a_list_of_size(6)).and_return([]) expect(subject).to render_template(:how_verify_works) end end context "GET choosing a company" do subject { get :about_choosing_a_company, params: { locale: "en" } } it "renders the choosing a company page" do expect(subject).to render_template(:choosing_a_company) end end context "GET about documents" do subject { get :about_documents, params: { locale: "en" } } it "renders the choosing a company page" do expect(subject).to render_template(:documents) end end context "GET prove identity another way" do subject { get :prove_your_identity_another_way, params: { locale: "en" } } it "renders the choosing a company page" do expect(subject).to render_template(:prove_your_identity_another_way) end end end end
32.866667
123
0.710345
790e66447b8b59cb340de2b6a419909010eb60c1
4,744
# frozen_string_literal: true require "spec_helper" if ENV['IODINE'] require 'lite_cable/iodine_server' require "iodine" else require 'lite_cable/server' require "puma" end shared_examples "Lite Cable server" do let(:cookies) { "user=john" } let(:path) { "/?sid=123" } let(:client) { @client = SyncClient.new("ws://127.0.0.1:3099#{path}", cookies: cookies) } let(:logs) { ServerTest.logs } after { logs.clear } describe "connect" do it "receives welcome message" do expect(client.read_message).to eq("type" => "welcome") end context "when unauthorized" do let(:cookies) { '' } it "disconnects" do client.wait_for_close expect(client).to be_closed end end end describe "disconnect" do it "calls disconnect handlers" do expect(client.read_message).to eq("type" => "welcome") client.close client.wait_for_close expect(client).to be_closed wait { !logs.size.zero? } expect(logs.last).to include "john disconnected" end end describe "channels" do it "subscribes to channels and perform actions" do expect(client.read_message).to eq("type" => "welcome") client.send_message command: "subscribe", identifier: JSON.generate(channel: "echo") expect(client.read_message).to eq("identifier" => "{\"channel\":\"echo\"}", "type" => "confirm_subscription") client.send_message command: "message", identifier: JSON.generate(channel: "echo"), data: JSON.generate(action: "ding", message: "hello") expect(client.read_message).to eq("identifier" => "{\"channel\":\"echo\"}", "message" => { "dong" => "hello" }) end it "unsubscribes from channels and receive cleanup messages" do expect(client.read_message).to eq("type" => "welcome") client.send_message command: "subscribe", identifier: JSON.generate(channel: "echo") expect(client.read_message).to eq("identifier" => "{\"channel\":\"echo\"}", "type" => "confirm_subscription") client.send_message command: "unsubscribe", identifier: JSON.generate(channel: "echo") expect(client.read_message).to eq("identifier" => "{\"channel\":\"echo\"}", "message" => { "message" => "Goodbye, john!" }) expect(client.read_message).to eq("identifier" => "{\"channel\":\"echo\"}", "type" => "cancel_subscription") end end describe "broadcasts" do let(:client2) { @client2 = SyncClient.new("ws://127.0.0.1:3099/?sid=234", cookies: "user=alice") } let(:clients) { [client, client2] } before do concurrently(clients) do |c| expect(c.read_message).to eq("type" => "welcome") c.send_message command: "subscribe", identifier: JSON.generate(channel: "echo") expect(c.read_message).to eq("identifier" => "{\"channel\":\"echo\"}", "type" => "confirm_subscription") end end it "transmit messages to connected clients" do client.send_message command: "message", identifier: JSON.generate(channel: "echo"), data: JSON.generate(action: "bulk", message: "Good news, everyone!") concurrently(clients) do |c| expect(c.read_message).to eq("identifier" => "{\"channel\":\"echo\"}", "message" => { "message" => "Good news, everyone!", "from" => "john", "sid" => "123" }) end client2.send_message command: "message", identifier: JSON.generate(channel: "echo"), data: JSON.generate(action: "bulk", message: "A-W-E-S-O-M-E") concurrently(clients) do |c| expect(c.read_message).to eq("identifier" => "{\"channel\":\"echo\"}", "message" => { "message" => "A-W-E-S-O-M-E", "from" => "alice", "sid" => "234" }) end end end end context 'default Server (puma)', :async, unless: ENV['IODINE'] do include_examples 'Lite Cable server' do before(:all) do @server = ::Puma::Server.new( LiteCable::Server::Middleware.new(nil, connection_class: ServerTest::Connection), ::Puma::Events.strings ) @server.add_tcp_listener "127.0.0.1", 3099 @server.min_threads = 1 @server.max_threads = 4 @server_t = Thread.new { @server.run.join } end after(:all) do @server&.stop(true) @server_t&.join end end end context 'IodineServer', :async, if: ENV['IODINE'] do include_examples 'Lite Cable server' do before(:all) do Iodine.workers = 1 Iodine.threads = 4 @server = Thread.new do Iodine::Rack.run( LiteCable::Server::Middleware.new(nil, connection_class: ServerTest::Connection), Port: '3099', Address: '127.0.0.1' ) end end after(:all) do Iodine.stop @server.join # Iodine.stop is asynchronous, wait fot the server to shutdown. end end end
33.408451
166
0.631745
bfd74e582480b9cf7b131fcb0ff0f573d855c731
1,534
module RavenDB class GenerateEntityIdOnTheClient def initialize(conventions, generate_id) @_conventions = conventions @_generate_id = generate_id end def identity_property(entity_type) @_conventions.identity_property(entity_type) end def try_get_id_from_instance(entity, id_holder) raise ArgumentError, "Entity cannot be null" if entity.nil? identity_property = identity_property(entity.class) unless identity_property.nil? value = entity.send(identity_property) if value.is_a?(String) id_holder.value = value return true end end id_holder.value = nil false end def or_generate_document_id(entity) id_holder = Reference.new try_get_id_from_instance(entity, id_holder) id = id_holder.value id = @_generate_id[entity] if id.nil? if !id.nil? && id.start_with?("/") raise "Cannot use value '#{id}' as a document id because it begins with a '/'" end id end def generate_document_key_for_storage(entity) id = or_generate_document_id(entity) try_set_identity(entity, id) id end def try_set_identity(entity, id) entity_type = entity.class identity_property = @_conventions.identity_property(entity_type) return if identity_property.nil? set_property_or_field(entity, identity_property, id) end def set_property_or_field(entity, field, id) entity.send("#{field}=", id) end end end
27.890909
86
0.675359
2675e0932075eef2bb60d1892c57c9abac690a9f
42
require 'compound_interest/calculator.rb'
21
41
0.857143
21ac64e03954830829186cf12cc864fe8e03185a
136
class Api::TeamsController < ApplicationController def show @teams = Team.all render :json => @teams, status: 201 end end
15.111111
50
0.683824
edfeb2b1400e09b686376c92c7274bb92dc5a1d5
477
cask "singularity" do version "1.8.6,6156" sha256 "002597a1d7386ff1b505416476fce812037a38c61bd152212fd758db943de40c" # bitbucket.org/SingularityViewer/singularityviewer/ was verified as official when first introduced to the cask url "https://bitbucket.org/SingularityViewer/singularityviewer/downloads/Singularity_#{version.dots_to_underscores.sub(",", "_")}.dmg" name "Singularity Viewer" homepage "http://www.singularityviewer.org/" app "Singularity.app" end
39.75
136
0.796646
269dd442859927fdf68b461aa329965d64280ea5
475
# frozen_string_literal: true class Database < ApplicationRecord include Attributes::Strip include Databases::ActiveRecordConfig include Databases::Credentials include Databases::ODBC include Databases::Properties include Databases::Scopes include Databases::Search include Databases::Validations include Filterable include PublicAuditable scope :ordered, -> { order :name } strip_fields :name belongs_to :account def to_s name end end
19
39
0.768421
281ec71a9f71e79bce3cb4062e6f9dd7a2a6e15b
1,498
require 'activeadmin-sortable/version' require 'activeadmin' require 'rails/engine' module ActiveAdmin module Sortable module ControllerActions def sortable member_action :sort, :method => :post do if defined?(::Mongoid::Orderable) && resource.class.included_modules.include?(::Mongoid::Orderable) resource.move_to! params[:position].to_i else resource.insert_at params[:position].to_i end head 200 end end end module TableMethods HANDLE = '&#x2195;'.html_safe def sortable_handle_column column '', :class => "activeadmin-sortable" do |resource| sort_url, query_params = resource_path(resource).split '?', 2 sort_url += "/sort" sort_url += "?" + query_params if query_params order_by, order_dir = params[:order].split '_', 2 position = resource.send(order_by.to_sym) content_tag :span, HANDLE, :class => 'handle', 'data-sort-url' => sort_url, 'data-position' => position, 'data-order' => order_dir end end end ::ActiveAdmin::ResourceDSL.send(:include, ControllerActions) ::ActiveAdmin::Views::TableFor.send(:include, TableMethods) class Engine < ::Rails::Engine # Including an Engine tells Rails that this gem contains assets end end end
29.372549
74
0.583445
03bd0876ab14e4fcca2b832e322c486296850fdd
295
class AudioMate < Cask version '2.0.4' sha256 'dd66b67ff57c90d7f2c62c46f6a4049f5cecfbf1d5eb4fd502c447c9f0bef28b' url 'https://s3.amazonaws.com/apps-leftbee/products/downloadables/000/000/005/original/AudioMate-v2.0.4.dmg' homepage 'http://audiomateapp.com/' link 'AudioMate.app' end
29.5
110
0.783051
6a69621b15755b69da95c7870ef3c726fd005971
2,200
class IngramMicro::Transmission XSD = { 'sales-order-submission' => 'outbound/BPXML-SalesOrderDomestic.xsd', 'sales-order-international' => 'outbound/BPXML-SalesOrderInternational.xsd', 'shipment-status' => 'outbound/BPXML-ShipmentStatus.xsd', 'return-authorization' => 'outbound/BPXML-ReturnAuthorization.xsd', 'standard-response' => 'outbound/BPXML-StandardResponse.xsd', 'load-reject' => 'inbound/BPXML-LoadReject.xsd', 'load-success' => 'inbound/BPXML-LoadSuccess.xsd', 'return-receipt' => 'inbound/BPXML-ReturnReceipt.xsd', 'ship-advice' => 'inbound/BPXML-ShipAdvice.xsd' } attr_reader :errors, :transaction_name def initialize(options={}) @errors = [] end def schema_valid? xsd = load_schema valid = true xsd.validate(self.xml_builder.doc).each do |error| errors << error.message valid = false end errors.each { |error| puts 'XML VALIDATION ERROR: ' + error } valid end # This will find the appropriate xsd file and return it for use in xml # validation. For sales-order-submission, there are two different schemas, # and which one to load depends on whether you need the one configured for # domestic-only use or the one for mixed domestic and internatinal use. def load_schema transmission_name = self.class::TRANSMISSION_FILENAME if transmission_name == 'sales-order-submission' && !IngramMicro.domestic_schema? transmission_name = 'sales-order-international' end Nokogiri::XML::Schema(File.read("#{IngramMicro::GEM_DIR}/xsd/" + XSD[transmission_name])) end def order_builder warn '[DEPRECATION] `order_builder` is deprecated. Please use `xml_builder` instead.' xml_builder end def xml_builder raise StandardError, 'xml_builder needs to be implemented in subclass' end def add_transaction_info(builder) builder.send('transactionInfo') do builder.send('eventID') end end def submit_request raise IngramMicro::XMLSchemaMismatch, 'xml did not pass schema' if !schema_valid? send_request end def send_request client = IngramMicro::Client.new client.post(self.xml_builder.to_xml) end end
31.428571
90
0.71
bf0f7e5c1cbb4bd4719dfb7687e33d4180cd32a5
261
require 'rails_helper' RSpec.describe "routing to jimmy_wales" do it "routes http://dyl.anjon.es/jimmywales to jimmy_wales" do expect(get: "http://dyl.anjon.es/jimmywales").to route_to( controller: "jimmy_wales", action: "index") end end
21.75
62
0.697318
f83ea5e6511398a63ee725a8b252bb3b907b447d
1,709
# # Testing OpenWFE # # John Mettraux at openwfe.org # # Thu Nov 22 11:53:13 JST 2007 # require File.dirname(__FILE__) + '/flowtestbase' require 'openwfe/def' class FlowTest9b < Test::Unit::TestCase include FlowTestBase # # Test 0 # class Test0 < OpenWFE::ProcessDefinition cursor do set :v => 'v0', :val => 'x' _print '${v0}' end end def test_0 dotest Test0, 'x' end # # Test 1 # #class Test1 < OpenWFE::ProcessDefinition # cursor do # my_participant # end #end #def test_1 # @engine.register_participant :my_participant do |fexp, wi| # #puts fexp.to_s # #puts fexp.environment_id.to_s # @tracer << "ok0\n" if fexp.environment_id.expid != fexp.fei.expid # @tracer << "ok1\n" if fexp.environment_id.expid == "0.0" # @tracer << "ok2\n" if fexp.environment_id.wfid + ".0" == fexp.fei.wfid # end # dotest Test1, "ok0\nok1\nok2" #end # # Test 2 # class Test2 < OpenWFE::ProcessDefinition cursor do my_participant end end class MyParticipant include OpenWFE::LocalParticipant def initialize (tracer) @tracer = tracer end def consume (workitem) @tracer << "consume\n" @workitem = workitem end def cancel (cancelitem) @tracer << "cancel\n" end end def test_2 #log_level_to_debug @engine.register_participant :my_participant, MyParticipant.new(@tracer) fei = launch Test2 sleep 0.350 @engine.cancel_process fei sleep 0.350 assert( [ "consume\ncancel", "consume\ncancel\ncancel" ].include?(@tracer.to_s)) assert_equal 1, @engine.get_expression_storage.size end end
17.09
77
0.626097
617b2b11752e5795ef22d5e3e1baea4740c701c8
564
require "ffi_yajl" require "chef_zero/rest_base" module ChefZero module Endpoints # /users/NAME/association_requests/count class UserAssociationRequestsCountEndpoint < RestBase def get(request) get_data(request, request.rest_path[0..-3]) username = request.rest_path[1] result = list_data(request, [ "organizations" ]).select do |org| exists_data?(request, [ "organizations", org, "association_requests", username ]) end json_response(200, { "value" => result.size }) end end end end
28.2
91
0.66844
39d7db5422b3ef89ed12ab21725a4f380e43a255
692
# frozen_string_literal: true json.id @system.id json.name @system.name json.description @system.description json.coords_x @system.coords_x json.coords_y @system.coords_y json.time_to_jump @system.time_to_jump json.occupation_dates @system.system_occupation_dates do |date| json.faction date.faction json.start date.occupation_start end json.owner_eras @system.system_owner_eras do |era| json.faction era.faction json.era era.era end json.factories @system.factories do |factory| json.factory factory.name json.components factory.components do |component| json.name component.name json.type component.component_type.name end end
25.62963
63
0.760116
f84db1e8dae30b88a427a90465cb39bed088cefa
1,855
require 'pathname' module Xcake # This class handles classifing the files and how Xcake should handle them. # class PathClassifier EXTENSION_MAPPINGS = { PBXFrameworksBuildPhase: %w(.a .dylib .so .framework).freeze, PBXHeadersBuildPhase: %w(.h .hpp).freeze, PBXSourcesBuildPhase: %w(.c .m .mm .cpp .swift .xcdatamodeld .java).freeze, PBXResourcesBuildPhase: %w(.xcassets).freeze }.freeze # @note This should be overidden # by subclasses. # # @param [String] the path # # @return [Boolean] true if classifier thinks the path should be included # into the project # def self.should_include_path?(path) return false if locale_container?(path) return false if inside_classified_container?(path) true end def self.classification_for_path(path) classification = EXTENSION_MAPPINGS.detect do |_key, ext_group| ext_group.any? { |ext| File.extname(path) == ext } end return :PBXResourcesBuildPhase if classification.nil? classification.first end def self.should_create_build_phase_for_classification?(classification) classification != :PBXHeadersBuildPhase end class << self private def locale_container?(path) components = path.split('/') File.extname(components.last) == '.lproj' end def inside_classified_container?(path) components = path.split('/') classified_component_index = components.index do |c| classified?(c) end if !classified_component_index.nil? classified_component_index < (components.length - 1) else false end end def classified?(path) EXTENSION_MAPPINGS.values.flatten.any? { |ext| File.extname(path) == ext } end end end end
26.126761
82
0.652291
1c76bf8443673d4a42385208cb6967b6f004a542
495
# Migration test. Miguel::Schema.define do table :a do primary_key :id Float :a foreign_key :fk, :c end table :b do primary_key :id Text :t Unsigned :u, default: 123 Signed? :s timestamps foreign_key :fk, :c unique :u index :create_time end table :c do primary_key :id String? :s Text :t end table :d do Integer :a Integer :b primary_key [:a,:b] end join_table :left_id, :a, :right_id, :b end # EOF #
12.692308
40
0.581818
7aa64730f27405cf5f72e6d0cd96d7949d42b98c
6,798
require 'spec_helper' describe Ability, :type => :request do let(:organization) { threadable.organizations.find_by_slug('raceteam') } let(:organization_members) { organization.members } let(:member) { organization.members.current_member} let(:group) { organization.groups.find_by_slug('electronics') } let(:group_members) { group.members } let(:tom) { organization.members.find_by_email_address('[email protected]')} describe 'for owners' do before do sign_in_as '[email protected]' end describe 'organization' do it 'can do everything' do expect(member.can?(:make_owners_for, organization)).to be_truthy expect(member.can?(:change_settings_for, organization)).to be_truthy expect(member.can?(:remove_non_empty_group_from, organization)).to be_truthy expect(member.can?(:be_google_user_for, organization)).to be_truthy expect(member.can?(:create, organization_members)).to be_truthy expect(member.can?(:delete, organization_members)).to be_truthy expect(member.can?(:change_delivery_for, organization.members.find_by_user_id(tom.id))).to be_truthy end end describe 'group' do it 'can do almost everything' do expect(member.can?(:set_google_sync_for, group)).to be_truthy expect(member.can?(:change_settings_for, group)).to be_truthy expect(member.can?(:change_settings_when_private_for, group)).to be_truthy expect(member.can?(:create, group_members)).to be_truthy expect(member.can?(:delete, group_members)).to be_truthy expect(member.can?(:change_delivery_for, group.members.find_by_user_id(tom.id))).to be_truthy expect(member.can?(:read_private, organization.groups)).to be_truthy end context 'when the organization is free' do before do organization.organization_record.update_attribute(:plan, :free) end it 'cannot make private groups' do expect(member.can?(:make_private, organization.groups)).to be_falsy end end context 'when the organization is paid' do before do organization.organization_record.update_attribute(:plan, :paid) end it 'cannot make private groups' do expect(member.can?(:make_private, organization.groups)).to be_truthy end end end end describe 'for members' do let(:bethany) { organization.members.find_by_email_address('[email protected]')} before do sign_in_as '[email protected]' end describe 'organization' do it 'can do nothing' do expect(member.can?(:make_owners_for, organization)).to be_falsy expect(member.can?(:change_settings_for, organization)).to be_falsy expect(member.can?(:remove_non_empty_group_from, organization)).to be_falsy expect(member.can?(:be_google_user_for, organization)).to be_falsy end context 'when the org allows changing org membership' do before do organization.organization_record.update_attribute(:organization_membership_permission, 0) end it 'can add to the org membership' do expect(member.can?(:change_delivery_for, organization.members.find_by_user_id(tom.id))).to be_truthy expect(member.can?(:create, organization_members)).to be_truthy expect(member.can?(:delete, organization_members)).to be_falsy end end context 'when the org does not allow changing org membership' do before do organization.organization_record.update_attribute(:organization_membership_permission, 1) end it 'cannot add to the org membership' do expect(member.can?(:change_delivery_for, organization.members.find_by_user_id(tom.id))).to be_falsy expect(member.can?(:create, organization_members)).to be_falsy expect(member.can?(:delete, organization_members)).to be_falsy end end end describe 'group' do it 'cannot change the google user or private group settings' do expect(member.can?(:set_google_sync_for, group)).to be_falsy expect(member.can?(:change_settings_when_private_for, group)).to be_falsy end context 'when the organization is free' do before do organization.organization_record.update_attribute(:plan, :free) end it 'cannot make private groups' do expect(member.can?(:make_private, organization.groups)).to be_falsy end end context 'when the organization is paid' do before do organization.organization_record.update_attribute(:plan, :paid) end it 'cannot make private groups' do expect(member.can?(:make_private, organization.groups)).to be_truthy end end context 'when the org allows changing group settings' do before do organization.organization_record.update_attribute(:group_settings_permission, 0) end it 'can change the group settings' do expect(member.can?(:change_settings_for, group)).to be_truthy end end context 'when the org does not allow changing group settings' do before do organization.organization_record.update_attribute(:group_settings_permission, 1) end it 'cannot change the group settings' do expect(member.can?(:change_settings_for, group)).to be_falsy end end context 'when the org allows changing group membership' do before do organization.organization_record.update_attribute(:group_membership_permission, 0) end it 'can change the group membership' do expect(member.can?(:create, group_members)).to be_truthy expect(member.can?(:delete, group_members)).to be_truthy expect(member.can?(:change_delivery_for, group.members.find_by_user_id(tom.id))).to be_truthy end end context 'when the org does not allow changing group membership' do before do organization.organization_record.update_attribute(:group_membership_permission, 1) end it 'can change the group membership' do expect(member.can?(:create, group_members)).to be_falsy expect(member.can?(:delete, group_members)).to be_falsy expect(member.can?(:change_delivery_for, group.members.find_by_user_id(tom.id))).to be_falsy expect(member.can?(:change_delivery_for, group.members.find_by_user_id(bethany.id))).to be_truthy end end end end end
38.625
116
0.670786
916006406570b561e5e78548e51367607cb1ee2c
1,630
# # Be sure to run `pod lib lint DXDownload.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'DXDownload' s.version = '1.1.0' s.summary = 'A short description of DXDownload.' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC TODO: Add long description of the pod here. DESC s.homepage = 'https://github.com/Jackdx/DXDownload' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'Jackdx' => '[email protected]' } s.source = { :git => 'https://github.com/Jackdx/DXDownload.git', :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '9.0' s.source_files = 'DXDownload/Classes/**/*' # s.resource_bundles = { # 'DXDownload' => ['DXDownload/Assets/*.png'] # } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' s.dependency 'AFNetworking', '~> 4.0.0' s.dependency 'TMCache', '~> 2.1.0' end
37.045455
101
0.634356
187c314b30c17e19841eedd8f44e10a7a07fe098
1,230
require 'test_helper' class FinancialMonthsControllerTest < ActionDispatch::IntegrationTest setup do @financial_month = financial_months(:one) end test "should get index" do get financial_months_url assert_response :success end test "should get new" do get new_financial_month_url assert_response :success end test "should create financial_month" do assert_difference('FinancialMonth.count') do post financial_months_url, params: { financial_month: { } } end assert_redirected_to financial_month_url(FinancialMonth.last) end test "should show financial_month" do get financial_month_url(@financial_month) assert_response :success end test "should get edit" do get edit_financial_month_url(@financial_month) assert_response :success end test "should update financial_month" do patch financial_month_url(@financial_month), params: { financial_month: { } } assert_redirected_to financial_month_url(@financial_month) end test "should destroy financial_month" do assert_difference('FinancialMonth.count', -1) do delete financial_month_url(@financial_month) end assert_redirected_to financial_months_url end end
25.102041
82
0.757724
61b8e4888322a0b6b416481e44436deac5a62205
2,826
require 'spec_helper' describe 'collectd::plugin::write_graphite::carbon', type: :define do let :facts do { osfamily: 'Debian', id: 'root', concat_basedir: '/dne', path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', collectd_version: '4.8.0', operatingsystemmajrelease: '7', python_dir: '/usr/local/lib/python2.7/dist-packages' } end context 'protocol should not be include with version < 5.4' do let(:title) { 'graphite_udp' } let :facts do { osfamily: 'RedHat', collectd_version: '5.3', concat_basedir: '/dne', operatingsystemmajrelease: '7', python_dir: '/usr/local/lib/python2.7/dist-packages' } end let :params do { protocol: 'udp' } end it 'does not include protocol in /etc/collectd.d/write_graphite.conf for collectd < 5.4' do is_expected.not_to contain_concat__fragment( 'collectd_plugin_write_graphite_conf_localhost_2003' ).with_content(%r{.*Protocol \"udp\".*}) end end context 'protocol should be include with version >= 5.4' do let(:title) { 'wg' } let :facts do { osfamily: 'RedHat', collectd_version: '5.4', concat_basedir: '/dne', operatingsystemmajrelease: '7', python_dir: '/usr/local/lib/python2.7/dist-packages' } end let :params do { protocol: 'udp' } end it 'includes protocol in /etc/collectd.d/write_graphite.conf for collectd >= 5.4' do is_expected.to contain_concat__fragment( 'collectd_plugin_write_graphite_conf_wg_udp_2003' ).with_content(%r{.*Protocol \"udp\".*}) end it 'uses Node definition' do is_expected.to contain_concat__fragment('collectd_plugin_write_graphite_conf_wg_udp_2003').with(content: %r{<Node "wg">}, target: '/etc/collectd.d/write_graphite-config.conf') end end context 'default configuration (undefined collectd version)' do let(:title) { 'graphite_default' } it 'includes carbon configuration' do is_expected.to contain_concat__fragment('collectd_plugin_write_graphite_conf_graphite_default_tcp_2003').with(content: %r{<Carbon>}, target: '/etc/collectd/conf.d/write_graphite-config.conf') is_expected.to contain_concat__fragment('collectd_plugin_write_graphite_conf_graphite_default_tcp_2003').with(content: %r{Host "localhost"}) is_expected.to contain_concat__fragment('collectd_plugin_write_graphite_conf_graphite_default_tcp_2003').with(content: %r{Port "2003"}) end end end
34.463415
174
0.617834
62729436adf95a5559914977401ad089930e7278
417
cask 'vuescan' do version '9.5.90' sha256 '0c77e72b7ee929820b06973bb5e953c4b4b66d7aae6f6c201b57ae5f433b8072' url "https://www.hamrick.com/files/vuex64#{version.major_minor.no_dots}.dmg" appcast 'https://www.hamrick.com/old-versions.html', checkpoint: '105d346d578b815e7d1eeb5fdbe5e8c329af7ae6e76c331f663bdb1cf8f05e2c' name 'VueScan' homepage 'https://www.hamrick.com/' app 'VueScan.app' end
32.076923
88
0.769784
33dbdf40a68010588a06572f75f37159cabd84f9
3,831
# coding: UTF-8 require 'spec_helper' describe "Assets API" do before(:all) do AWS.stub! end before(:each) do @user = FactoryGirl.create(:valid_user) delete_user_data @user host! "#{@user.username}.localhost.lan" end after(:each) do @user.destroy end let(:params) { { :api_key => @user.api_key } } it 'creates a new asset' do Asset.any_instance.stubs('use_s3?').returns(false) file_path = Rails.root.join('spec', 'support', 'data', 'cartofante_blue.png') if File.exist?(file_path) && File.file?(file_path) uploaded_file = Rack::Test::UploadedFile.new(file_path, 'image/png') post_json( api_v1_users_assets_create_url(user_id: @user), params.merge(kind: 'wadus', filename: uploaded_file.path) ) do |response| response.status.should be_success response.body[:public_url].should =~ /\/test\/#{@user.username}\/assets\/\d+cartofante_blue/ URI(response.body[:public_url]).should be_absolute response.body[:kind].should == 'wadus' @user.reload @user.assets.count.should == 1 asset = @user.assets.first asset.public_url.should =~ /\/test\/#{@user.username}\/assets\/\d+cartofante_blue/ asset.kind.should == 'wadus' end else pending("Required spec asset '#{file_path}' not found, test can't properly execute") end end it 'creates a new asset with spaces in name' do Asset.any_instance.stubs('use_s3?').returns(false) file_path = Rails.root.join('spec', 'support', 'data', 'cartofante blue.png') if File.exist?(file_path) && File.file?(file_path) uploaded_file = Rack::Test::UploadedFile.new(file_path, 'image/png') post_json( api_v1_users_assets_create_url(user_id: @user), params.merge(kind: 'wadus', filename: uploaded_file.path) ) do |response| response.status.should be_success response.body[:public_url].should =~ /\/test\/#{@user.username}\/assets\/\d+cartofante%20blue/ URI(response.body[:public_url]).should be_absolute response.body[:kind].should == 'wadus' @user.reload @user.assets.count.should == 1 asset = @user.assets.first asset.public_url.should =~ /\/test\/#{@user.username}\/assets\/\d+cartofante%20blue/ asset.kind.should == 'wadus' end else pending("Required spec asset '#{file_path}' not found, test can't properly execute") end end it "returns some error message when the asset creation fails" do pending "Fix this test, sometimes fails" Asset.any_instance.stubs(:s3_bucket).raises("AWS exception") post_json(api_v1_users_assets_create_url(user_id: @user), params.merge( :filename => Rack::Test::UploadedFile.new(Rails.root.join('spec/support/data/cartofante_blue.png'), 'image/png').path) ) do |response| response.status.should == 400 response.body[:error].should == ["AWS exception"] end end it "finds image file extension" do asset = FactoryGirl.create(:asset, user_id: @user.id) Asset::VALID_EXTENSIONS.each do |extension| asset_name = "cartofante" + extension asset.stubs(:asset_file).returns(asset_name) asset.asset_file_extension.should == extension end end it "detects incorrect image file extension" do asset = FactoryGirl.create(:asset, user_id: @user.id) asset.stubs(:asset_file).returns("cartofante.gifv") asset.asset_file_extension.should == nil end it "deletes an asset" do FactoryGirl.create(:asset, user_id: @user.id) @user.reload delete_json(api_v1_users_assets_destroy_url(user_id: @user.id, id: @user.assets.first.id), params) do |response| response.status.should be_success @user.reload @user.assets.count.should == 0 end end end
33.605263
124
0.665362
2193207b630bebce8bc3f9395cabe2ac469141d5
6,789
#!/usr/bin/env ruby require 'yaml' require 'fileutils' require_relative '../../../lib/upgrade' class CommonEnforcer < Upgrade::BaseActivationEnforcer def enable_micro_depls micro_depls_deployments = %w[ 00-core-connectivity-terraform bosh-master concourse credhub-ha credhub-seeder dns-recursor docker-bosh-cli gitlab jcr internet-proxy minio-private-s3 nexus prometheus-exporter-master ] micro_depls.enable_deployments(micro_depls_deployments) end def disable_micro_depls micro_depls_deployments = %w[ ntp k8s k8s-addon k8s-traefik k8s-jaeger k8s-openebs k8s-longhorn k8s-logging k8s-prometheus k8s-kubeapps ] micro_depls.disable_deployments(micro_depls_deployments) end def micro_depls_pipelines # Nothing shared in v44 end def micro_depls_ci_overview root_deployment_name = 'micro-depls' ci_deployment_overview = Upgrade::CiDeploymentOverview.new(root_deployment_name, @config_path) pipelines_activation = Upgrade::CiDeploymentOverviewPipelineActivation.new( root_deployment_name, ci_deployment_overview.load.dig('ci-deployment',root_deployment_name,'pipelines')) pipelines_activation.activate pipelines_activation.activate_bosh_pipelines pipelines_activation.activate_concourse_pipelines ci_deployment_overview.target_name ci_deployment_overview.enable_terraform ci_deployment_overview.update_pipeline(pipelines_activation.pipelines) ci_deployment_overview.update end def enable_master_depls master_depls_deployments = %w[ bosh-coab bosh-ops cf cloudfoundry-datastores intranet-interco-relay isolation-segment-intranet-1 logsearch-ops metabase openldap ops-routing osb-routing prometheus prometheus-exporter-coab prometheus-exporter-ops weave-scope isolation-segment-internal ] master_depls.enable_deployments(master_depls_deployments) end def disable_master_depls master_depls_deployments = %w[ prometheus-exporter-kubo shield k8s k8s-addon k8s-traefik k8s-jaeger k8s-longhorn k8s-logging k8s-prometheus k8s-metabase k8s-grafana k8s-openebs k8s-kubeapps ] master_depls.disable_deployments(master_depls_deployments) end def master_depls_pipelines pipelines = %w[ cached-buildpack-pipeline ] master_depls.enable_deployments(pipelines) end def master_depls_ci_overview root_deployment_name = 'master-depls' ci_deployment_overview = Upgrade::CiDeploymentOverview.new(root_deployment_name, @config_path) pipelines_activation = Upgrade::CiDeploymentOverviewPipelineActivation.new( root_deployment_name, ci_deployment_overview.load.dig('ci-deployment',root_deployment_name,'pipelines')) pipelines_activation.activate pipelines_activation.activate_bosh_pipelines pipelines_activation.activate_concourse_pipelines ci_deployment_overview.target_name ci_deployment_overview.enable_terraform ci_deployment_overview.update_pipeline(pipelines_activation.pipelines) ci_deployment_overview.update end def enable_ops_depls ops_deployments = %w[ cf-rabbit37 cf-rabbit-osb mongodb-osb ] ops_depls.enable_deployments(ops_deployments) end def disable_ops_depls ops_deployments = %w[ admin-ui cf-rabbit ] ops_depls.disable_deployments(ops_deployments) end def ops_depls_pipelines # Nothing in v44 end def ops_depls_cf_apps enabled_ops_cf_apps = %w[ admin-ui stratos-ui-v2 ] ops_depls.enable_cf_app_deployments(enabled_ops_cf_apps) disabled_ops_cf_apps = %w[ app-with-metrics-influxdb cf-webui ] ops_depls.disable_deployments(disabled_ops_cf_apps) end def ops_depls_ci_overview root_deployment_name = 'ops-depls' ci_deployment_overview = Upgrade::CiDeploymentOverview.new(root_deployment_name, @config_path) pipelines_activation = Upgrade::CiDeploymentOverviewPipelineActivation.new( root_deployment_name, ci_deployment_overview.load.dig('ci-deployment',root_deployment_name,'pipelines')) pipelines_activation.activate pipelines_activation.activate_bosh_pipelines pipelines_activation.activate_concourse_pipelines pipelines_activation.activate_cf_apps_pipelines ci_deployment_overview.target_name ci_deployment_overview.enable_terraform("#{root_deployment_name}/cloudfoundry/terraform-config") ci_deployment_overview.update_pipeline(pipelines_activation.pipelines) ci_deployment_overview.update end def enable_coab_depls coab_deployments = %w[ 01-cf-mysql-extended cf-mysql mongodb redis 02-redis-extended ] coab_depls.enable_deployments(coab_deployments) end def disable_coab_depls coab_deployments = %w[ bui shield 10-k8s-openebs 10-k8s 10-k8s-addon 10-k8s-traefik 10-k8s-jaeger 10-k8s-longhorn 10-k8s-logging 10-k8s-prometheus 10-k8s-kubeapps ] coab_depls.disable_deployments(coab_deployments) end def enable_coab_depls_cf_apps coab_cf_apps = %w[ coa-cf-mysql-broker coa-cf-mysql-extended-broker coa-mongodb-broker coa-redis-broker coa-redis-extended-broker ] coab_depls.enable_cf_app_deployments(coab_cf_apps) end def disable_coab_depls_cf_apps coab_cf_apps = %w[ ] coab_depls.disable_cf_app_deployments(coab_cf_apps) end def coab_depls_pipelines # No specific activation in v46.0.0 end def coab_depls_ci_overview root_deployment_name = 'coab-depls' ci_deployment_overview = Upgrade::CiDeploymentOverview.new(root_deployment_name, @config_path) pipelines_activation = Upgrade::CiDeploymentOverviewPipelineActivation.new( root_deployment_name, ci_deployment_overview.load.dig('ci-deployment',root_deployment_name,'pipelines')) pipelines_activation.activate pipelines_activation.activate_bosh_pipelines pipelines_activation.activate_cf_apps_pipelines pipelines_activation.activate_concourse_pipelines ci_deployment_overview.target_name ci_deployment_overview.enable_terraform ci_deployment_overview.update_pipeline(pipelines_activation.pipelines) ci_deployment_overview.update ci_deployment_overview.add_default_auto_init_credentials end def enable_kubo_depls end def disable_kubo_depls kubo_depls_deployments = %w[ ] kubo_depls.disable_deployments(kubo_depls_deployments) end def kubo_depls_pipelines end end config_path = ARGV[0] CommonEnforcer.new(config_path).run
28.52521
184
0.752835
26f1b62c5b675cd1c73e8a8eb608060574262755
3,007
class Cairo < Formula desc "Vector graphics library with cross-device output support" homepage "https://cairographics.org/" url "https://cairographics.org/releases/cairo-1.14.12.tar.xz" mirror "https://www.mirrorservice.org/sites/ftp.netbsd.org/pub/pkgsrc/distfiles/cairo-1.14.12.tar.xz" sha256 "8c90f00c500b2299c0a323dd9beead2a00353752b2092ead558139bd67f7bf16" revision 3 unless OS.mac? bottle do sha256 "5bdc28de8e5a615ab664d43f7f322ed02d58071171415bb6e2750f486b9465e2" => :high_sierra sha256 "102847d74a0a11bb6143d93b9f32e1736e88036fb4c685d554a8bcd376bbd929" => :sierra sha256 "bec85433a35605164bdbf5f8913e29eb6d9ceb5acc5569dd9d864706ae6c8d49" => :el_capitan sha256 "f280c34cad69a036fb1f209249e054e78da643481afd8a3962bed5ad91ca9ccb" => :x86_64_linux end head do url "https://anongit.freedesktop.org/git/cairo", :using => :git depends_on "automake" => :build depends_on "autoconf" => :build depends_on "libtool" => :build end depends_on "pkg-config" => :build depends_on "freetype" depends_on "fontconfig" depends_on "libpng" depends_on "pixman" depends_on "glib" unless OS.mac? depends_on "zlib" depends_on "linuxbrew/xorg/xorg" => :recommended if build.with?("xorg") depends_on "linuxbrew/xorg/kbproto" depends_on "linuxbrew/xorg/libxcb" depends_on "linuxbrew/xorg/renderproto" depends_on "linuxbrew/xorg/xcb-proto" depends_on "linuxbrew/xorg/xextproto" end end def install args = %W[ --disable-dependency-tracking --prefix=#{prefix} --enable-gobject=yes --enable-svg=yes --enable-tee=yes ] args += %w[ --enable-quartz-image ] if OS.mac? if !OS.mac? || build.with?("xorg") args << "--enable-xcb=yes" << "--enable-xlib=yes" << "--enable-xlib-xrender=yes" else args << "--enable-xcb=no" << "--enable-xlib=no" << "--enable-xlib-xrender=no" end if build.head? ENV["NOCONFIGURE"] = "1" system "./autogen.sh" end system "./configure", *args system "make", "install" end test do (testpath/"test.c").write <<~EOS #include <cairo.h> int main(int argc, char *argv[]) { cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 600, 400); cairo_t *context = cairo_create(surface); return 0; } EOS fontconfig = Formula["fontconfig"] freetype = Formula["freetype"] gettext = Formula["gettext"] glib = Formula["glib"] libpng = Formula["libpng"] pixman = Formula["pixman"] flags = %W[ -I#{fontconfig.opt_include} -I#{freetype.opt_include}/freetype2 -I#{gettext.opt_include} -I#{glib.opt_include}/glib-2.0 -I#{glib.opt_lib}/glib-2.0/include -I#{include}/cairo -I#{libpng.opt_include}/libpng16 -I#{pixman.opt_include}/pixman-1 -L#{lib} -lcairo ] system ENV.cc, "test.c", "-o", "test", *flags system "./test" end end
29.480392
103
0.659461
f87e32252139665c32d1186311e27056b67c5fcd
10,917
module JABA ## # class JabaAttributeBase attr_reader :services attr_reader :node attr_reader :attr_def ## # def initialize(attr_def, node, outer_attr) @services = node.services @attr_def = attr_def @node = node @outer_attr = outer_attr @last_call_location = nil @set = false @default_block = @attr_def.default_block end ## # def type_id @attr_def.type_id end ## # def defn_id @attr_def.defn_id end ## # def single? @attr_def.single? end ## # def array? @attr_def.array? end ## # def hash? @attr_def.hash? end ## # Used in error messages. # def describe @outer_attr.do_describe end ## # def set? @set end ## # def required? @attr_def.has_flag?(:required) end ## # Allows attributes to be treated the same as JabaObject for error reporting. # def src_loc @last_call_location end ## # def jaba_warn(msg) obj = @last_call_location ? self : @attr_def services.jaba_warn(msg, errobj: obj) end ## # TODO: review def attr_error(msg, callstack: nil) jdl_bt = services.get_jdl_backtrace(callstack || caller) if jdl_bt.empty? obj = @last_call_location ? self : @attr_def JABA.error(msg, errobj: obj) else JABA.error(msg, callstack: jdl_bt) end end ## # def call_validators begin yield rescue => e attr_error("#{describe} invalid: #{e.message}", callstack: e.backtrace) end end ## # def value_from_block(__jdl_call_loc, id:, block_args: nil, &block) if @attr_def.compound? if @value # If node has already been made but the compound attr is being set again, re-evaluate existing value against block @value.eval_jdl(&block) return @value else nm = services.get_node_manager(@attr_def.ref_jaba_type) dfn = services.make_definition(@node.defn_id, block, __jdl_call_loc) nm_dfn = nm.add_compound_attr_definition(dfn, name: id, parent: @node, block_args: block_args, flags: NodeFlags::IS_COMPOUND_ATTR) nm.process return nm_dfn.root_node end elsif @attr_def.block_attr? block # If its a block attr the value is the block itself else return @node.eval_jdl(&block) end end end ## # class JabaAttributeElement < JabaAttributeBase attr_reader :value_options attr_reader :flag_options ## # def initialize(attr_def, node, parent) super @value = nil @flag_options = nil @value_options = nil @in_on_set = false end ## # For ease of debugging. # def to_s "#{@attr_def} value=#{@value}" end ## # Returns the value of the attribute. If value is a reference to a JabaNode and the call to value() came from user # definitions then return the node's attributes rather than the node itself. # def value(jdl_call_loc = nil) @last_call_location = jdl_call_loc if jdl_call_loc if jdl_call_loc && @value.is_a?(JabaNode) @value.attrs_read_only.__internal_set_jdl_call_loc(jdl_call_loc) else @value end end ## # def set(*args, __jdl_call_loc: nil, validate: true, __resolve_ref: true, call_on_set: true, **keyval_args, &block) @last_call_location = __jdl_call_loc if __jdl_call_loc # Check for read only if calling from definitions, or if not calling from definitions but from library code, # allow setting read only attrs the first time, in order to initialise them. # if (__jdl_call_loc || @set) && [email protected]_set_read_only_attrs? if @attr_def.has_flag?(:read_only) attr_error("#{describe} is read only") end end new_value = if block_given? value_from_block(__jdl_call_loc, id: "#{@attr_def.defn_id}", &block) else if @attr_def.compound? && !@outer_attr attr_error("Compound attributes require a block") end args.shift end if new_value.is_a?(Enumerable) attr_error("#{describe} must be a single value not a '#{new_value.class}'") end attr_type = @attr_def.jaba_attr_type new_value = attr_type.map_value(new_value) @flag_options = args # Take a deep copy of value_options so they are private to this attribute # @value_options = keyval_args.empty? ? {} : Marshal.load(Marshal.dump(keyval_args)) if validate @flag_options.each do |f| if !@attr_def.flag_options.include?(f) attr_error("Invalid flag option '#{f.inspect_unquoted}' passed to #{describe}. Valid flags are #{@attr_def.flag_options}") end end # Validate that value options flagged as required have been supplied # @attr_def.each_value_option do |vo| if vo.required if !@value_options.key?(vo.id) if !vo.items.empty? attr_error("When setting #{describe} '#{vo.id}' option requires a value. Valid values are #{vo.items.inspect}") else attr_error("When setting #{describe} '#{vo.id}' option requires a value") end end end end # Validate that all supplied value options exist and have valid values # @value_options.each do |k, v| vo = @attr_def.get_value_option(k) if !vo.items.empty? if !vo.items.include?(v) attr_error("When setting #{describe} invalid value '#{v.inspect_unquoted}' passed to '#{k.inspect_unquoted}' option. Valid values: #{vo.items.inspect}") end end end if !new_value.nil? call_validators do attr_type.validate_value(@attr_def, new_value) @attr_def.call_block_property(:validate, new_value, @flag_options, **@value_options) end end end @value = new_value if @attr_def.reference? if __resolve_ref # Only resolve reference immediately if referencing a different type to this node's type. This is because not all nodes # of the same type will have been created by this point whereas nodes of a different type will all have been created # due to having been dependency sorted. References to the same type are resolved after all nodes have been created. # @value = @node.node_manager.resolve_reference(self, new_value, ignore_if_same_type: true) end elsif !@attr_def.compound? # Don't freeze whole nodes @value.freeze # Prevents value from being changed directly after it has been returned by 'value' method end @set = true if call_on_set if @in_on_set JABA.error("Reentrancy detected in #{describe} on_set") end @in_on_set = true @attr_def.call_block_property(:on_set, new_value, receiver: @node) @in_on_set = false end nil end ## # def <=>(other) if @value.respond_to?(:casecmp) @value.to_s.casecmp(other.value.to_s) # to_s is required because symbols need to be compared to strings else @value <=> other.value end end ## # def has_flag_option?(o) @flag_options&.include?(o) end ## # def get_option_value(key, fail_if_not_found: true) @attr_def.get_value_option(key) if !@value_options.key?(key) if fail_if_not_found attr_error("Option key '#{key}' not found in #{describe}") else return nil end end @value_options[key] end ## # def map_value_option! attr_def.each_value_option do |vod| if @value_options.key?(vod.id) vo = @value_options[vod.id] if vo.array? vo.map!{|o| yield vod.id, vod.type, o} else @value_options[vod.id] = yield vod.id, vod.type, vo end end end end ## # def visit_attr(&block) if block.arity == 2 yield self, value else yield self end end ## # This can only be called after the value has had its final value set as it gives raw access to value. # def raw_value @value end ## # This can only be called after the value has had its final value set as it gives raw access to value. # def map_value! @value = yield(@value) end ## # def process_flags # Nothing yet end end ## # class JabaAttributeSingle < JabaAttributeElement ## # def initialize(attr_def, node) super(attr_def, node, self) if attr_def.default_set? && !@default_block set(attr_def.default, call_on_set: false) end end ## # def do_describe "'#{@node.defn_id}.#{@attr_def.defn_id}' attribute" end ## # If attribute's default value was specified as a block it is executed here, after the node has been created, since # default blocks can be implemented in terms of other attributes. If the user has already supplied a value then the # default block will not be executed. # def finalise return if !@default_block || @set val = services.execute_attr_default_block(@node, @default_block) set(val) end ## # Returns the value of the attribute. If value is a reference to a JabaNode and the call to value() came from user # definitions then return the node's attributes rather than the node itself. # def value(jdl_call_loc = nil) @last_call_location = jdl_call_loc if jdl_call_loc if !@set if @default_block val = services.execute_attr_default_block(@node, @default_block) @attr_def.jaba_attr_type.map_value(val) elsif services.in_attr_default_block? attr_error("Cannot read uninitialised #{describe} - it might need a default value") else nil end elsif jdl_call_loc && @value.is_a?(JabaNode) # Pass on jdl call location to the read only attribute accessor to enable value calls to be chained. This happens # if a node-by-value attribute is nested, eg root_attr.sub_attr1.sub_attr2. # @value.attrs_read_only.__internal_set_jdl_call_loc(jdl_call_loc) else @value end end ## # TODO: re-examine def clear if attr_def.default_set? && !@default_block @value = attr_def.default else @value = nil end end end end
26.117225
166
0.604195
e9a5120b6cae4b656301c61beb347eb53e7a57b5
297
# -*- coding: utf-8 -*- # http://dxruby.sourceforge.jp/DXRubyReference/2009531233720546.htm require 'dxruby' image = Image.load('data.png') # data.pngを読み込む Window.loop do x = Input.mousePosX # マウスカーソルのx座標 y = Input.mousePosY # マウスカーソルのy座標 Window.draw(x, y, image) # data.pngを描画する end
22.846154
67
0.703704
ab9ee66519bf68c27a065dd91285419ed9eb7c1a
133
module Constants::MessageStyle module Color EPISODE_NO = '#e3a368' URL_LINK = '#325b85' SEPARATOR = '#888888' end end
19
30
0.669173
61db644a3721921207e538f0955abd6cace8698d
875
# frozen_string_literal: true require 'spec_helper' RSpec.describe BulkImports::Groups::Graphql::GetLabelsQuery do it 'has a valid query' do tracker = create(:bulk_import_tracker) context = BulkImports::Pipeline::Context.new(tracker) query = GraphQL::Query.new( GitlabSchema, described_class.to_s, variables: described_class.variables(context) ) result = GitlabSchema.static_validator.validate(query) expect(result[:errors]).to be_empty end describe '#data_path' do it 'returns data path' do expected = %w[data group labels nodes] expect(described_class.data_path).to eq(expected) end end describe '#page_info_path' do it 'returns pagination information path' do expected = %w[data group labels page_info] expect(described_class.page_info_path).to eq(expected) end end end
24.305556
62
0.710857
f738bd2538ff54b9f3912ce881ae4412bcc10db8
1,237
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module DropHunter class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.autoload_paths += Dir["#{config.root}/lib/**/"] config.assets.precompile += %w( bootstrap-material.css ) config.active_record.raise_in_transactional_callbacks = true end end
42.655172
99
0.726758
ffe5cef54cafb32a32296823a91108aebbfda6c7
83
# frozen_string_literal: true module StoreModel # :nodoc: VERSION = "0.8.1" end
13.833333
29
0.710843
1cc4cab8ac45ad57312519e8125bd5e3c0865a29
3,378
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you 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 'test_helper' class Elastic::Transport::ClientIntegrationTest < Minitest::Test context "Transport" do setup do begin; Object.send(:remove_const, :Patron); rescue NameError; end uri = URI(HOST) @host = { host: uri.host, port: uri.port, user: uri.user, password: uri.password } end should "allow to customize the Faraday adapter to Typhoeus" do require 'typhoeus' require 'typhoeus/adapters/faraday' transport = Elastic::Transport::Transport::HTTP::Faraday.new(hosts: [@host]) do |f| f.response :logger f.adapter :typhoeus end client = Elastic::Transport::Client.new(transport: transport) client.perform_request 'GET', '' end unless jruby? should "allow to customize the Faraday adapter to NetHttpPersistent" do require 'net/http/persistent' transport = Elastic::Transport::Transport::HTTP::Faraday.new(hosts: [@host]) do |f| f.response :logger f.adapter :net_http_persistent end client = Elastic::Transport::Client.new(transport: transport) client.perform_request 'GET', '' end should "allow to define connection parameters and pass them" do transport = Elastic::Transport::Transport::HTTP::Faraday.new( hosts: [@host], options: { transport_options: { params: { format: 'yaml' } } } ) client = Elastic::Transport::Client.new transport: transport response = client.perform_request 'GET', '' assert response.body.start_with?("---\n"), "Response body should be YAML: #{response.body.inspect}" end should "use the Curb client" do require 'curb' require 'elastic/transport/transport/http/curb' transport = Elastic::Transport::Transport::HTTP::Curb.new(hosts: [@host]) do |curl| curl.verbose = true end client = Elastic::Transport::Client.new(transport: transport) client.perform_request 'GET', '' end unless JRUBY should "deserialize JSON responses in the Curb client" do require 'curb' require 'elastic/transport/transport/http/curb' transport = Elastic::Transport::Transport::HTTP::Curb.new(hosts: [@host]) do |curl| curl.verbose = true end client = Elastic::Transport::Client.new(transport: transport) response = client.perform_request 'GET', '' assert_respond_to(response.body, :to_hash) assert_not_nil response.body['name'] assert_equal 'application/json', response.headers['content-type'] end unless jruby? end end
34.121212
105
0.681172
6a6b9ad5314617771b6d50afbc3164b4889fb6c8
1,978
require 'spec_helper' describe "cms_import_with_upload_policy", type: :feature, dbscope: :example, js: true do subject(:site) { cms_site } subject(:index_path) { cms_import_path site.id } let!(:file) { "#{Rails.root}/spec/fixtures/cms/import/site.zip" } let!(:name) { File.basename(file, ".*") } let!(:now) { Time.zone.now.beginning_of_minute } let!(:job_wait) { 1.year.since.to_f } before { login_cms_user } before { upload_policy_before_settings("sanitizer") } after { upload_policy_after_settings } context "sanitizer settings" do context "import_date is presnet" do it do visit index_path # upload expectation = expect do within "form#task-form" do attach_file "item[in_file]", file fill_in 'item[import_date]', with: I18n.l(now, format: :long) click_button I18n.t('ss.buttons.import') end end expectation.to have_enqueued_job(Cms::ImportFilesJob) enqueued_jobs.first.tap do |enqueued_job| expect(enqueued_job[:at]).to be > job_wait end # sanitize job_file = Cms::ImportJobFile.first restored_file = mock_sanitizer_restore(job_file.files[0]) expect(Fs.exist?(restored_file)).to be_truthy end end context "import_date is empty" do it do visit index_path # upload expectation = expect do within "form#task-form" do attach_file "item[in_file]", file click_button I18n.t('ss.buttons.import') end end expectation.to have_enqueued_job(Cms::ImportFilesJob) enqueued_jobs.first.tap do |enqueued_job| expect(enqueued_job[:at]).to be > job_wait end # sanitize job_file = Cms::ImportJobFile.first restored_file = mock_sanitizer_restore(job_file.files[0]) expect(Fs.exist?(restored_file)).to be_truthy end end end end
29.969697
88
0.631951
bfab97cf1e25bc1233081f24d5f734b3d269ab0b
9,497
require 'abstract_unit' require 'fileutils' require 'action_view/dependency_tracker' class FixtureTemplate attr_reader :source, :handler def initialize(template_path) @source = File.read(template_path) @handler = ActionView::Template.handler_for_extension(:erb) rescue Errno::ENOENT raise ActionView::MissingTemplate.new([], "", [], true, []) end end class FixtureFinder < ActionView::LookupContext FIXTURES_DIR = "#{File.dirname(__FILE__)}/../fixtures/digestor" def initialize(details = {}) super(ActionView::PathSet.new(['digestor']), details, []) end end class TemplateDigestorTest < ActionView::TestCase def setup @cwd = Dir.pwd @tmp_dir = Dir.mktmpdir FileUtils.cp_r FixtureFinder::FIXTURES_DIR, @tmp_dir Dir.chdir @tmp_dir end def teardown Dir.chdir @cwd FileUtils.rm_r @tmp_dir ActionView::Digestor.cache.clear end def test_top_level_change_reflected assert_digest_difference("messages/show") do change_template("messages/show") end end def test_explicit_dependency assert_digest_difference("messages/show") do change_template("messages/_message") end end def test_explicit_dependency_in_multiline_erb_tag assert_digest_difference("messages/show") do change_template("messages/_form") end end def test_explicit_dependency_wildcard assert_digest_difference("events/index") do change_template("events/_completed") end end def test_explicit_dependency_wildcard_picks_up_added_file old_caching, ActionView::Resolver.caching = ActionView::Resolver.caching, false assert_digest_difference("events/index") do add_template("events/_uncompleted") end ensure remove_template("events/_uncompleted") ActionView::Resolver.caching = old_caching end def test_explicit_dependency_wildcard_picks_up_removed_file old_caching, ActionView::Resolver.caching = ActionView::Resolver.caching, false add_template("events/_subscribers_changed") assert_digest_difference("events/index") do remove_template("events/_subscribers_changed") end ensure ActionView::Resolver.caching = old_caching end def test_second_level_dependency assert_digest_difference("messages/show") do change_template("comments/_comments") end end def test_second_level_dependency_within_same_directory assert_digest_difference("messages/show") do change_template("messages/_header") end end def test_third_level_dependency assert_digest_difference("messages/show") do change_template("comments/_comment") end end def test_directory_depth_dependency assert_digest_difference("level/below/index") do change_template("level/below/_header") end end def test_logging_of_missing_template assert_logged "Couldn't find template for digesting: messages/something_missing" do digest("messages/show") end end def test_logging_of_missing_template_ending_with_number assert_logged "Couldn't find template for digesting: messages/something_missing_1" do digest("messages/show") end end def test_logging_of_missing_template_for_dependencies assert_logged "'messages/something_missing' file doesn't exist, so no dependencies" do dependencies("messages/something_missing") end end def test_logging_of_missing_template_for_nested_dependencies assert_logged "'messages/something_missing' file doesn't exist, so no dependencies" do nested_dependencies("messages/something_missing") end end def test_nested_template_directory assert_digest_difference("messages/show") do change_template("messages/actions/_move") end end def test_recursion_in_renders assert digest("level/recursion") # assert recursion is possible assert_not_nil digest("level/recursion") # assert digest is stored end def test_chaining_the_top_template_on_recursion assert digest("level/recursion") # assert recursion is possible assert_digest_difference("level/recursion") do change_template("level/recursion") end assert_not_nil digest("level/recursion") # assert digest is stored end def test_chaining_the_partial_template_on_recursion assert digest("level/recursion") # assert recursion is possible assert_digest_difference("level/recursion") do change_template("level/_recursion") end assert_not_nil digest("level/recursion") # assert digest is stored end def test_dont_generate_a_digest_for_missing_templates assert_equal '', digest("nothing/there") end def test_collection_dependency assert_digest_difference("messages/index") do change_template("messages/_message") end assert_digest_difference("messages/index") do change_template("events/_event") end end def test_collection_derived_from_record_dependency assert_digest_difference("messages/show") do change_template("events/_event") end end def test_details_are_included_in_cache_key # Cache the template digest. @finder = FixtureFinder.new({:formats => [:html]}) old_digest = digest("events/_event") # Change the template; the cached digest remains unchanged. change_template("events/_event") # The details are changed, so a new cache key is generated. @finder = FixtureFinder.new # The cache is busted. assert_not_equal old_digest, digest("events/_event") end def test_extra_whitespace_in_render_partial assert_digest_difference("messages/edit") do change_template("messages/_form") end end def test_extra_whitespace_in_render_named_partial assert_digest_difference("messages/edit") do change_template("messages/_header") end end def test_extra_whitespace_in_render_record assert_digest_difference("messages/edit") do change_template("messages/_message") end end def test_extra_whitespace_in_render_with_parenthesis assert_digest_difference("messages/edit") do change_template("events/_event") end end def test_old_style_hash_in_render_invocation assert_digest_difference("messages/edit") do change_template("comments/_comment") end end def test_variants assert_digest_difference("messages/new", variants: [:iphone]) do change_template("messages/new", :iphone) change_template("messages/_header", :iphone) end end def test_dependencies_via_options_results_in_different_digest digest_plain = digest("comments/_comment") digest_fridge = digest("comments/_comment", dependencies: ["fridge"]) digest_phone = digest("comments/_comment", dependencies: ["phone"]) digest_fridge_phone = digest("comments/_comment", dependencies: ["fridge", "phone"]) assert_not_equal digest_plain, digest_fridge assert_not_equal digest_plain, digest_phone assert_not_equal digest_plain, digest_fridge_phone assert_not_equal digest_fridge, digest_phone assert_not_equal digest_fridge, digest_fridge_phone assert_not_equal digest_phone, digest_fridge_phone end def test_digest_cache_cleanup_with_recursion first_digest = digest("level/_recursion") second_digest = digest("level/_recursion") assert first_digest # If the cache is cleaned up correctly, subsequent digests should return the same assert_equal first_digest, second_digest end def test_digest_cache_cleanup_with_recursion_and_template_caching_off resolver_before = ActionView::Resolver.caching ActionView::Resolver.caching = false first_digest = digest("level/_recursion") second_digest = digest("level/_recursion") assert first_digest # If the cache is cleaned up correctly, subsequent digests should return the same assert_equal first_digest, second_digest ensure ActionView::Resolver.caching = resolver_before end private def assert_logged(message) old_logger = ActionView::Base.logger log = StringIO.new ActionView::Base.logger = Logger.new(log) begin yield log.rewind assert_match message, log.read ensure ActionView::Base.logger = old_logger end end def assert_digest_difference(template_name, options = {}) previous_digest = digest(template_name, options) ActionView::Digestor.cache.clear yield assert_not_equal previous_digest, digest(template_name, options), "digest didn't change" ActionView::Digestor.cache.clear end def digest(template_name, options = {}) options = options.dup finder.variants = options.delete(:variants) || [] ActionView::Digestor.digest({ name: template_name, finder: finder }.merge(options)) end def dependencies(template_name) ActionView::Digestor.new(template_name, finder).dependencies end def nested_dependencies(template_name) ActionView::Digestor.new(template_name, finder).nested_dependencies end def finder @finder ||= FixtureFinder.new end def change_template(template_name, variant = nil) variant = "+#{variant}" if variant.present? File.open("digestor/#{template_name}.html#{variant}.erb", "w") do |f| f.write "\nTHIS WAS CHANGED!" end end alias_method :add_template, :change_template def remove_template(template_name) File.delete("digestor/#{template_name}.html.erb") end end
28.349254
94
0.741813
f7b655e381f18e1ba49c58179a1ff93b26e8465b
1,107
# frozen_string_literal: true require 'support/shared_examples_for_rules' require 'support/shared_examples_for_adjective_rules' require 'support/shared_examples_for_from_now_adjective_for_rules' require 'support/shared_examples_for_rule_apply' require 'support/shared_examples_for_unit_rules' require 'test_dates' RSpec.describe Expire::FromNowKeepMonthlyForRule do subject { described_class.new(amount: 2, unit: 'years') } it_behaves_like 'a rule' do let(:name) { 'from_now_keep_monthly_for' } let(:option_name) { '--from-now-keep-monthly-for' } let(:rank) { 44 } end it_behaves_like 'an adjective rule' do let(:adjective) { 'monthly' } let(:spacing) { 'month' } end it_behaves_like 'an from now adjective-for rule' it_behaves_like 'an #apply on a rule' do let(:backups) do TestDates.create(years: 1858..1860, months: 4..5).to_backups end let(:kept) do TestDates.create(years: 1859..1860, months: 4..5).to_backups end let(:reference_time) { Time.new(1861, 4, 1, 12, 0, 0) } end it_behaves_like 'an unit rule' end
27.675
66
0.715447
395840750216c74bbe6d56ec7d6169a04232ef6a
87
class MiqGroupDecorator < MiqDecorator def self.fonticon 'ff ff-group' end end
14.5
38
0.735632
21385ea5b06640a2e40af3c498571e60d7602873
3,172
require "spec_helper" describe "Using Capybara::Screenshot with MiniTest" do include CommonSetup before do clean_current_dir end def run_failing_case(code) write_file('test_failure.rb', <<-RUBY) #{ensure_load_paths_valid} require 'minitest/autorun' require 'capybara' require 'capybara-screenshot' require 'capybara-screenshot/minitest' #{setup_test_app} Capybara::Screenshot.register_filename_prefix_formatter(:minitest) do |test_case| test_name = test_case.respond_to?(:name) ? test_case.name : test_case.__name__ raise "expected fault" unless test_name.include? 'test_failure' 'my_screenshot' end #{code} RUBY cmd = 'bundle exec ruby test_failure.rb' run_simple_with_retry cmd, false expect(output_from(cmd)).to include %q{Unable to find link or button "you'll never find me"} end it 'saves a screenshot on failure' do run_failing_case <<-RUBY module ActionDispatch class IntegrationTest < Minitest::Unit::TestCase; end end class TestFailure < ActionDispatch::IntegrationTest include Capybara::DSL def test_failure visit '/' assert(page.body.include?('This is the root page')) click_on "you'll never find me" end end RUBY check_file_content 'tmp/my_screenshot.html', 'This is the root page', true end it "does not save a screenshot for tests that don't inherit from ActionDispatch::IntegrationTest" do run_failing_case <<-RUBY class TestFailure < MiniTest::Unit::TestCase include Capybara::DSL def test_failure visit '/' assert(page.body.include?('This is the root page')) click_on "you'll never find me" end end RUBY check_file_presence(%w{tmp/my_screenshot.html}, false) end it 'saves a screenshot for the correct session for failures using_session' do run_failing_case <<-RUBY module ActionDispatch class IntegrationTest < Minitest::Unit::TestCase; end end class TestFailure < ActionDispatch::IntegrationTest include Capybara::DSL def test_failure visit '/' assert(page.body.include?('This is the root page')) using_session :different_session do visit '/different_page' assert(page.body.include?('This is a different page')) click_on "you'll never find me" end end end RUBY check_file_content 'tmp/my_screenshot.html', 'This is a different page', true end it 'prunes screenshots on failure' do create_screenshot_for_pruning configure_prune_strategy :last_run run_failing_case <<-RUBY module ActionDispatch class IntegrationTest < Minitest::Unit::TestCase; end end class TestFailure < ActionDispatch::IntegrationTest include Capybara::DSL def test_failure visit '/' assert(page.body.include?('This is the root page')) click_on "you'll never find me" end end RUBY assert_screenshot_pruned end end
28.576577
102
0.658575
e2ebf06122f6f263109013236f582b738ff1c603
262
module Washington class Failure attr_reader :message, :function, :original, :error def initialize message, function, original, error @message = message @function = function @original = original @error = error end end end
20.153846
54
0.660305
d55c9eff4cb8c13db5f66ce15309142db9d00273
3,856
require_relative "../test_helper" describe Elastomer::Client::Scroller do before do @name = "elastomer-scroller-test" @index = $client.index(@name) unless @index.exists? @index.create \ :settings => { "index.number_of_shards" => 1, "index.number_of_replicas" => 0 }, :mappings => { :tweet => { :_source => { :enabled => true }, :_all => { :enabled => false }, :properties => { :message => $client.version_support.text(analyzer: "standard"), :author => $client.version_support.keyword, :sorter => { :type => "integer" } } }, :book => { :_source => { :enabled => true }, :_all => { :enabled => false }, :properties => { :title => $client.version_support.text(analyzer: "standard"), :author => $client.version_support.keyword, :sorter => { :type => "integer" } } } } wait_for_index(@name) populate! end end after do @index.delete if @index.exists? end it "scans over all documents in an index" do scan = @index.scan '{"query":{"match_all":{}}}', :size => 10 counts = {"tweet" => 0, "book" => 0} scan.each_document { |h| counts[h["_type"]] += 1 } assert_equal 50, counts["tweet"] assert_equal 25, counts["book"] end it "restricts the scan to a single document type" do scan = @index.scan '{"query":{"match_all":{}}}', :type => "book" counts = {"tweet" => 0, "book" => 0} scan.each_document { |h| counts[h["_type"]] += 1 } assert_equal 0, counts["tweet"] assert_equal 25, counts["book"] end it "limits results by query" do scan = @index.scan :query => { :bool => { :should => [ {:match => {:author => "pea53"}}, {:match => {:title => "17"}} ]}} counts = {"tweet" => 0, "book" => 0} scan.each_document { |h| counts[h["_type"]] += 1 } assert_equal 50, counts["tweet"] assert_equal 1, counts["book"] end it "scrolls and sorts over all documents" do scroll = @index.scroll({ :query => {:match_all => {}}, :sort => {:sorter => {:order => :asc}} }, :type => "tweet") tweets = [] scroll.each_document { |h| tweets << h["_id"].to_i } expected = (0...50).to_a.reverse assert_equal expected, tweets end it "propagates URL query strings" do scan = @index.scan(nil, { :q => "author:pea53 || title:17" }) counts = {"tweet" => 0, "book" => 0} scan.each_document { |h| counts[h["_type"]] += 1 } assert_equal 50, counts["tweet"] assert_equal 1, counts["book"] end it "clears one or more scroll IDs" do h = $client.start_scroll \ body: {query: {match_all: {}}}, index: @index.name, type: "tweet", scroll: "1m", size: 10 refute_nil h["_scroll_id"], "response is missing a scroll ID" response = $client.clear_scroll(h["_scroll_id"]) if returns_cleared_scroll_id_info? assert response["succeeded"] assert_equal 1, response["num_freed"] else assert_empty response end end it "raises an exception on existing sort in query" do assert_raises(ArgumentError) { @index.scan :sort => [:_doc] , :query => {} } end def populate! h = @index.bulk do |b| 50.times { |num| b.index %Q({"author":"pea53","message":"this is tweet number #{num}","sorter":#{50-num}}), :_id => num, :_type => "tweet" } end h["items"].each {|item| assert_bulk_index(item) } h = @index.bulk do |b| 25.times { |num| b.index %Q({"author":"Pratchett","title":"DiscWorld Book #{num}","sorter":#{25-num}}), :_id => num, :_type => "book" } end h["items"].each {|item| assert_bulk_index(item) } @index.refresh end end
27.942029
129
0.548755
bf6bc58dcf042ade5dd69141e10c5e60283239e1
215
# config/initializers/recaptcha.rb if Settings.recaptcha.present? Recaptcha.configure do |config| config.site_key = Settings.recaptcha.site_key config.secret_key = Settings.recaptcha.secret_key end end
23.888889
53
0.786047
01a6da37808974cdac5429e026b25b3b5cbf9eeb
540
module Xcunique module Keys CHILDREN = 'children' FILE_REF = 'fileRef' FILES = 'files' ISA = 'isa' MAIN_GROUP = 'mainGroup' NAME = 'name' OBJECTS = 'objects' PATH = 'path' PBXGroup = 'PBXGroup' ROOT_OBJECT = 'rootObject' end end require "xcunique/cli" require 'xcunique/hash_ext' require 'xcunique/helpers' require "xcunique/options" require "xcunique/parser" require "xcunique/sorter" require "xcunique/uniquifier" require "xcunique/version"
22.5
31
0.624074
014078ec46e03843e97f7c36df50bc29c4df2a78
1,046
require 'rake' require 'pathname' require 'rake/clean' Dir.chdir Pathname.getwd() SOURCE_FILES = Rake::FileList.new("sources/**/*.md", "sources/**/*.markdown") do |fl| fl.exclude("**/~*") fl.exclude(/^sources\/scratch\//) fl.exclude do |f| `git ls-files #{f}`.empty? end end task :default => :gen_html # puts "SOURCE_FILES => #{SOURCE_FILES}" GEN_FILES = SOURCE_FILES.pathmap("%{^sources/,outputs/}X.html") # task :html_path => SOURCE_FILES.pathmap("%{^sources/,outputs/}X.html") OUT_FILES = Rake::FileList.new("outputs/**/**") do |fl| fl.exclude("~*") end OUT_HTML = OUT_FILES.ext(".html") CLEAN.include(OUT_HTML) # task :gen_html => GEN_FILES multitask :gen_html => GEN_FILES directory "outputs" rule ".html" => [->(f){source_for_html(f)}, "outputs"] do |t| # puts "do => t.name.pathmap(\"%d\") #{t.name.pathmap("%d")}" mkdir_p t.name.pathmap("%d") sh "pandoc -o #{t.name} #{t.source}" end def source_for_html(html_file) SOURCE_FILES.detect{|f| f.ext('') == html_file.pathmap("%{^outputs/,sources/}X") } end
24.904762
85
0.648184
08566bfe19c523b7cd536a0c5459594e2f6c9a3e
5,007
# # Be sure to run `pod spec lint SHMIDIKit.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |s| # ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # These will help people to find your library, and whilst it # can feel like a chore to fill in it's definitely to your advantage. The # summary should be tweet-length, and the description more in depth. # s.name = "SHMultiSlider" s.version = "0.3.1" s.summary = "[macOS] Knob with 2 sliders" # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC A multislider UI component for macOS, written in Swift 4.2 DESC s.homepage = "https://sonichits.studio/" # s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif" # ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Licensing your code is important. See http://choosealicense.com for more info. # CocoaPods will detect a license file if there is a named LICENSE* # Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'. # s.license = "MIT" # s.license = { :type => "MIT", :file => "FILE_LICENSE" } # ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Specify the authors of the library, with email addresses. Email addresses # of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also # accepts just a name if you'd rather not provide an email address. # # Specify a social_media_url where others can refer to, for example a twitter # profile URL. # s.author = { "Rex Wang" => "Sonic Hits Co" } # Or just: s.author = "Rexhits" # s.authors = { "Rexhits" => "" } # s.social_media_url = "http://twitter.com/Rexhits" # ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # If this Pod runs only on iOS or OS X, then specify the platform and # the deployment target. You can optionally include the target after the platform. # # s.platform = :ios # s.platform = :ios, "5.0" # When using multiple platforms s.osx.deployment_target = "10.11" # s.watchos.deployment_target = "2.0" # s.tvos.deployment_target = "9.0" # ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Specify the location from where the source should be retrieved. # Supports git, hg, bzr, svn and HTTP. # s.source = { :git => "https://github.com/Rexhits/SHMultiSlider.git", :tag => "#{s.version}" } # ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # CocoaPods is smart about how it includes source code. For source files # giving a folder will include any swift, h, m, mm, c & cpp files. # For header files it will include any header in the folder. # Not including the public_header_files will make all headers public. # s.source_files = "Sources/*.swift" s.swift_version = '4.2' # s.public_header_files = "Classes/**/*.h" # ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # A list of resources included with the Pod. These are copied into the # target bundle with a build phase script. Anything else will be cleaned. # You can preserve files from being cleaned, please don't preserve # non-essential files like tests, examples and documentation. # # s.resource = "icon.png" s.resources = "Resources/*.xib" # s.preserve_paths = "FilesToSave", "MoreFilesToSave" # ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Link your library with frameworks, or libraries. Libraries do not include # the lib prefix of their name. # # s.framework = "SomeFramework" # s.frameworks = "SomeFramework", "AnotherFramework" # s.library = "iconv" # s.libraries = "iconv", "xml2" # ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # If your library depends on compiler flags you can set them in the xcconfig hash # where they will only apply to your library. If you depend on other Podspecs # you can include multiple dependencies to ensure it works. # s.requires_arc = true # s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" } # s.dependency "JSONKit", "~> 1.4" end
36.282609
101
0.589774
b91599f04a1a57e372a2a829ba7e70ba9959c050
444
cask 'font-hanamina' do version '2017.09.04,68253' sha256 '571cd4a09ae7da0c642d640fc2442c050aa450ebb0587a95cdd097d41a9c9572' # osdn.dl.osdn.jp/hanazono-font was verified as official when first introduced to the cask url "https://osdn.dl.osdn.jp/hanazono-font/#{version.after_comma}/hanazono-#{version.before_comma.no_dots}.zip" name 'HanaMinA' homepage 'https://fonts.jp/hanazono/' font 'HanaMinA.ttf' font 'HanaMinB.ttf' end
34.153846
113
0.768018
bfa578a0741ac07374764890ec7c82f13c3d7ed8
36
AasmPlus::Engine.routes.draw do end
12
31
0.805556
1cd93cd5ec930366ba040d4c35d682e96c1e7e95
3,949
#!/usr/bin/env ruby # frozen_string_literal: true require 'erb' require_relative 'octokit_utils' require_relative 'options' options = parse_options parsed = load_url(options) util = OctokitUtils.new(options[:oauth]) open_prs = [] def does_array_have_pr(array, pr_number) found = false array.each do |entry| found = true if pr_number == entry.number end found end parsed.each do |_k, v| limit = util.client.rate_limit! puts "Getting data from Github API for #{v['github']}" if limit.remaining == 0 # sleep 60 #Sleep between requests to prevent Github API - 403 response sleep limit.resets_in puts 'Waiting for rate limit reset in Github API' end sleep 2 # Keep Github API happy pr_information_cache = util.fetch_async((v['github']).to_s) # no comment from a puppet employee puppet_uncommented_pulls = util.fetch_pull_requests_with_no_puppet_personnel_comments(pr_information_cache) # last comment mentions a puppet person mentioned_pulls = util.fetch_pull_requests_mention_member(pr_information_cache) # loop through open pr's and create a row that has all the pertinant info pr_information_cache.each do |pr| sleep(2) if pr[:pull][:draft] == false row = {} row[:repo] = v['title'] row[:address] = "https://github.com/#{v['github']}" row[:pr] = pr[:pull].number row[:age] = ((Time.now - pr[:pull].created_at) / 60 / 60 / 24).round row[:owner] = pr[:pull].user.login row[:owner] += " <span class='label label-primary'>iac</span>" if util.iac_member?(pr[:pull].user.login) row[:owner] += " <span class='label label-warning'>puppet</span>" if util.puppet_member?(pr[:pull].user.login) row[:owner] += " <span class='badge badge-secondary'>vox</span>" if util.voxpupuli_member?(pr[:pull].user.login) row[:title] = pr[:pull].title if !pr[:issue_comments].empty? if pr[:issue_comments].last.user.login =~ /\Acodecov/ begin row[:last_comment] = pr[:issue_comments].body(-2).gsub(%r{<\/?[^>]*>}, '') rescue StandardError row[:last_comment] = 'No previous comment other than codecov-io' row[:by] = '' end else row[:last_comment] = pr[:issue_comments].last.body.gsub(%r{<\/?[^>]*>}, '') row[:by] = pr[:issue_comments].last.user.login end row[:age_comment] = ((Time.now - pr[:issue_comments].last.updated_at) / 60 / 60 / 24).round else row[:last_comment] = '0 comments' row[:by] = '' row[:age_comment] = 0 end row[:num_comments] = pr[:issue_comments].size # find prs not commented by puppet row[:no_comment_from_puppet] = does_array_have_pr(puppet_uncommented_pulls, pr[:pull].number) # last comment mentions puppet member row[:last_comment_mentions_puppet] = does_array_have_pr(mentioned_pulls, pr[:pull].number) open_prs.push(row) end end end copy_open_prs = [] copy_open_prs = open_prs open_prs = copy_open_prs.select { |row| row[:age_comment] > 60 && row[:age_comment] < 90 } html60 = ERB.new(File.read('pr_review_list.html.erb')).result(binding) File.open('report60.html', 'wb') do |f| f.puts(html60) end open_prs = copy_open_prs.select { |row| row[:age_comment] > 30 && row[:age_comment] < 60 } html30 = ERB.new(File.read('pr_review_list.html.erb')).result(binding) File.open('report30.html', 'wb') do |f| f.puts(html30) end open_prs = copy_open_prs.select { |row| row[:age_comment] > 90 } html90 = ERB.new(File.read('pr_review_list.html.erb')).result(binding) File.open('report90.html', 'wb') do |f| f.puts(html90) end open_prs = copy_open_prs html = ERB.new(File.read('pr_review_list.html.erb')).result(binding) File.open('report.html', 'wb') do |f| f.puts(html) end File.open('report.json', 'wb') do |f| JSON.dump(open_prs, f) end
33.466102
120
0.651557
b92d2a51cbe6f3c12b33d4b6e1a1ab2801e8aa68
849
class PicardTools < Formula desc "Tools for manipulating HTS data and formats" homepage "https://broadinstitute.github.io/picard/" url "https://github.com/broadinstitute/picard/releases/download/2.23.3/picard.jar" sha256 "0eae556a8f925d0790d9df2c94b7df323a0107eecdd6ac45866c391921888f23" license "MIT" bottle :unneeded depends_on "openjdk" def install libexec.install "picard.jar" (bin/"picard").write <<~EOS #!/bin/bash exec "#{Formula["openjdk"].opt_bin}/java" $JAVA_OPTS -jar "#{libexec}/picard.jar" "$@" EOS end test do (testpath/"test.fasta").write <<~EOS >U00096.2:1-70 AGCTTTTCATTCTGACTGCAACGGGCAATATGTCT CTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC EOS cmd = "#{bin}/picard NormalizeFasta I=test.fasta O=/dev/stdout" assert_match "TCTCTG", shell_output(cmd) end end
28.3
92
0.707892
79059dcf23aafd6dc432ee5c1205ee825bb9b52f
1,541
require "formula" class Jenkins < Formula homepage "https://jenkins-ci.org" url "http://mirrors.jenkins-ci.org/war/1.598/jenkins.war" sha1 "ee3f94a2eab93a119baaa897a2fd0045cc401e73" head do url "https://github.com/jenkinsci/jenkins.git" depends_on "maven" => :build end depends_on :java => "1.6" def install if build.head? system "mvn", "clean", "install", "-pl", "war", "-am", "-DskipTests" else system "jar", "xvf", "jenkins.war" end libexec.install Dir["**/jenkins.war", "**/jenkins-cli.jar"] bin.write_jar_script libexec/"jenkins.war", "jenkins" bin.write_jar_script libexec/"jenkins-cli.jar", "jenkins-cli" end plist_options :manual => "jenkins" def plist; <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>/usr/bin/java</string> <string>-Dmail.smtp.starttls.enable=true</string> <string>-jar</string> <string>#{opt_libexec}/jenkins.war</string> <string>--httpListenAddress=127.0.0.1</string> <string>--httpPort=8080</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> EOS end def caveats; <<-EOS.undent Note: When using launchctl the port will be 8080. EOS end end
27.517857
106
0.609345
6a9f6c7e2b8ade393ab3449bf62b92903eea997d
3,173
require 'slack-notifier' module WorkerTools module SlackErrorNotifier def with_wrapper_slack_error_notifier(&block) block.yield rescue StandardError => e slack_error_notify(e) if slack_error_notifier_enabled raise end def slack_error_notifier_enabled Rails.env.production? end def slack_error_notifier_emoji ':red_circle:' end def slack_error_notifier_channel return SLACK_NOTIFIER_CHANNEL if defined?(SLACK_NOTIFIER_CHANNEL) raise 'Define slack_error_notifier_channel or set SLACK_NOTIFIER_CHANNEL in an initializer' end def slack_error_notifier_webhook return SLACK_NOTIFIER_WEBHOOK if defined?(SLACK_NOTIFIER_WEBHOOK) raise 'Define slack_error_notifier_webhook or set SLACK_NOTIFIER_WEBHOOK in an initializer' end def slack_error_notifier_username 'Notifier' end def slack_error_notifier_receivers # Ex: '@all' end def slack_error_notifier_attachments_color # good, warning, danger, hex color 'danger' end def slack_error_notifier_title # Example with a link: # # For urls a default_url_options[:host] might be necessary. # In this example I just copy it from existing action_mailer defaults. # # import = slack_error_notifier_model # host = Rails.application.config.action_mailer.default_url_options[:host] # url = Rails.application.routes.url_helpers.import_url(import, host: host, protocol: :https) # kind = I18n.t(import.kind, scope: 'import.kinds') # text = "##{import.id} *#{kind}*" # "[#{text}](#{url})" klass = model.class.model_name.human kind = I18n.t("activerecord.attributes.#{model.class.name.underscore}.kinds.#{model.kind}") "#{klass} #{kind} ##{model.id}" end def slack_error_notifier_error_details(error) error.backtrace[0..2].join("\n") end def slack_error_notifier_message message = [] message << slack_error_notifier_receivers message << slack_error_notifier_title message.compact.join(' - ') end def slack_error_notifier_attachments(error) [ { color: slack_error_notifier_attachments_color, fields: slack_error_notifier_attachments_fields }, { title: [error.class, error.message].join(' : '), color: slack_error_notifier_attachments_color, text: slack_error_notifier_error_details(error) } ] end def slack_error_notifier_attachments_fields [ { title: 'Application', value: Rails.application.class.module_parent_name, short: true }, { title: 'Environment', value: Rails.env, short: true } ] end def slack_error_notifier Slack::Notifier.new(slack_error_notifier_webhook) end def slack_error_notify(error) slack_error_notifier.post( username: slack_error_notifier_username, channel: slack_error_notifier_channel, icon_emoji: slack_error_notifier_emoji, text: "*#{slack_error_notifier_message}*", attachments: slack_error_notifier_attachments(error) ) end end end
29.933962
107
0.691459
39ba8c35b7cefb4366c9991a24146a0e9bd4f16c
5,983
require 'vcap/services/api' require 'controllers/services/lifecycle/service_instance_binding_manager' require 'models/helpers/process_types' require 'actions/services/service_binding_read' module VCAP::CloudController class ServiceBindingsController < RestController::ModelController define_attributes do to_one :app, association_controller: :AppsController, association_name: :v2_app to_one :service_instance attribute :binding_options, Hash, exclude_in: [:create, :update] attribute :parameters, Hash, default: nil attribute :name, String, default: nil end get path, :enumerate query_parameters :app_guid, :name, :service_instance_guid get path_guid, :read def read(guid) obj = find_guid(guid) raise CloudController::Errors::ApiError.new_from_details('ServiceBindingNotFound', guid) unless obj.v2_app.present? validate_access(:read, obj) object_renderer.render_json(self.class, obj, @opts) end post path, :create def create @request_attrs = self.class::CreateMessage.decode(body).extract(stringify_keys: true) logger.debug 'cc.create', model: self.class.model_class_name, attributes: request_attrs raise InvalidRequest unless request_attrs message = ServiceBindingCreateMessage.new({ type: 'app', name: request_attrs['name'], relationships: { app: { data: { guid: request_attrs['app_guid'] } }, service_instance: { data: { guid: request_attrs['service_instance_guid'] } }, }, data: { parameters: request_attrs['parameters'] } }) accepts_incomplete = convert_flag_to_bool(params['accepts_incomplete']) app, service_instance = ServiceBindingCreateFetcher.new.fetch(message.app_guid, message.service_instance_guid) raise CloudController::Errors::ApiError.new_from_details('AppNotFound', @request_attrs['app_guid']) unless app raise CloudController::Errors::ApiError.new_from_details('ServiceInstanceNotFound', @request_attrs['service_instance_guid']) unless service_instance raise CloudController::Errors::ApiError.new_from_details('NotAuthorized') unless Permissions.new(SecurityContext.current_user).can_write_to_space?(app.space_guid) creator = ServiceBindingCreate.new(UserAuditInfo.from_context(SecurityContext)) service_binding = creator.create(app, service_instance, message, volume_services_enabled?, accepts_incomplete) warn_if_user_provided_service_has_parameters!(service_instance) [ status_from_operation_state(service_binding.last_operation), { 'Location' => "#{self.class.path}/#{service_binding.guid}" }, object_renderer.render_json(self.class, service_binding, @opts) ] rescue ServiceBindingCreate::ServiceInstanceNotBindable raise CloudController::Errors::ApiError.new_from_details('UnbindableService') rescue ServiceBindingCreate::VolumeMountServiceDisabled raise CloudController::Errors::ApiError.new_from_details('VolumeMountServiceDisabled') rescue ServiceBindingCreate::ServiceBrokerInvalidBindingsRetrievable raise CloudController::Errors::ApiError.new_from_details('ServiceBindingInvalid', 'Could not create asynchronous binding when bindings_retrievable is false.') rescue ServiceBindingCreate::ServiceBrokerRespondedAsyncWhenNotAllowed raise CloudController::Errors::ApiError.new_from_details('ServiceBrokerRespondedAsyncWhenNotAllowed') rescue ServiceBindingCreate::InvalidServiceBinding => e raise CloudController::Errors::ApiError.new_from_details('ServiceBindingAppServiceTaken', e.message) end delete path_guid, :delete def delete(guid) binding = ServiceBinding.find(guid: guid) raise CloudController::Errors::ApiError.new_from_details('ServiceBindingNotFound', guid) unless binding raise CloudController::Errors::ApiError.new_from_details('NotAuthorized') unless Permissions.new(SecurityContext.current_user).can_write_to_space?(binding.space.guid) deleter = ServiceBindingDelete.new(UserAuditInfo.from_context(SecurityContext)) if async? job = deleter.single_delete_async(binding) [HTTP::ACCEPTED, JobPresenter.new(job).to_json] else deleter.single_delete_sync(binding) [HTTP::NO_CONTENT, nil] end end get '/v2/service_bindings/:guid/parameters', :parameters def parameters(guid) binding = find_guid_and_validate_access(:read, guid) raise CloudController::Errors::ApiError.new_from_details('ServiceBindingNotFound', guid) unless binding.v2_app.present? fetcher = ServiceBindingRead.new begin parameters = fetcher.fetch_parameters(binding) [HTTP::OK, parameters.to_json] rescue ServiceBindingRead::NotSupportedError raise CloudController::Errors::ApiError.new_from_details('ServiceFetchBindingParametersNotSupported') end end def self.translate_validation_exception(e, _attributes) CloudController::Errors::ApiError.new_from_details('ServiceBindingInvalid', e.errors.full_messages) end define_messages private def filter_dataset(dataset) dataset.select_all(ServiceBinding.table_name).join(ProcessModel.table_name, app_guid: :app_guid, type: ProcessTypes::WEB) end def volume_services_enabled? @config.get(:volume_services_enabled) end def warn_if_user_provided_service_has_parameters!(service_instance) if service_instance.user_provided_instance? && @request_attrs['parameters'] && @request_attrs['parameters'].any? add_warning('Configuration parameters are ignored for bindings to user-provided service instances.') end end def status_from_operation_state(last_operation) if last_operation&.state == 'in progress' HTTP::ACCEPTED else HTTP::CREATED end end end end
41.839161
172
0.74344
113f5b43c4ecf16c4fb56a3ed802d1fa79dab45b
1,406
require "webrat/selenium/application_servers/base" module Webrat module Selenium module ApplicationServers class Rack < Webrat::Selenium::ApplicationServers::Base def start @pid = fork do if File.exist?("log") redirect_io(STDOUT, File.join("log", "webrat.webrick.stdout.log")) redirect_io(STDERR, File.join("log", "webrat.webrick.stderr.log")) end exec start_command end end def stop Process.kill("INT", @pid) end def fail $stderr.puts $stderr.puts $stderr.puts "==> Failed to boot the application server... exiting!" $stderr.puts $stderr.puts "Verify you can start a server on port #{Webrat.configuration.application_port} with the following command:" $stderr.puts $stderr.puts " #{start_command}" exit end def start_command "#{bundler} rackup -s webrick --port #{Webrat.configuration.application_port} --env #{Webrat.configuration.application_environment}".strip end private def bundler File.exist?("./Gemfile") ? "bundle exec " : "" end def redirect_io(io, path) File.open(path, 'ab') { |fp| io.reopen(fp) } if path io.sync = true end end end end end
27.038462
148
0.568279
036bba7c5bef7ff44a59ea4f6a27f34f5d0c92b0
822
# -*- coding: binary -*- module Rex module Crypto # Returns an encrypted string using AES256-CBC. # # @param iv [String] Initialization vector. # @param key [String] Secret key. # @return [String] The encrypted string. def self.encrypt_aes256(iv, key, value) aes = OpenSSL::Cipher::AES256.new(:CBC) aes.encrypt aes.iv = iv aes.key = key aes.update(value) + aes.final end # Returns a decrypted string using AES256-CBC. # # @param iv [String] Initialization vector. # @param key [String] Secret key. # @return [String] The decrypted string. def self.decrypt_aes256(iv, key, value) aes = OpenSSL::Cipher::AES256.new(:CBC) aes.decrypt aes.iv = iv aes.key = key aes.update(value) + aes.final end end end
24.909091
51
0.615572
4afe36b3986247319b528907d56406eb657bc84a
24,334
require 'set' require 'savon' require 'netsuite/version' require 'netsuite/errors' require 'netsuite/utilities' require 'netsuite/utilities/data_center' require 'netsuite/rest/utilities/roles' require 'netsuite/rest/utilities/request' require 'netsuite/core_ext/string/lower_camelcase' module NetSuite autoload :Configuration, 'netsuite/configuration' autoload :Response, 'netsuite/response' module Namespaces autoload :ActSched, 'netsuite/namespaces/act_sched' autoload :FileCabinet, 'netsuite/namespaces/file_cabinet' autoload :ListAcct, 'netsuite/namespaces/list_acct' autoload :ListRel, 'netsuite/namespaces/list_rel' autoload :ListSupport, 'netsuite/namespaces/list_support' autoload :ListWebsite, 'netsuite/namespaces/list_website' autoload :PlatformCommon, 'netsuite/namespaces/platform_common' autoload :PlatformCore, 'netsuite/namespaces/platform_core' autoload :TranBank, 'netsuite/namespaces/tran_bank' autoload :TranCust, 'netsuite/namespaces/tran_cust' autoload :TranEmp, 'netsuite/namespaces/tran_emp' autoload :TranGeneral, 'netsuite/namespaces/tran_general' autoload :CommGeneral, 'netsuite/namespaces/comm_general' autoload :TranInvt, 'netsuite/namespaces/tran_invt' autoload :TranSales, 'netsuite/namespaces/tran_sales' autoload :TranPurch, 'netsuite/namespaces/tran_purch' autoload :SetupCustom, 'netsuite/namespaces/setup_custom' autoload :ListEmp, 'netsuite/namespaces/list_emp' autoload :ListMkt, 'netsuite/namespaces/list_mkt' end module Support autoload :Actions, 'netsuite/support/actions' autoload :Attributes, 'netsuite/support/attributes' autoload :Fields, 'netsuite/support/fields' autoload :Sublist, 'netsuite/support/sublist' autoload :RecordRefs, 'netsuite/support/record_refs' autoload :Records, 'netsuite/support/records' autoload :Requests, 'netsuite/support/requests' autoload :SearchResult, 'netsuite/support/search_result' autoload :Country, 'netsuite/support/country' end module Actions autoload :Add, 'netsuite/actions/add' autoload :Delete, 'netsuite/actions/delete' autoload :DeleteList, 'netsuite/actions/delete_list' autoload :Get, 'netsuite/actions/get' autoload :GetDeleted, 'netsuite/actions/get_deleted' autoload :GetAll, 'netsuite/actions/get_all' autoload :GetList, 'netsuite/actions/get_list' autoload :GetSelectValue, 'netsuite/actions/get_select_value' autoload :Initialize, 'netsuite/actions/initialize' autoload :Update, 'netsuite/actions/update' autoload :UpdateList, 'netsuite/actions/update_list' autoload :Upsert, 'netsuite/actions/upsert' autoload :UpsertList, 'netsuite/actions/upsert_list' autoload :Search, 'netsuite/actions/search' autoload :Login, 'netsuite/actions/login' end module Records autoload :AssemblyItem, 'netsuite/records/assembly_item' autoload :AssemblyBuild, 'netsuite/records/assembly_build' autoload :AssemblyComponent, 'netsuite/records/assembly_component' autoload :AssemblyComponentList, 'netsuite/records/assembly_component_list' autoload :AssemblyUnbuild, 'netsuite/records/assembly_unbuild' autoload :Account, 'netsuite/records/account' autoload :AccountingPeriod, 'netsuite/records/accounting_period' autoload :Address, 'netsuite/records/address' autoload :BaseRefList, 'netsuite/records/base_ref_list' autoload :BillAddress, 'netsuite/records/bill_address' autoload :BillingSchedule, 'netsuite/records/billing_schedule' autoload :BillingScheduleMilestone, 'netsuite/records/billing_schedule_milestone' autoload :BillingScheduleMilestoneList, 'netsuite/records/billing_schedule_milestone_list' autoload :BillingScheduleRecurrence, 'netsuite/records/billing_schedule_recurrence' autoload :BillingScheduleRecurrenceList, 'netsuite/records/billing_schedule_recurrence_list' autoload :Bin, 'netsuite/records/bin' autoload :BinNumber, 'netsuite/records/bin_number' autoload :BinNumberList, 'netsuite/records/bin_number_list' autoload :BinTransfer, 'netsuite/records/bin_transfer' autoload :BinTransferInventory, 'netsuite/records/bin_transfer_inventory' autoload :BinTransferInventoryList, 'netsuite/records/bin_transfer_inventory_list' autoload :CashSale, 'netsuite/records/cash_sale' autoload :CashSaleItem, 'netsuite/records/cash_sale_item' autoload :CashSaleItemList, 'netsuite/records/cash_sale_item_list' autoload :CashRefund, 'netsuite/records/cash_refund' autoload :CashRefundItem, 'netsuite/records/cash_refund_item' autoload :CashRefundItemList, 'netsuite/records/cash_refund_item_list' autoload :Campaign, 'netsuite/records/campaign' autoload :Classification, 'netsuite/records/classification' autoload :CostCategory, 'netsuite/records/cost_category' autoload :CreditMemo, 'netsuite/records/credit_memo' autoload :CreditMemoApply, 'netsuite/records/credit_memo_apply' autoload :CreditMemoApplyList, 'netsuite/records/credit_memo_apply_list' autoload :CreditMemoItem, 'netsuite/records/credit_memo_item' autoload :CreditMemoItemList, 'netsuite/records/credit_memo_item_list' autoload :CustomField, 'netsuite/records/custom_field' autoload :CustomFieldList, 'netsuite/records/custom_field_list' autoload :CustomList, 'netsuite/records/custom_list' autoload :CustomRecord, 'netsuite/records/custom_record' autoload :CustomRecordRef, 'netsuite/records/custom_record_ref' autoload :CustomRecordType, 'netsuite/records/custom_record_type' autoload :CustomListCustomValue, 'netsuite/records/custom_list_custom_value' autoload :CustomListCustomValueList, 'netsuite/records/custom_list_custom_value_list' autoload :Customer, 'netsuite/records/customer' autoload :CustomerAddressbook, 'netsuite/records/customer_addressbook' autoload :CustomerAddressbookList, 'netsuite/records/customer_addressbook_list' autoload :CustomerCategory, 'netsuite/records/customer_category' autoload :CustomerCreditCards, 'netsuite/records/customer_credit_cards' autoload :CustomerCreditCardsList, 'netsuite/records/customer_credit_cards_list' autoload :CustomerCurrency, 'netsuite/records/customer_currency' autoload :CustomerCurrencyList, 'netsuite/records/customer_currency_list' autoload :CustomerDeposit, 'netsuite/records/customer_deposit' autoload :CustomerDepositApplyList, 'netsuite/records/customer_deposit_apply_list' autoload :CustomerDepositApply, 'netsuite/records/customer_deposit_apply' autoload :CustomerPartnersList, 'netsuite/records/customer_partners_list' autoload :CustomerPayment, 'netsuite/records/customer_payment' autoload :CustomerPaymentApply, 'netsuite/records/customer_payment_apply' autoload :CustomerPaymentApplyList, 'netsuite/records/customer_payment_apply_list' autoload :CustomerPaymentCredit, 'netsuite/records/customer_payment_credit' autoload :CustomerPaymentCreditList, 'netsuite/records/customer_payment_credit_list' autoload :CustomerPartner, 'netsuite/records/customer_partner' autoload :CustomerRefund, 'netsuite/records/customer_refund' autoload :CustomerRefundApply, 'netsuite/records/customer_refund_apply' autoload :CustomerRefundApplyList, 'netsuite/records/customer_refund_apply_list' autoload :CustomerRefundDeposit, 'netsuite/records/customer_refund_deposit' autoload :CustomerRefundDepositList, 'netsuite/records/customer_refund_deposit_list' autoload :CustomerSubscription, 'netsuite/records/customer_subscription' autoload :CustomerSubscriptionsList, 'netsuite/records/customer_subscriptions_list' autoload :CustomerStatus, 'netsuite/records/customer_status' autoload :CustomerPartner, 'netsuite/records/customer_partner' autoload :CustomerSalesTeam, 'netsuite/records/customer_sales_team' autoload :CustomerSalesTeamList, 'netsuite/records/customer_sales_team_list' autoload :ContactList, 'netsuite/records/contact_list' autoload :Contact, 'netsuite/records/contact' autoload :ContactAddressbook, 'netsuite/records/contact_addressbook' autoload :ContactAddressbookList, 'netsuite/records/contact_addressbook_list' autoload :ContactRole, 'netsuite/records/contact_role' autoload :ContactAccessRoles, 'netsuite/records/contact_access_roles' autoload :ContactAccessRolesList, 'netsuite/records/contact_access_roles_list' autoload :Currency, 'netsuite/records/currency' autoload :CurrencyRate, 'netsuite/records/currency_rate' autoload :Department, 'netsuite/records/department' autoload :Deposit, 'netsuite/records/deposit' autoload :DepositApplication, 'netsuite/records/deposit_application' autoload :DepositPayment, 'netsuite/records/deposit_payment' autoload :DepositPaymentList, 'netsuite/records/deposit_payment_list' autoload :DepositOther, 'netsuite/records/deposit_other' autoload :DepositOtherList, 'netsuite/records/deposit_other_list' autoload :DepositCashBack, 'netsuite/records/deposit_cash_back' autoload :DepositCashBackList, 'netsuite/records/deposit_cash_back_list' autoload :DescriptionItem, 'netsuite/records/description_item' autoload :DiscountItem, 'netsuite/records/discount_item' autoload :Duration, 'netsuite/records/duration' autoload :Employee, 'netsuite/records/employee' autoload :EntityCustomField, 'netsuite/records/entity_custom_field' autoload :Estimate, 'netsuite/records/estimate' autoload :EstimateItem, 'netsuite/records/estimate_item' autoload :EstimateItemList, 'netsuite/records/estimate_item_list' autoload :File, 'netsuite/records/file' autoload :GiftCertificate, 'netsuite/records/gift_certificate' autoload :GiftCertificateItem, 'netsuite/records/gift_certificate_item' autoload :GiftCertRedemption, 'netsuite/records/gift_cert_redemption' autoload :GiftCertRedemptionList, 'netsuite/records/gift_cert_redemption_list' autoload :Folder, 'netsuite/records/folder' autoload :InboundShipment, 'netsuite/records/inbound_shipment' autoload :InboundShipmentItem, 'netsuite/records/inbound_shipment_item' autoload :InboundShipmentItemList, 'netsuite/records/inbound_shipment_item_list' autoload :InterCompanyJournalEntry, 'netsuite/records/inter_company_journal_entry' autoload :InterCompanyJournalEntryLine, 'netsuite/records/inter_company_journal_entry_line' autoload :InterCompanyJournalEntryLineList, 'netsuite/records/inter_company_journal_entry_line_list' autoload :InventoryAdjustment, 'netsuite/records/inventory_adjustment' autoload :InventoryAdjustmentInventory, 'netsuite/records/inventory_adjustment_inventory' autoload :InventoryAdjustmentInventoryList, 'netsuite/records/inventory_adjustment_inventory_list' autoload :InventoryAssignment, 'netsuite/records/inventory_assignment' autoload :InventoryAssignmentList, 'netsuite/records/inventory_assignment_list' autoload :InventoryDetail, 'netsuite/records/inventory_detail' autoload :InventoryItem, 'netsuite/records/inventory_item' autoload :InventoryNumber, 'netsuite/records/inventory_number' autoload :InventoryNumberLocations, 'netsuite/records/inventory_number_locations' autoload :InventoryNumberLocationsList, 'netsuite/records/inventory_number_locations_list' autoload :InventoryTransfer, 'netsuite/records/inventory_transfer' autoload :InventoryTransferInventory, 'netsuite/records/inventory_transfer_inventory' autoload :InventoryTransferInventoryList, 'netsuite/records/inventory_transfer_inventory_list' autoload :Invoice, 'netsuite/records/invoice' autoload :InvoiceItem, 'netsuite/records/invoice_item' autoload :InvoiceItemList, 'netsuite/records/invoice_item_list' autoload :ItemFulfillment, 'netsuite/records/item_fulfillment' autoload :ItemFulfillmentItem, 'netsuite/records/item_fulfillment_item' autoload :ItemFulfillmentItemList, 'netsuite/records/item_fulfillment_item_list' autoload :ItemFulfillmentPackage, 'netsuite/records/item_fulfillment_package' autoload :ItemFulfillmentPackageList, 'netsuite/records/item_fulfillment_package_list' autoload :ItemGroup, 'netsuite/records/item_group' autoload :ItemMember, 'netsuite/records/item_member' autoload :ItemMemberList, 'netsuite/records/item_member_list' autoload :ItemReceipt, 'netsuite/records/item_receipt' autoload :ItemReceiptItemList, 'netsuite/records/item_receipt_item_list' autoload :ItemReceiptItem, 'netsuite/records/item_receipt_item' autoload :ItemVendor, 'netsuite/records/item_vendor' autoload :ItemVendorList, 'netsuite/records/item_vendor_list' autoload :Job, 'netsuite/records/job' autoload :JobStatus, 'netsuite/records/job_status' autoload :JournalEntry, 'netsuite/records/journal_entry' autoload :JournalEntryLine, 'netsuite/records/journal_entry_line' autoload :JournalEntryLineList, 'netsuite/records/journal_entry_line_list' autoload :KitItem, 'netsuite/records/kit_item' autoload :Location, 'netsuite/records/location' autoload :LocationsList, 'netsuite/records/locations_list' autoload :LotNumberedAssemblyItem, 'netsuite/records/lot_numbered_assembly_item' autoload :LotNumberedInventoryItem, 'netsuite/records/lot_numbered_inventory_item' autoload :MatrixOptionList, 'netsuite/records/matrix_option_list' autoload :MemberList, 'netsuite/records/member_list' autoload :Message, 'netsuite/records/message' autoload :NonInventorySaleItem, 'netsuite/records/non_inventory_sale_item' autoload :NonInventoryPurchaseItem, 'netsuite/records/non_inventory_purchase_item' autoload :NonInventoryResaleItem, 'netsuite/records/non_inventory_resale_item' autoload :Note, 'netsuite/records/note' autoload :NoteType, 'netsuite/records/note_type' autoload :Opportunity, 'netsuite/records/opportunity' autoload :OpportunityItem, 'netsuite/records/opportunity_item' autoload :OpportunityItemList, 'netsuite/records/opportunity_item_list' autoload :OtherChargeSaleItem, 'netsuite/records/other_charge_sale_item' autoload :Partner, 'netsuite/records/partner' autoload :PaymentItem, 'netsuite/records/payment_item' autoload :PaymentMethod, 'netsuite/records/payment_method' autoload :PayrollItem, 'netsuite/records/payroll_item' autoload :PhoneCall, 'netsuite/records/phone_call' autoload :Price, 'netsuite/records/price' autoload :PriceLevel, 'netsuite/records/price_level' autoload :PriceList, 'netsuite/records/price_list' autoload :Pricing, 'netsuite/records/pricing' autoload :PricingMatrix, 'netsuite/records/pricing_matrix' autoload :PromotionCode, 'netsuite/records/promotion_code' autoload :PromotionsList, 'netsuite/records/promotions_list' autoload :Promotions, 'netsuite/records/promotions' autoload :PurchaseOrder, 'netsuite/records/purchase_order' autoload :PurchaseOrderItemList, 'netsuite/records/purchase_order_item_list' autoload :PurchaseOrderItem, 'netsuite/records/purchase_order_item' autoload :Roles, 'netsuite/records/roles' autoload :RecordRef, 'netsuite/records/record_ref' autoload :RecordRefList, 'netsuite/records/record_ref_list' autoload :RevRecTemplate, 'netsuite/records/rev_rec_template' autoload :RevRecSchedule, 'netsuite/records/rev_rec_schedule' autoload :RoleList, 'netsuite/records/role_list' autoload :ReturnAuthorization, 'netsuite/records/return_authorization' autoload :ReturnAuthorizationItem, 'netsuite/records/return_authorization_item' autoload :ReturnAuthorizationItemList, 'netsuite/records/return_authorization_item_list' autoload :SalesOrder, 'netsuite/records/sales_order' autoload :SalesOrderShipGroupList, 'netsuite/records/sales_order_ship_group_list' autoload :SalesOrderItem, 'netsuite/records/sales_order_item' autoload :SalesOrderItemList, 'netsuite/records/sales_order_item_list' autoload :SalesRole, 'netsuite/records/sales_role' autoload :SalesTaxItem, 'netsuite/records/sales_tax_item' autoload :ServiceResaleItem, 'netsuite/records/service_resale_item' autoload :ServiceSaleItem, 'netsuite/records/service_sale_item' autoload :SerializedAssemblyItem, 'netsuite/records/serialized_assembly_item' autoload :SerializedInventoryItem, 'netsuite/records/serialized_inventory_item' autoload :SerializedInventoryItemNumbers, 'netsuite/records/serialized_inventory_item_numbers' autoload :SerializedInventoryItemNumbersList, 'netsuite/records/serialized_inventory_item_numbers_list' autoload :SerializedInventoryItemLocation, 'netsuite/records/serialized_inventory_item_location' autoload :SerializedInventoryItemLocationsList, 'netsuite/records/serialized_inventory_item_locations_list' autoload :ShipAddress, 'netsuite/records/ship_address' autoload :SiteCategory, 'netsuite/records/site_category' autoload :Subsidiary, 'netsuite/records/subsidiary' autoload :SubtotalItem, 'netsuite/records/subtotal_item' autoload :SupportCase, 'netsuite/records/support_case' autoload :SupportCaseType, 'netsuite/records/support_case_type' autoload :TaxType, 'netsuite/records/tax_type' autoload :TaxGroup, 'netsuite/records/tax_group' autoload :Task, 'netsuite/records/task' autoload :Term, 'netsuite/records/term' autoload :TimeBill, 'netsuite/records/time_bill' autoload :TransactionBodyCustomField, 'netsuite/records/transaction_body_custom_field' autoload :TransactionColumnCustomField, 'netsuite/records/transaction_column_custom_field' autoload :TransactionShipGroup, 'netsuite/records/transaction_ship_group' autoload :TransferOrder, 'netsuite/records/transfer_order' autoload :TransferOrderItemList, 'netsuite/records/transfer_order_item_list' autoload :TransferOrderItem, 'netsuite/records/transfer_order_item' autoload :UnitsType, 'netsuite/records/units_type' autoload :UnitsTypeUomList, 'netsuite/records/units_type_uom_list' autoload :UnitsTypeUom, 'netsuite/records/units_type_uom' autoload :Vendor, 'netsuite/records/vendor' autoload :VendorBill, 'netsuite/records/vendor_bill' autoload :VendorBillExpense, 'netsuite/records/vendor_bill_expense' autoload :VendorBillExpenseList, 'netsuite/records/vendor_bill_expense_list' autoload :VendorBillItem, 'netsuite/records/vendor_bill_item' autoload :VendorBillItemList, 'netsuite/records/vendor_bill_item_list' autoload :VendorCategory, 'netsuite/records/vendor_category' autoload :VendorCredit, 'netsuite/records/vendor_credit' autoload :VendorCreditApply, 'netsuite/records/vendor_credit_apply' autoload :VendorCreditApplyList, 'netsuite/records/vendor_credit_apply_list' autoload :VendorCreditItem, 'netsuite/records/vendor_credit_item' autoload :VendorCreditItemList, 'netsuite/records/vendor_credit_item_list' autoload :VendorCreditExpense, 'netsuite/records/vendor_credit_expense' autoload :VendorCreditExpenseList, 'netsuite/records/vendor_credit_expense_list' autoload :VendorCurrencyList, 'netsuite/records/vendor_currency_list' autoload :VendorCurrency, 'netsuite/records/vendor_currency' autoload :VendorReturnAuthorization, 'netsuite/records/vendor_return_authorization' autoload :VendorReturnAuthorizationItem, 'netsuite/records/vendor_return_authorization_item' autoload :VendorReturnAuthorizationItemList, 'netsuite/records/vendor_return_authorization_item_list' autoload :VendorPayment, 'netsuite/records/vendor_payment' autoload :VendorPaymentApply, 'netsuite/records/vendor_payment_apply' autoload :VendorPaymentApplyList, 'netsuite/records/vendor_payment_apply_list' autoload :WorkOrder, 'netsuite/records/work_order' autoload :WorkOrderItem, 'netsuite/records/work_order_item' autoload :WorkOrderItemList, 'netsuite/records/work_order_item_list' end module Passports autoload :User, 'netsuite/passports/user' autoload :Token, 'netsuite/passports/token' end def self.configure(&block) NetSuite::Configuration.instance_eval(&block) end end
74.644172
117
0.667831
335f70bbc17e90874f3e96907a3172308cbb2be2
252
allowed_environments = %w{ production staging development test } unless allowed_environments.include? node.chef_environment raise "Dude, your environment #{node.chef_environment.inspect} is really not one of #{allowed_environments.join(', ')}." end
42
122
0.793651
b9cdee837e0e18d5c8c42cd098d3be228244b6ca
142
# frozen_string_literal: true class ApplicationMailer < ActionMailer::Base default from: '[email protected]' layout 'mailer' end
20.285714
44
0.78169
79c0a1e4704a20e14956d4e5c569676b1ec7f112
126
require_relative('ios/test_app') def use_test_app!(options = {}, &block) use_test_app_internal!(:ios, options, &block) end
21
47
0.738095
79481d85882131e8c8badfc9ec35a18fabebb6ab
1,147
# frozen_string_literal: true module Xcode include MiniTest::Assertions def self.product_with_name(name, destination:, derived_data_path:) glob = File.join(derived_data_path, "**/Build/**/Products/#{destination}/#{name}/") Dir.glob(glob).max_by { |f| File.mtime(f) } end def self.find_framework(product:, destination:, framework:, derived_data_path:) product_path = product_with_name( product, destination: destination, derived_data_path: derived_data_path ) return if product_path.nil? framework_glob = File.join(product_path, "**/Frameworks/#{framework}.framework") # /path/to/product/Frameworks/MyFramework.framework framework_path = Dir.glob(framework_glob).first framework_path end def self.find_resource(product:, destination:, resource:, derived_data_path:) product_path = product_with_name( product, destination: destination, derived_data_path: derived_data_path ) return if product_path.nil? resource_glob = File.join(product_path, "**/#{resource}") # /path/to/product/resource.png Dir.glob(resource_glob).first end end
28.675
87
0.71578
1c75c67403da6980963bcaa28e1ca23e02415e5d
459
cask 'natron' do version '2.3.3' sha256 '3efe76aa82872b2bdd80ec96746151d3997c9662967d008d22a010eff241e483' url "https://downloads.natron.fr/Mac/releases/Natron-#{version}.dmg", referer: 'https://natron.fr/download/?os=Mac' appcast 'https://github.com/MrKepzie/Natron/releases.atom', checkpoint: '03c0144b1f5a17998020f8c05dbf13e9d8b9d9db322576cb9746c5bf183db2aa' name 'Natron' homepage 'https://natron.fr/' app 'Natron.app' end
32.785714
88
0.749455
6a088569a52a4a16a979c988083bdd29ecf8a290
125
module Sass::Script::Functions def microtime() return Sass::Script::Number.new(Time.now.to_f * 1000) end end
20.833333
61
0.664
ff48eeb74e74857078a75e55baef8bae94119302
3,566
# frozen_string_literal: true module Archimate module FileFormats module Sax SaxEvent = Struct.new(:sym, :args, :source) FutureReference = Struct.new(:obj, :attr, :id) autoload :AnyElement, 'archimate/file_formats/sax/any_element' autoload :CaptureContent, 'archimate/file_formats/sax/capture_content' autoload :CaptureDocumentation, 'archimate/file_formats/sax/capture_documentation' autoload :CaptureProperties, 'archimate/file_formats/sax/capture_properties' autoload :ContentElement, 'archimate/file_formats/sax/content_element' autoload :Document, 'archimate/file_formats/sax/document' autoload :Handler, 'archimate/file_formats/sax/handler' autoload :LangString, 'archimate/file_formats/sax/lang_string' autoload :NoOp, 'archimate/file_formats/sax/no_op' autoload :PreservedLangString, 'archimate/file_formats/sax/preserved_lang_string' module Archi autoload :ArchiHandlerFactory, 'archimate/file_formats/sax/archi/archi_handler_factory' autoload :Bounds, 'archimate/file_formats/sax/archi/bounds' autoload :Connection, 'archimate/file_formats/sax/archi/connection' autoload :Content, 'archimate/file_formats/sax/archi/content' autoload :Diagram, 'archimate/file_formats/sax/archi/diagram' autoload :Element, 'archimate/file_formats/sax/archi/element' autoload :Location, 'archimate/file_formats/sax/archi/location' autoload :Model, 'archimate/file_formats/sax/archi/model' autoload :Organization, 'archimate/file_formats/sax/archi/organization' autoload :PreservedLangString, 'archimate/file_formats/sax/archi/preserved_lang_string' autoload :Property, 'archimate/file_formats/sax/archi/property' autoload :Relationship, 'archimate/file_formats/sax/archi/relationship' autoload :Style, 'archimate/file_formats/sax/archi/style' autoload :ViewNode, 'archimate/file_formats/sax/archi/view_node' end module ModelExchangeFile autoload :Color, 'archimate/file_formats/sax/model_exchange_file/color' autoload :Connection, 'archimate/file_formats/sax/model_exchange_file/connection' autoload :Diagram, 'archimate/file_formats/sax/model_exchange_file/diagram' autoload :Element, 'archimate/file_formats/sax/model_exchange_file/element' autoload :Font, 'archimate/file_formats/sax/model_exchange_file/font' autoload :Item, 'archimate/file_formats/sax/model_exchange_file/item' autoload :Location, 'archimate/file_formats/sax/model_exchange_file/location' autoload :Metadata, 'archimate/file_formats/sax/model_exchange_file/metadata' autoload :ModelExchangeHandlerFactory, 'archimate/file_formats/sax/model_exchange_file/model_exchange_handler_factory' autoload :Model, 'archimate/file_formats/sax/model_exchange_file/model' autoload :Property, 'archimate/file_formats/sax/model_exchange_file/property' autoload :PropertyDefinition, 'archimate/file_formats/sax/model_exchange_file/property_definition' autoload :Relationship, 'archimate/file_formats/sax/model_exchange_file/relationship' autoload :Schema, 'archimate/file_formats/sax/model_exchange_file/schema' autoload :SchemaInfo, 'archimate/file_formats/sax/model_exchange_file/schema_info' autoload :Style, 'archimate/file_formats/sax/model_exchange_file/style' autoload :ViewNode, 'archimate/file_formats/sax/model_exchange_file/view_node' end end end end
62.561404
126
0.762479
edd4555568bcb5dbb7f432ff429635b64d7edb94
566
# Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. #ActiveSupport.on_load(:action_controller) do # wrap_parameters format: [:json] #end # To enable root element in JSON for ActiveRecord objects. # ActiveSupport.on_load(:active_record) do # self.include_root_in_json = true # end ActiveSupport.on_load(:action_controller) do wrap_parameters format: [] end
31.444444
96
0.784452
e20944d6a76b6952a1c04fcf220511938d1739d1
253
# frozen_string_literal: true module Namespaceable extend ActiveSupport::Concern included do include Pundit before_action :namespace end private def namespace @namespace = Namespace.friendly.find(params[:slug][1..]) end end
14.055556
60
0.727273
b937e253a893c6756cb54c42871934f18a738d52
6,051
# frozen_string_literal: true require 'i18n/backend/base' module I18n begin require 'oj' class JSON class << self def encode(value) Oj::Rails.encode(value) end def decode(value) Oj.load(value) end end end rescue LoadError require 'active_support/json' JSON = ActiveSupport::JSON end module Backend # This is a basic backend for key value stores. It receives on # initialization the store, which should respond to three methods: # # * store#[](key) - Used to get a value # * store#[]=(key, value) - Used to set a value # * store#keys - Used to get all keys # # Since these stores only supports string, all values are converted # to JSON before being stored, allowing it to also store booleans, # hashes and arrays. However, this store does not support Procs. # # As the ActiveRecord backend, Symbols are just supported when loading # translations from the filesystem or through explicit store translations. # # Also, avoid calling I18n.available_locales since it's a somehow # expensive operation in most stores. # # == Example # # To setup I18n to use TokyoCabinet in memory is quite straightforward: # # require 'rufus/tokyo/cabinet' # gem install rufus-tokyo # I18n.backend = I18n::Backend::KeyValue.new(Rufus::Tokyo::Cabinet.new('*')) # # == Performance # # You may make this backend even faster by including the Memoize module. # However, notice that you should properly clear the cache if you change # values directly in the key-store. # # == Subtrees # # In most backends, you are allowed to retrieve part of a translation tree: # # I18n.backend.store_translations :en, :foo => { :bar => :baz } # I18n.t "foo" #=> { :bar => :baz } # # This backend supports this feature by default, but it slows down the storage # of new data considerably and makes hard to delete entries. That said, you are # allowed to disable the storage of subtrees on initialization: # # I18n::Backend::KeyValue.new(@store, false) # # This is useful if you are using a KeyValue backend chained to a Simple backend. class KeyValue module Implementation attr_accessor :store include Base, Flatten def initialize(store, subtrees=true) @store, @subtrees = store, subtrees end def initialized? [email protected]? end def store_translations(locale, data, options = EMPTY_HASH) escape = options.fetch(:escape, true) flatten_translations(locale, data, escape, @subtrees).each do |key, value| key = "#{locale}.#{key}" case value when Hash if @subtrees && (old_value = @store[key]) old_value = JSON.decode(old_value) value = Utils.deep_merge!(Utils.deep_symbolize_keys(old_value), value) if old_value.is_a?(Hash) end when Proc raise "Key-value stores cannot handle procs" end @store[key] = JSON.encode(value) unless value.is_a?(Symbol) end end def available_locales locales = @store.keys.map { |k| k =~ /\./; $` } locales.uniq! locales.compact! locales.map! { |k| k.to_sym } locales end protected # Queries the translations from the key-value store and converts # them into a hash such as the one returned from loading the # haml files def translations @translations = Utils.deep_symbolize_keys(@store.keys.clone.map do |main_key| main_value = JSON.decode(@store[main_key]) main_key.to_s.split(".").reverse.inject(main_value) do |value, key| {key.to_sym => value} end end.inject{|hash, elem| Utils.deep_merge!(hash, elem)}) end def init_translations # NO OP # This call made also inside Simple Backend and accessed by # other plugins like I18n-js and babilu and # to use it along with the Chain backend we need to # provide a uniform API even for protected methods :S end def subtrees? @subtrees end def lookup(locale, key, scope = [], options = EMPTY_HASH) key = normalize_flat_keys(locale, key, scope, options[:separator]) value = @store["#{locale}.#{key}"] value = JSON.decode(value) if value if value.is_a?(Hash) Utils.deep_symbolize_keys(value) elsif !value.nil? value elsif !@subtrees SubtreeProxy.new("#{locale}.#{key}", @store) end end def pluralize(locale, entry, count) if subtrees? super else return entry unless entry.is_a?(Hash) key = pluralization_key(entry, count) entry[key] end end end class SubtreeProxy def initialize(master_key, store) @master_key = master_key @store = store @subtree = nil end def has_key?(key) @subtree && @subtree.has_key?(key) || self[key] end def [](key) unless @subtree && value = @subtree[key] value = @store["#{@master_key}.#{key}"] if value value = JSON.decode(value) (@subtree ||= {})[key] = value end end value end def is_a?(klass) Hash == klass || super end alias :kind_of? :is_a? def instance_of?(klass) Hash == klass || super end def nil? @subtree.nil? end def inspect @subtree.inspect end end include Implementation end end end
29.517073
111
0.571311
1c60e0d668dabd96df5c7a71df6c6a2ada1d26b9
131
require 'test_helper' class DogsControllerTest < ActionController::TestCase # test "the truth" do # assert true # end end
16.375
53
0.725191
ab9409d4e737ae2eab11f5b2f4cf6697bd59cd8e
8,775
describe 'Ridgepole::Client#diff -> migrate' do context 'when add column after id (pk: normal)' do let(:actual_dsl) do erbh(<<-ERB) create_table "employees", force: :cascade do |t| t.date "birth_date", null: false t.string "first_name", limit: 14, null: false t.string "last_name", limit: 16, null: false t.string "gender", limit: 1, null: false t.date "hire_date", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.binary "registered_name", <%= i cond(5.0, limit: 65535) %> end ERB end let(:expected_dsl) do erbh(<<-ERB) create_table "employees", force: :cascade do |t| t.string "ext_column", null: false t.date "birth_date", null: false t.string "first_name", limit: 14, null: false t.string "last_name", limit: 16, null: false t.string "gender", limit: 1, null: false t.date "hire_date", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.binary "registered_name", limit: 255 end ERB end before { subject.diff(actual_dsl).migrate } subject { client } it { delta = subject.diff(expected_dsl) expect(delta.differ?).to be_truthy expect(subject.dump).to match_ruby actual_dsl delta.migrate expect(subject.dump).to match_ruby expected_dsl expect(show_create_table_mysql('employees')).to match_fuzzy erbh(<<-ERB) CREATE TABLE `employees` ( `id` <%= cond('>= 5.1','bigint(20)', 'int(11)') %> NOT NULL AUTO_INCREMENT, `ext_column` varchar(255) NOT NULL, `birth_date` date NOT NULL, `first_name` varchar(14) NOT NULL, `last_name` varchar(16) NOT NULL, `gender` varchar(1) NOT NULL, `hire_date` date NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, `registered_name` varbinary(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ERB } end context 'when add column after id (pk: emp_id)' do let(:actual_dsl) do erbh(<<-ERB) create_table "employees", primary_key: "emp_id", force: :cascade do |t| t.date "birth_date", null: false t.string "first_name", limit: 14, null: false t.string "last_name", limit: 16, null: false t.string "gender", limit: 1, null: false t.date "hire_date", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.binary "registered_name", <%= i cond(5.0, limit: 65535) %> end ERB end let(:expected_dsl) do erbh(<<-ERB) create_table "employees", primary_key: "emp_id", force: :cascade do |t| t.string "ext_column", null: false t.date "birth_date", null: false t.string "first_name", limit: 14, null: false t.string "last_name", limit: 16, null: false t.string "gender", limit: 1, null: false t.date "hire_date", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.binary "registered_name", limit: 255 end ERB end before { subject.diff(actual_dsl).migrate } subject { client } it { delta = subject.diff(expected_dsl) expect(delta.differ?).to be_truthy expect(subject.dump).to match_ruby actual_dsl delta.migrate expect(subject.dump).to match_ruby expected_dsl expect(show_create_table_mysql('employees')).to match_fuzzy erbh(<<-ERB) CREATE TABLE `employees` ( `emp_id` <%= cond('>= 5.1','bigint(20)', 'int(11)') %> NOT NULL AUTO_INCREMENT, `ext_column` varchar(255) NOT NULL, `birth_date` date NOT NULL, `first_name` varchar(14) NOT NULL, `last_name` varchar(16) NOT NULL, `gender` varchar(1) NOT NULL, `hire_date` date NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, `registered_name` varbinary(255) DEFAULT NULL, PRIMARY KEY (`emp_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ERB } end context 'when add column after id (pk: no pk)' do let(:actual_dsl) do erbh(<<-ERB) create_table "employees", id: false, force: :cascade do |t| t.date "birth_date", null: false t.string "first_name", limit: 14, null: false t.string "last_name", limit: 16, null: false t.string "gender", limit: 1, null: false t.date "hire_date", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.binary "registered_name", <%= i cond(5.0, limit: 65535) %> end ERB end let(:expected_dsl) do erbh(<<-ERB) create_table "employees", id: false, force: :cascade do |t| t.string "ext_column", null: false t.date "birth_date", null: false t.string "first_name", limit: 14, null: false t.string "last_name", limit: 16, null: false t.string "gender", limit: 1, null: false t.date "hire_date", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.binary "registered_name", limit: 255 end ERB end before { subject.diff(actual_dsl).migrate } subject { client } it { delta = subject.diff(expected_dsl) expect(delta.differ?).to be_truthy expect(subject.dump).to match_ruby actual_dsl delta.migrate expect(subject.dump).to match_ruby expected_dsl expect(show_create_table_mysql('employees')).to match_fuzzy <<-SQL CREATE TABLE `employees` ( `ext_column` varchar(255) NOT NULL, `birth_date` date NOT NULL, `first_name` varchar(14) NOT NULL, `last_name` varchar(16) NOT NULL, `gender` varchar(1) NOT NULL, `hire_date` date NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, `registered_name` varbinary(255) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 SQL } end context 'when add column after id (pk: with pk delta)' do let(:actual_dsl) do erbh(<<-ERB) create_table "employees", force: :cascade do |t| t.date "birth_date", null: false t.string "first_name", limit: 14, null: false t.string "last_name", limit: 16, null: false t.string "gender", limit: 1, null: false t.date "hire_date", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.binary "registered_name", <%= i cond(5.0, limit: 65535) %> end ERB end let(:expected_dsl) do erbh(<<-ERB) create_table "employees", primary_key: "emp_id", force: :cascade do |t| t.string "ext_column", null: false t.date "birth_date", null: false t.string "first_name", limit: 14, null: false t.string "last_name", limit: 16, null: false t.string "gender", limit: 1, null: false t.date "hire_date", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.binary "registered_name", limit: 255 end ERB end before { subject.diff(actual_dsl).migrate } subject { client } it { delta = subject.diff(expected_dsl) expect(delta.differ?).to be_truthy expect(subject.dump).to match_ruby actual_dsl delta.migrate expect(subject.dump).to match_ruby expected_dsl.sub(/, *primary_key: *"emp_id"/, '') expect(show_create_table_mysql('employees')).to match_fuzzy erbh(<<-ERB) CREATE TABLE `employees` ( `id` <%= cond('>= 5.1','bigint(20)', 'int(11)') %> NOT NULL AUTO_INCREMENT, `ext_column` varchar(255) NOT NULL, `birth_date` date NOT NULL, `first_name` varchar(14) NOT NULL, `last_name` varchar(16) NOT NULL, `gender` varchar(1) NOT NULL, `hire_date` date NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, `registered_name` varbinary(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ERB } end end
36.5625
90
0.579943
f704b81ee6db285c927ca9c97c2c4a81dbc1b819
1,461
module Concurrent module Synchronization # @!visibility private # TODO (pitr-ch 04-Dec-2016): should be in edge class Condition < LockableObject safe_initialization! # TODO (pitr 12-Sep-2015): locks two objects, improve # TODO (pitr 26-Sep-2015): study # http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/concurrent/locks/AbstractQueuedSynchronizer.java#AbstractQueuedSynchronizer.Node singleton_class.send :alias_method, :private_new, :new private_class_method :new def initialize(lock) super() @Lock = lock end def wait(timeout = nil) @Lock.synchronize { ns_wait(timeout) } end def ns_wait(timeout = nil) synchronize { super(timeout) } end def wait_until(timeout = nil, &condition) @Lock.synchronize { ns_wait_until(timeout, &condition) } end def ns_wait_until(timeout = nil, &condition) synchronize { super(timeout, &condition) } end def signal @Lock.synchronize { ns_signal } end def ns_signal synchronize { super } end def broadcast @Lock.synchronize { ns_broadcast } end def ns_broadcast synchronize { super } end end class LockableObject < LockableObjectImplementation def new_condition Condition.private_new(self) end end end end
23.95082
176
0.637235