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
|
---|---|---|---|---|---|
62d59c80629674a7e7b10120f06af0f1ecf04214 | 5,008 | require 'active_record'
require 'fileutils'
require_relative '../../../services/user-mover/export_user'
require_dependency 'file_upload'
require_dependency 'resque/user_migration_jobs'
require_dependency 'carto/ghost_tables_manager'
module Carto
class UserMigrationExport < ::ActiveRecord::Base
belongs_to :organization, class_name: Carto::Organization
belongs_to :user, class_name: Carto::User
belongs_to :log, class_name: Carto::Log
STATE_PENDING = 'pending'.freeze
STATE_EXPORTING = 'exporting'.freeze
STATE_UPLOADING = 'uploading'.freeze
STATE_COMPLETE = 'complete'.freeze
STATE_FAILURE = 'failure'.freeze
VALID_STATES = [STATE_PENDING, STATE_EXPORTING, STATE_UPLOADING, STATE_COMPLETE, STATE_FAILURE].freeze
after_initialize :set_defaults
validates :state, inclusion: { in: VALID_STATES }
validate :user_or_organization_present
validate :validate_export_data
def run_export
check_valid_user(user) if user && export_metadata
check_valid_organization(organization) if organization && export_metadata
check_custom_plpython2_functions
log.append("=== Exporting #{organization ? 'user' : 'org'} data ===")
update_attributes(state: STATE_EXPORTING)
package = if backup
UserMigrationPackage.for_backup("backup_#{user.username}_#{Time.now.iso8601}", log)
else
UserMigrationPackage.for_export(id, log)
end
export_job = CartoDB::DataMover::ExportJob.new(export_job_arguments(package.data_dir)) if export_data?
run_metadata_export(package.meta_dir) if export_metadata?
log.append("=== Uploading ===")
update_attributes(
state: STATE_UPLOADING,
json_file: export_data? ? "#{id}/#{export_job.json_file}" : 'no_data_exported'
)
uploaded_path = package.upload
state = uploaded_path.present? ? STATE_COMPLETE : STATE_FAILURE
log.append("=== Finishing. State: #{state}. File: #{uploaded_path} ===")
update_attributes(state: state, exported_file: uploaded_path)
true
rescue => e
log.append_exception('Exporting', exception: e)
CartoDB::Logger.error(exception: e, message: 'Error exporting user data', job: inspect)
update_attributes(state: STATE_FAILURE)
false
ensure
package.try(:cleanup)
end
def enqueue
Resque.enqueue(Resque::UserMigrationJobs::Export, export_id: id)
end
private
# TODO: delete this once migration to plpython3 is completed
def check_custom_plpython2_functions
target_user = user || organization.owner
pg_result = target_user.in_database(as: :superuser).execute(%{
select
nspname, proname
from
pg_catalog.pg_proc p
join pg_catalog.pg_language l on p.prolang = l.oid
join pg_namespace on p.pronamespace = pg_namespace.oid
where
lanname in ('plpythonu', 'plpython2u') and
nspname not in ('cartodb', 'cdb_dataservices_client', 'cdb_crankshaft') and
(nspname = 'public' and proname not in ('cdb_invalidate_varnish', 'update_timestamp'))
})
raise "Can't migrate custom plpython2 functions" if pg_result.ntuples > 0
end
def check_valid_user(user)
Carto::GhostTablesManager.new(user.id).link_ghost_tables_synchronously
end
def check_valid_organization(organization)
organization.users.each do |user|
check_valid_user(user)
end
end
def run_metadata_export(meta_dir)
if organization
Carto::OrganizationMetadataExportService.new.export_to_directory(organization, meta_dir)
elsif user
Carto::UserMetadataExportService.new.export_to_directory(user, meta_dir)
else
raise 'Unrecognized export type for exporting metadata'
end
end
def export_job_arguments(data_dir)
args = if user.present?
{
id: user.username,
schema_mode: false
}
else
{
organization_name: organization.name,
schema_mode: true,
split_user_schemas: false
}
end
args.merge(
path: data_dir,
job_uuid: id,
export_job_logger: log.logger,
logger: log.logger,
metadata: false,
data: export_data?
)
end
def user_or_organization_present
unless (user.present? && organization.blank?) || (organization.present? && user.blank?)
errors.add(:user, 'exactly one user or organization required')
end
end
def validate_export_data
errors.add(:export_metadata, 'needs to be true if export_data is set to false') if !export_data? && !export_metadata?
end
def set_defaults
self.log = Carto::Log.create(type: 'user_migration_export') unless log
self.state = STATE_PENDING unless state
save
end
end
end
| 32.519481 | 123 | 0.666733 |
910115ba57e685a620bb1021b93f6077013b2078 | 538 | class ApplicationError < StandardError
attr_reader :tags, :data
def initialize(subject, tags = '', data = {})
super(subject)
@tags = tags
@data = data
puts "#{'-'*10}\n#{@data}\n#{'-'*10}" if Rails.env.development?
Log.on_raise(self, caller(2))
end
# для логирования при бросании и в дефолтном обработчике
def with_log?
self.class.name.end_with?('Log', 'Alert')
end
# для логирования при бросании и в дефолтном обработчике
def with_alert?
self.class.name.end_with?('Alert')
end
end
| 18.551724 | 67 | 0.652416 |
61fb0e295b6a496eac000abd7a9f6b625dc212ba | 388 | class AddCreatedAtToVariant < ActiveRecord::Migration[5.0]
def change
add_column :spree_variants, :created_at, :datetime
Spree::Variant.reset_column_information
Spree::Variant.unscoped.where.not(updated_at: nil).update_all('created_at = updated_at')
Spree::Variant.unscoped.where(updated_at: nil).update_all(created_at: Time.current, updated_at: Time.current)
end
end
| 43.111111 | 113 | 0.780928 |
087a4628bf0fc35c5d9f06688b635774488dd2f7 | 941 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Google
module Apis
module DatastoreV1beta3
# Version of the google-apis-datastore_v1beta3 gem
GEM_VERSION = "0.10.0"
# Version of the code generator used to generate this client
GENERATOR_VERSION = "0.4.0"
# Revision of the discovery document this client was generated from
REVISION = "20211029"
end
end
end
| 32.448276 | 74 | 0.7322 |
266612e97206741a0945f2fda3f67b0fec26bd11 | 989 | module Jni
module J
module Android
module Webkit
class WebSettings < Java::Lang::Object
attach Void, "setJavaScriptEnabled", Boolean
end
class WebViewClient < Java::Lang::Object
attach_init
end
class WebView < Widget::AbsoluteLayout
attach_init Android::Content::Context
attach Void, "loadData", Java::Lang::String, Java::Lang::String, Java::Lang::String
attach Void, "loadDataWithBaseURL", Java::Lang::String, Java::Lang::String, Java::Lang::String, Java::Lang::String, Java::Lang::String
attach Void, "loadUrl", Java::Lang::String
attach Void, "setWebViewClient", Android::Webkit::WebViewClient
attach Void, "addJavascriptInterface", Java::Lang::Object, Java::Lang::String
attach Void, "setOnTouchListener", Android::View::View::OnTouchListener
attach Android::Webkit::WebSettings, "getSettings"
end
end
end
end
end | 41.208333 | 144 | 0.644085 |
4ae196efdf7628cbacce04751108929c92f30bb4 | 8,007 | # Embedded model that stores a location address
class Address
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::History::Trackable
embedded_in :person
embedded_in :office_location
embedded_in :census_member, class_name: "CensusMember"
KINDS = %W(home work mailing)
OFFICE_KINDS = %W(primary mailing branch)
# The type of address
field :kind, type: String
field :address_1, type: String
field :address_2, type: String, default: ""
field :address_3, type: String, default: ""
# The name of the city where this address is located
field :city, type: String
# The name of the county where this address is located
field :county, type: String, default: ''
# The name of the U.S. state where this address is located
field :state, type: String
# @todo Add support for FIPS codes
field :location_state_code, type: String
# @deprecated Use {#to_s} or {#to_html} instead
field :full_text, type: String
# The postal zip code where this address is located
field :zip, type: String
# The name of the country where this address is located
field :country_name, type: String, default: ""
track_history :on => [:fields],
:scope => :person,
:modifier_field => :modifier,
:modifier_field_optional => true,
:version_field => :tracking_version,
:track_create => true, # track document creation, default is false
:track_update => true, # track document updates, default is true
:track_destroy => true
validates_presence_of :address_1, :city, :state, :zip
validates :kind,
inclusion: { in: KINDS + OFFICE_KINDS, message: "%{value} is not a valid address kind" },
allow_blank: false
validates :zip,
format: {
:with => /\A\d{5}(-\d{4})?\z/,
:message => "should be in the form: 12345 or 12345-1234"
}
# @note Add support for GIS location
def location
nil #todo
end
def office_is_primary_location?
kind == 'primary'
end
# Determine if an address instance is empty
#
# @example Is the address blank?
# model.blank?
#
# @return [ true, false ] true if blank, false if present
def blank?
[:city, :zip, :address_1, :address_2].all? do |attr|
self.send(attr).blank?
end
end
# Get the full address formatted as a string with each line enclosed within html <div> tags
#
# @example Get the full address as a <div> delimited string
# model.to_html
#
# @return [ String ] the full address
def to_html
if address_2.blank?
"<div>#{address_1.strip()}</div><div>#{city}, #{state} #{zip}</div>".html_safe
else
"<div>#{address_1.strip()}</div><div>#{address_2}</div><div>#{city}, #{state} #{zip}</div>".html_safe
end
end
# Get the full address formatted as a <br/> delimited string
#
# @example Get the full address formatted as a <br/> delimited string
# model.to_s
#
# @return [ String ] the full address
def to_s
city.present? ? city_delim = city + "," : city_delim = city
line3 = [city_delim, state, zip].reject(&:nil? || empty?).join(' ')
[address_1, address_2, line3].reject(&:nil? || empty?).join('<br/>').html_safe
end
def to_a
[kind, address_1, address_2.to_s, city, state, zip]
end
# Get the full address formatted as a string
#
# @example Get the full address formatted as a string
# model.full_address
#
# @return [ String ] the full address
def full_address
city.present? ? city_delim = city + "," : city_delim = city
[address_1, address_2, city_delim, state, zip].reject(&:nil? || empty?).join(' ')
end
# Sets the address type.
#
# @overload kind=(new_kind)
#
# @param new_kind [ KINDS ] The address type.
# @param new_kind [ OFFICE_KINDS ] The {OfficeLocation} address type.
def kind=(new_kind)
kind_val = new_kind.to_s.squish.downcase
if kind_val == 'primary' && office_location.present? && office_location.is_primary
write_attribute(:kind, 'work')
else
write_attribute(:kind, kind_val)
end
end
# Gets the address type.
#
# @overload kind
#
# @return [ KINDS ] address type
# @return [ OFFICE_KINDS ] If the address is embedded in {OfficeLocation} address type
def kind
kind_val = read_attribute(:kind)
if office_location.present? && office_location.is_primary && kind_val == 'work'
'primary'
else
kind_val
end
end
# @overload address_1=(new_address_1)
#
# Sets the new first line of address
#
# @param new_address_1 [ String ] Address line number 1
def address_1=(new_address_1)
write_attribute(:address_1, new_address_1.to_s.squish)
end
# @overload address_2=(new_address_2)
#
# Sets the new second line of address
#
# @param new_address_2 [ String ] Address line number 2
def address_2=(new_address_2)
write_attribute(:address_2, new_address_2.to_s.squish)
end
# @overload address_3=(new_address_3)
#
# Sets the new third line of address
#
# @param new_address_3 [ String ] Address line number 3
def address_3=(new_address_3)
write_attribute(:address_3, new_address_3.to_s.squish)
end
# @overload city=(new_city)
#
# Sets the new city name
#
# @param new_city [String] the new city name
def city=(new_city)
write_attribute(:city, new_city.to_s.squish)
end
# @overload state=(new_state)
#
# Sets the new state name
#
# @param new_state [String] the new state name
def state=(new_state)
write_attribute(:state, new_state.to_s.squish)
end
# @overload zip=(new_zip)
#
# Sets the new five or nine digit postal zip code value
#
# @example Set five digit postal zip code
# model.zip = "20002"
# @example Set nine digit postal zip code
# model.zip = "20002-0001"
#
# @param new_zip [String] the new zip code
def zip=(new_zip)
write_attribute(:zip, new_zip.to_s.squish)
end
# Get the five digit postal zip code for this address, omitting the four digit extension
#
# @example Get the five digit postal zip code
# model.zip_without_extension
#
# @return [ String ] The five digit zip code.
def zip_without_extension
return nil if zip.blank?
if zip =~ /-/
zip.split("-").first
else
zip
end
end
# Get the postal zip code four digit extension for this address
#
# @example Get the four digit postal zip code extension
# model.zip_extension
#
# @return [ String ] The four digit zip code extension.
def zip_extension
return nil if zip.blank?
if zip =~ /-/
zip.split("-").last
else
nil
end
end
# Determine if this address is type: "mailing"
#
# @example Is the address a mailing address?
# model.mailing?
#
# @return [ true, false ] true if mailing type, false if not mailing type
def mailing?
kind.to_s == "mailing"
end
# Determine if this address is type: "home"
#
# @example Is the address a home address?
# model.home?
#
# @return [ true, false ] true if home type, false if not home type
def home?
"home" == self.kind.to_s
end
# Compare passed address with this address
#
# @param another_address [ Object ] The address to be compared.
#
# @return [ true, false ] true if addresses are the same, false if addresses are different
def matches_addresses?(another_address)
return(false) if another_address.nil?
attrs_to_match = [:kind, :address_1, :address_2, :address_3, :city, :state, :zip]
attrs_to_match.all? { |attr| attribute_matches?(attr, another_address) }
end
def same_address?(another_address)
return(false) if another_address.nil?
attrs_to_match = [:address_1, :address_2, :address_3, :city, :state, :zip]
attrs_to_match.all? { |attr| attribute_matches?(attr, another_address) }
end
private
def attribute_matches?(attribute, other)
self[attribute].to_s.downcase == other[attribute].to_s.downcase
end
end
| 27.898955 | 107 | 0.663794 |
ff2cdbacd038db99745f00ad6cefa8ea1fe3846c | 2,578 | # frozen_string_literal: true
require 'spec_helper'
describe GemUpdater::GemFile do
subject(:gemfile) { GemUpdater::GemFile.new }
let(:old_spec_set) do
[
Bundler::LazySpecification.new(
'gem_up_to_date', '0.1', 'ruby', 'gem_up_to_date_source'
),
Bundler::LazySpecification.new(
'gem_to_update', '1.5', 'ruby', 'gem_to_update_source'
)
]
end
let(:new_spec_set) do
[
Bundler::LazySpecification.new(
'gem_up_to_date', '0.1', 'ruby', 'gem_up_to_date_source'
),
Bundler::LazySpecification.new(
'gem_to_update', '2.3', 'ruby', 'gem_to_update_source'
)
]
end
before do
allow(Bundler).to receive_message_chain(:locked_gems, :specs) { old_spec_set }
allow(Bundler::CLI).to receive(:start)
end
describe '#update!' do
before do
allow(subject).to receive(:compute_changes)
subject.update!([])
end
it 'launches bundle update' do
expect(Bundler::CLI).to have_received(:start).with(['update'])
end
end
describe '#compute_changes' do
before do
allow(subject).to receive(:spec_sets_diff!)
allow(subject).to receive(:old_spec_set) { old_spec_set }
allow(subject).to receive(:new_spec_set) { new_spec_set }
subject.compute_changes
end
it 'gets specs sets' do
expect(subject).to have_received(:spec_sets_diff!)
end
it 'skips gems that were not updated' do
expect(subject.changes).to_not have_key(:gem_up_to_date)
end
it 'includes updated gems with old and new version number' do
expect(subject.changes['gem_to_update']).to eq(
versions: { old: '1.5', new: '2.3' }, source: 'gem_to_update_source'
)
end
end
describe '#spec_sets_diff!' do
before do
allow(subject).to receive(:reinitialize_spec_set!)
subject.send(:spec_sets_diff!)
end
it 'gets specs spet' do
expect(Bundler.locked_gems).to have_received(:specs).twice
end
end
describe '#spec_set' do
before do
subject.send(:spec_set)
end
it 'calls Bundler.locked_gems.specs' do
expect(Bundler).to have_received(:locked_gems)
expect(Bundler.locked_gems).to have_received(:specs)
end
end
describe '#reinitialize_spec_set!' do
before do
allow(Bundler).to receive(:remove_instance_variable)
subject.send(:reinitialize_spec_set!)
end
it 'reinitializes locked gems' do
expect(Bundler).to have_received(
:remove_instance_variable
).with('@locked_gems')
end
end
end
| 25.029126 | 82 | 0.657486 |
6aed105719972a632bd0e3ebc46d06224ca4cbe1 | 1,464 | require "rubygems"
require "bundler/setup"
require "ruby-transmitsms"
require "test/unit"
require "vcr"
VCR.configure do |c|
c.cassette_library_dir = "fixtures/vcr_cassettes"
c.hook_into :webmock
end
class NumbersApiTest < Test::Unit::TestCase
def setup()
@api = NumbersApi.new("15ad266c538fb36c4d90f01055aef494", "moose")
end
def test_get_number()
VCR.use_cassette("numbers_api_get_number") do
response = @api.get_number("+61422222222")
assert response.code == 200
assert response.body["number"] == 61422222222
assert response.body["auto_renew"] == true
assert response.body["error"]["code"] == "SUCCESS"
assert response.body["error"]["description"] == "OK"
end
end
def test_get_numbers()
VCR.use_cassette("numbers_api_get_numbers") do
response = @api.get_numbers("+61422222222")
assert response.code == 200
assert response.body["numbers"].length > 0
assert response.body["numbers_total"] == 4
assert response.body["error"]["code"] == "SUCCESS"
assert response.body["error"]["description"] == "OK"
end
end
def test_lease_number()
VCR.use_cassette("numbers_api_lease_number") do
response = @api.lease_number("0422222213")
assert response.code == 400
assert response.body["error"]["code"] == "FIELD_INVALID"
assert response.body["error"]["description"] == "This number is not available for lease."
end
end
end
| 27.111111 | 95 | 0.678279 |
0885954db005a3184def36651abdc953f9146e52 | 231 | class ApplicationException < StandardError
def initialize(status: 500, title: nil)
@status = status
@title = title
end
attr_reader :status
def title
@title ||= Rack::Utils::HTTP_STATUS_CODES[status]
end
end
| 17.769231 | 53 | 0.69697 |
61943512e0d33ca966a843b1eab0ece1f9c42ccc | 24,801 | # frozen_string_literal: true
# WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/version-3/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
module Aws::STS
# @api private
module ClientApi
include Seahorse::Model
AssumeRoleRequest = Shapes::StructureShape.new(name: 'AssumeRoleRequest')
AssumeRoleResponse = Shapes::StructureShape.new(name: 'AssumeRoleResponse')
AssumeRoleWithSAMLRequest = Shapes::StructureShape.new(name: 'AssumeRoleWithSAMLRequest')
AssumeRoleWithSAMLResponse = Shapes::StructureShape.new(name: 'AssumeRoleWithSAMLResponse')
AssumeRoleWithWebIdentityRequest = Shapes::StructureShape.new(name: 'AssumeRoleWithWebIdentityRequest')
AssumeRoleWithWebIdentityResponse = Shapes::StructureShape.new(name: 'AssumeRoleWithWebIdentityResponse')
AssumedRoleUser = Shapes::StructureShape.new(name: 'AssumedRoleUser')
Audience = Shapes::StringShape.new(name: 'Audience')
Credentials = Shapes::StructureShape.new(name: 'Credentials')
DecodeAuthorizationMessageRequest = Shapes::StructureShape.new(name: 'DecodeAuthorizationMessageRequest')
DecodeAuthorizationMessageResponse = Shapes::StructureShape.new(name: 'DecodeAuthorizationMessageResponse')
ExpiredTokenException = Shapes::StructureShape.new(name: 'ExpiredTokenException')
FederatedUser = Shapes::StructureShape.new(name: 'FederatedUser')
GetAccessKeyInfoRequest = Shapes::StructureShape.new(name: 'GetAccessKeyInfoRequest')
GetAccessKeyInfoResponse = Shapes::StructureShape.new(name: 'GetAccessKeyInfoResponse')
GetCallerIdentityRequest = Shapes::StructureShape.new(name: 'GetCallerIdentityRequest')
GetCallerIdentityResponse = Shapes::StructureShape.new(name: 'GetCallerIdentityResponse')
GetFederationTokenRequest = Shapes::StructureShape.new(name: 'GetFederationTokenRequest')
GetFederationTokenResponse = Shapes::StructureShape.new(name: 'GetFederationTokenResponse')
GetSessionTokenRequest = Shapes::StructureShape.new(name: 'GetSessionTokenRequest')
GetSessionTokenResponse = Shapes::StructureShape.new(name: 'GetSessionTokenResponse')
IDPCommunicationErrorException = Shapes::StructureShape.new(name: 'IDPCommunicationErrorException')
IDPRejectedClaimException = Shapes::StructureShape.new(name: 'IDPRejectedClaimException')
InvalidAuthorizationMessageException = Shapes::StructureShape.new(name: 'InvalidAuthorizationMessageException')
InvalidIdentityTokenException = Shapes::StructureShape.new(name: 'InvalidIdentityTokenException')
Issuer = Shapes::StringShape.new(name: 'Issuer')
MalformedPolicyDocumentException = Shapes::StructureShape.new(name: 'MalformedPolicyDocumentException')
NameQualifier = Shapes::StringShape.new(name: 'NameQualifier')
PackedPolicyTooLargeException = Shapes::StructureShape.new(name: 'PackedPolicyTooLargeException')
PolicyDescriptorType = Shapes::StructureShape.new(name: 'PolicyDescriptorType')
RegionDisabledException = Shapes::StructureShape.new(name: 'RegionDisabledException')
SAMLAssertionType = Shapes::StringShape.new(name: 'SAMLAssertionType')
Subject = Shapes::StringShape.new(name: 'Subject')
SubjectType = Shapes::StringShape.new(name: 'SubjectType')
Tag = Shapes::StructureShape.new(name: 'Tag')
accessKeyIdType = Shapes::StringShape.new(name: 'accessKeyIdType')
accessKeySecretType = Shapes::StringShape.new(name: 'accessKeySecretType')
accountType = Shapes::StringShape.new(name: 'accountType')
arnType = Shapes::StringShape.new(name: 'arnType')
assumedRoleIdType = Shapes::StringShape.new(name: 'assumedRoleIdType')
clientTokenType = Shapes::StringShape.new(name: 'clientTokenType')
dateType = Shapes::TimestampShape.new(name: 'dateType')
decodedMessageType = Shapes::StringShape.new(name: 'decodedMessageType')
durationSecondsType = Shapes::IntegerShape.new(name: 'durationSecondsType')
encodedMessageType = Shapes::StringShape.new(name: 'encodedMessageType')
expiredIdentityTokenMessage = Shapes::StringShape.new(name: 'expiredIdentityTokenMessage')
externalIdType = Shapes::StringShape.new(name: 'externalIdType')
federatedIdType = Shapes::StringShape.new(name: 'federatedIdType')
idpCommunicationErrorMessage = Shapes::StringShape.new(name: 'idpCommunicationErrorMessage')
idpRejectedClaimMessage = Shapes::StringShape.new(name: 'idpRejectedClaimMessage')
invalidAuthorizationMessage = Shapes::StringShape.new(name: 'invalidAuthorizationMessage')
invalidIdentityTokenMessage = Shapes::StringShape.new(name: 'invalidIdentityTokenMessage')
malformedPolicyDocumentMessage = Shapes::StringShape.new(name: 'malformedPolicyDocumentMessage')
nonNegativeIntegerType = Shapes::IntegerShape.new(name: 'nonNegativeIntegerType')
packedPolicyTooLargeMessage = Shapes::StringShape.new(name: 'packedPolicyTooLargeMessage')
policyDescriptorListType = Shapes::ListShape.new(name: 'policyDescriptorListType')
regionDisabledMessage = Shapes::StringShape.new(name: 'regionDisabledMessage')
roleDurationSecondsType = Shapes::IntegerShape.new(name: 'roleDurationSecondsType')
roleSessionNameType = Shapes::StringShape.new(name: 'roleSessionNameType')
serialNumberType = Shapes::StringShape.new(name: 'serialNumberType')
sessionPolicyDocumentType = Shapes::StringShape.new(name: 'sessionPolicyDocumentType')
sourceIdentityType = Shapes::StringShape.new(name: 'sourceIdentityType')
tagKeyListType = Shapes::ListShape.new(name: 'tagKeyListType')
tagKeyType = Shapes::StringShape.new(name: 'tagKeyType')
tagListType = Shapes::ListShape.new(name: 'tagListType')
tagValueType = Shapes::StringShape.new(name: 'tagValueType')
tokenCodeType = Shapes::StringShape.new(name: 'tokenCodeType')
tokenType = Shapes::StringShape.new(name: 'tokenType')
urlType = Shapes::StringShape.new(name: 'urlType')
userIdType = Shapes::StringShape.new(name: 'userIdType')
userNameType = Shapes::StringShape.new(name: 'userNameType')
webIdentitySubjectType = Shapes::StringShape.new(name: 'webIdentitySubjectType')
AssumeRoleRequest.add_member(:role_arn, Shapes::ShapeRef.new(shape: arnType, required: true, location_name: "RoleArn"))
AssumeRoleRequest.add_member(:role_session_name, Shapes::ShapeRef.new(shape: roleSessionNameType, required: true, location_name: "RoleSessionName"))
AssumeRoleRequest.add_member(:policy_arns, Shapes::ShapeRef.new(shape: policyDescriptorListType, location_name: "PolicyArns"))
AssumeRoleRequest.add_member(:policy, Shapes::ShapeRef.new(shape: sessionPolicyDocumentType, location_name: "Policy"))
AssumeRoleRequest.add_member(:duration_seconds, Shapes::ShapeRef.new(shape: roleDurationSecondsType, location_name: "DurationSeconds"))
AssumeRoleRequest.add_member(:tags, Shapes::ShapeRef.new(shape: tagListType, location_name: "Tags"))
AssumeRoleRequest.add_member(:transitive_tag_keys, Shapes::ShapeRef.new(shape: tagKeyListType, location_name: "TransitiveTagKeys"))
AssumeRoleRequest.add_member(:external_id, Shapes::ShapeRef.new(shape: externalIdType, location_name: "ExternalId"))
AssumeRoleRequest.add_member(:serial_number, Shapes::ShapeRef.new(shape: serialNumberType, location_name: "SerialNumber"))
AssumeRoleRequest.add_member(:token_code, Shapes::ShapeRef.new(shape: tokenCodeType, location_name: "TokenCode"))
AssumeRoleRequest.add_member(:source_identity, Shapes::ShapeRef.new(shape: sourceIdentityType, location_name: "SourceIdentity"))
AssumeRoleRequest.struct_class = Types::AssumeRoleRequest
AssumeRoleResponse.add_member(:credentials, Shapes::ShapeRef.new(shape: Credentials, location_name: "Credentials"))
AssumeRoleResponse.add_member(:assumed_role_user, Shapes::ShapeRef.new(shape: AssumedRoleUser, location_name: "AssumedRoleUser"))
AssumeRoleResponse.add_member(:packed_policy_size, Shapes::ShapeRef.new(shape: nonNegativeIntegerType, location_name: "PackedPolicySize"))
AssumeRoleResponse.add_member(:source_identity, Shapes::ShapeRef.new(shape: sourceIdentityType, location_name: "SourceIdentity"))
AssumeRoleResponse.struct_class = Types::AssumeRoleResponse
AssumeRoleWithSAMLRequest.add_member(:role_arn, Shapes::ShapeRef.new(shape: arnType, required: true, location_name: "RoleArn"))
AssumeRoleWithSAMLRequest.add_member(:principal_arn, Shapes::ShapeRef.new(shape: arnType, required: true, location_name: "PrincipalArn"))
AssumeRoleWithSAMLRequest.add_member(:saml_assertion, Shapes::ShapeRef.new(shape: SAMLAssertionType, required: true, location_name: "SAMLAssertion"))
AssumeRoleWithSAMLRequest.add_member(:policy_arns, Shapes::ShapeRef.new(shape: policyDescriptorListType, location_name: "PolicyArns"))
AssumeRoleWithSAMLRequest.add_member(:policy, Shapes::ShapeRef.new(shape: sessionPolicyDocumentType, location_name: "Policy"))
AssumeRoleWithSAMLRequest.add_member(:duration_seconds, Shapes::ShapeRef.new(shape: roleDurationSecondsType, location_name: "DurationSeconds"))
AssumeRoleWithSAMLRequest.struct_class = Types::AssumeRoleWithSAMLRequest
AssumeRoleWithSAMLResponse.add_member(:credentials, Shapes::ShapeRef.new(shape: Credentials, location_name: "Credentials"))
AssumeRoleWithSAMLResponse.add_member(:assumed_role_user, Shapes::ShapeRef.new(shape: AssumedRoleUser, location_name: "AssumedRoleUser"))
AssumeRoleWithSAMLResponse.add_member(:packed_policy_size, Shapes::ShapeRef.new(shape: nonNegativeIntegerType, location_name: "PackedPolicySize"))
AssumeRoleWithSAMLResponse.add_member(:subject, Shapes::ShapeRef.new(shape: Subject, location_name: "Subject"))
AssumeRoleWithSAMLResponse.add_member(:subject_type, Shapes::ShapeRef.new(shape: SubjectType, location_name: "SubjectType"))
AssumeRoleWithSAMLResponse.add_member(:issuer, Shapes::ShapeRef.new(shape: Issuer, location_name: "Issuer"))
AssumeRoleWithSAMLResponse.add_member(:audience, Shapes::ShapeRef.new(shape: Audience, location_name: "Audience"))
AssumeRoleWithSAMLResponse.add_member(:name_qualifier, Shapes::ShapeRef.new(shape: NameQualifier, location_name: "NameQualifier"))
AssumeRoleWithSAMLResponse.add_member(:source_identity, Shapes::ShapeRef.new(shape: sourceIdentityType, location_name: "SourceIdentity"))
AssumeRoleWithSAMLResponse.struct_class = Types::AssumeRoleWithSAMLResponse
AssumeRoleWithWebIdentityRequest.add_member(:role_arn, Shapes::ShapeRef.new(shape: arnType, required: true, location_name: "RoleArn"))
AssumeRoleWithWebIdentityRequest.add_member(:role_session_name, Shapes::ShapeRef.new(shape: roleSessionNameType, required: true, location_name: "RoleSessionName"))
AssumeRoleWithWebIdentityRequest.add_member(:web_identity_token, Shapes::ShapeRef.new(shape: clientTokenType, required: true, location_name: "WebIdentityToken"))
AssumeRoleWithWebIdentityRequest.add_member(:provider_id, Shapes::ShapeRef.new(shape: urlType, location_name: "ProviderId"))
AssumeRoleWithWebIdentityRequest.add_member(:policy_arns, Shapes::ShapeRef.new(shape: policyDescriptorListType, location_name: "PolicyArns"))
AssumeRoleWithWebIdentityRequest.add_member(:policy, Shapes::ShapeRef.new(shape: sessionPolicyDocumentType, location_name: "Policy"))
AssumeRoleWithWebIdentityRequest.add_member(:duration_seconds, Shapes::ShapeRef.new(shape: roleDurationSecondsType, location_name: "DurationSeconds"))
AssumeRoleWithWebIdentityRequest.struct_class = Types::AssumeRoleWithWebIdentityRequest
AssumeRoleWithWebIdentityResponse.add_member(:credentials, Shapes::ShapeRef.new(shape: Credentials, location_name: "Credentials"))
AssumeRoleWithWebIdentityResponse.add_member(:subject_from_web_identity_token, Shapes::ShapeRef.new(shape: webIdentitySubjectType, location_name: "SubjectFromWebIdentityToken"))
AssumeRoleWithWebIdentityResponse.add_member(:assumed_role_user, Shapes::ShapeRef.new(shape: AssumedRoleUser, location_name: "AssumedRoleUser"))
AssumeRoleWithWebIdentityResponse.add_member(:packed_policy_size, Shapes::ShapeRef.new(shape: nonNegativeIntegerType, location_name: "PackedPolicySize"))
AssumeRoleWithWebIdentityResponse.add_member(:provider, Shapes::ShapeRef.new(shape: Issuer, location_name: "Provider"))
AssumeRoleWithWebIdentityResponse.add_member(:audience, Shapes::ShapeRef.new(shape: Audience, location_name: "Audience"))
AssumeRoleWithWebIdentityResponse.add_member(:source_identity, Shapes::ShapeRef.new(shape: sourceIdentityType, location_name: "SourceIdentity"))
AssumeRoleWithWebIdentityResponse.struct_class = Types::AssumeRoleWithWebIdentityResponse
AssumedRoleUser.add_member(:assumed_role_id, Shapes::ShapeRef.new(shape: assumedRoleIdType, required: true, location_name: "AssumedRoleId"))
AssumedRoleUser.add_member(:arn, Shapes::ShapeRef.new(shape: arnType, required: true, location_name: "Arn"))
AssumedRoleUser.struct_class = Types::AssumedRoleUser
Credentials.add_member(:access_key_id, Shapes::ShapeRef.new(shape: accessKeyIdType, required: true, location_name: "AccessKeyId"))
Credentials.add_member(:secret_access_key, Shapes::ShapeRef.new(shape: accessKeySecretType, required: true, location_name: "SecretAccessKey"))
Credentials.add_member(:session_token, Shapes::ShapeRef.new(shape: tokenType, required: true, location_name: "SessionToken"))
Credentials.add_member(:expiration, Shapes::ShapeRef.new(shape: dateType, required: true, location_name: "Expiration"))
Credentials.struct_class = Types::Credentials
DecodeAuthorizationMessageRequest.add_member(:encoded_message, Shapes::ShapeRef.new(shape: encodedMessageType, required: true, location_name: "EncodedMessage"))
DecodeAuthorizationMessageRequest.struct_class = Types::DecodeAuthorizationMessageRequest
DecodeAuthorizationMessageResponse.add_member(:decoded_message, Shapes::ShapeRef.new(shape: decodedMessageType, location_name: "DecodedMessage"))
DecodeAuthorizationMessageResponse.struct_class = Types::DecodeAuthorizationMessageResponse
ExpiredTokenException.add_member(:message, Shapes::ShapeRef.new(shape: expiredIdentityTokenMessage, location_name: "message"))
ExpiredTokenException.struct_class = Types::ExpiredTokenException
FederatedUser.add_member(:federated_user_id, Shapes::ShapeRef.new(shape: federatedIdType, required: true, location_name: "FederatedUserId"))
FederatedUser.add_member(:arn, Shapes::ShapeRef.new(shape: arnType, required: true, location_name: "Arn"))
FederatedUser.struct_class = Types::FederatedUser
GetAccessKeyInfoRequest.add_member(:access_key_id, Shapes::ShapeRef.new(shape: accessKeyIdType, required: true, location_name: "AccessKeyId"))
GetAccessKeyInfoRequest.struct_class = Types::GetAccessKeyInfoRequest
GetAccessKeyInfoResponse.add_member(:account, Shapes::ShapeRef.new(shape: accountType, location_name: "Account"))
GetAccessKeyInfoResponse.struct_class = Types::GetAccessKeyInfoResponse
GetCallerIdentityRequest.struct_class = Types::GetCallerIdentityRequest
GetCallerIdentityResponse.add_member(:user_id, Shapes::ShapeRef.new(shape: userIdType, location_name: "UserId"))
GetCallerIdentityResponse.add_member(:account, Shapes::ShapeRef.new(shape: accountType, location_name: "Account"))
GetCallerIdentityResponse.add_member(:arn, Shapes::ShapeRef.new(shape: arnType, location_name: "Arn"))
GetCallerIdentityResponse.struct_class = Types::GetCallerIdentityResponse
GetFederationTokenRequest.add_member(:name, Shapes::ShapeRef.new(shape: userNameType, required: true, location_name: "Name"))
GetFederationTokenRequest.add_member(:policy, Shapes::ShapeRef.new(shape: sessionPolicyDocumentType, location_name: "Policy"))
GetFederationTokenRequest.add_member(:policy_arns, Shapes::ShapeRef.new(shape: policyDescriptorListType, location_name: "PolicyArns"))
GetFederationTokenRequest.add_member(:duration_seconds, Shapes::ShapeRef.new(shape: durationSecondsType, location_name: "DurationSeconds"))
GetFederationTokenRequest.add_member(:tags, Shapes::ShapeRef.new(shape: tagListType, location_name: "Tags"))
GetFederationTokenRequest.struct_class = Types::GetFederationTokenRequest
GetFederationTokenResponse.add_member(:credentials, Shapes::ShapeRef.new(shape: Credentials, location_name: "Credentials"))
GetFederationTokenResponse.add_member(:federated_user, Shapes::ShapeRef.new(shape: FederatedUser, location_name: "FederatedUser"))
GetFederationTokenResponse.add_member(:packed_policy_size, Shapes::ShapeRef.new(shape: nonNegativeIntegerType, location_name: "PackedPolicySize"))
GetFederationTokenResponse.struct_class = Types::GetFederationTokenResponse
GetSessionTokenRequest.add_member(:duration_seconds, Shapes::ShapeRef.new(shape: durationSecondsType, location_name: "DurationSeconds"))
GetSessionTokenRequest.add_member(:serial_number, Shapes::ShapeRef.new(shape: serialNumberType, location_name: "SerialNumber"))
GetSessionTokenRequest.add_member(:token_code, Shapes::ShapeRef.new(shape: tokenCodeType, location_name: "TokenCode"))
GetSessionTokenRequest.struct_class = Types::GetSessionTokenRequest
GetSessionTokenResponse.add_member(:credentials, Shapes::ShapeRef.new(shape: Credentials, location_name: "Credentials"))
GetSessionTokenResponse.struct_class = Types::GetSessionTokenResponse
IDPCommunicationErrorException.add_member(:message, Shapes::ShapeRef.new(shape: idpCommunicationErrorMessage, location_name: "message"))
IDPCommunicationErrorException.struct_class = Types::IDPCommunicationErrorException
IDPRejectedClaimException.add_member(:message, Shapes::ShapeRef.new(shape: idpRejectedClaimMessage, location_name: "message"))
IDPRejectedClaimException.struct_class = Types::IDPRejectedClaimException
InvalidAuthorizationMessageException.add_member(:message, Shapes::ShapeRef.new(shape: invalidAuthorizationMessage, location_name: "message"))
InvalidAuthorizationMessageException.struct_class = Types::InvalidAuthorizationMessageException
InvalidIdentityTokenException.add_member(:message, Shapes::ShapeRef.new(shape: invalidIdentityTokenMessage, location_name: "message"))
InvalidIdentityTokenException.struct_class = Types::InvalidIdentityTokenException
MalformedPolicyDocumentException.add_member(:message, Shapes::ShapeRef.new(shape: malformedPolicyDocumentMessage, location_name: "message"))
MalformedPolicyDocumentException.struct_class = Types::MalformedPolicyDocumentException
PackedPolicyTooLargeException.add_member(:message, Shapes::ShapeRef.new(shape: packedPolicyTooLargeMessage, location_name: "message"))
PackedPolicyTooLargeException.struct_class = Types::PackedPolicyTooLargeException
PolicyDescriptorType.add_member(:arn, Shapes::ShapeRef.new(shape: arnType, location_name: "arn"))
PolicyDescriptorType.struct_class = Types::PolicyDescriptorType
RegionDisabledException.add_member(:message, Shapes::ShapeRef.new(shape: regionDisabledMessage, location_name: "message"))
RegionDisabledException.struct_class = Types::RegionDisabledException
Tag.add_member(:key, Shapes::ShapeRef.new(shape: tagKeyType, required: true, location_name: "Key"))
Tag.add_member(:value, Shapes::ShapeRef.new(shape: tagValueType, required: true, location_name: "Value"))
Tag.struct_class = Types::Tag
policyDescriptorListType.member = Shapes::ShapeRef.new(shape: PolicyDescriptorType)
tagKeyListType.member = Shapes::ShapeRef.new(shape: tagKeyType)
tagListType.member = Shapes::ShapeRef.new(shape: Tag)
# @api private
API = Seahorse::Model::Api.new.tap do |api|
api.version = "2011-06-15"
api.metadata = {
"apiVersion" => "2011-06-15",
"endpointPrefix" => "sts",
"globalEndpoint" => "sts.amazonaws.com",
"protocol" => "query",
"serviceAbbreviation" => "AWS STS",
"serviceFullName" => "AWS Security Token Service",
"serviceId" => "STS",
"signatureVersion" => "v4",
"uid" => "sts-2011-06-15",
"xmlNamespace" => "https://sts.amazonaws.com/doc/2011-06-15/",
}
api.add_operation(:assume_role, Seahorse::Model::Operation.new.tap do |o|
o.name = "AssumeRole"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: AssumeRoleRequest)
o.output = Shapes::ShapeRef.new(shape: AssumeRoleResponse)
o.errors << Shapes::ShapeRef.new(shape: MalformedPolicyDocumentException)
o.errors << Shapes::ShapeRef.new(shape: PackedPolicyTooLargeException)
o.errors << Shapes::ShapeRef.new(shape: RegionDisabledException)
o.errors << Shapes::ShapeRef.new(shape: ExpiredTokenException)
end)
api.add_operation(:assume_role_with_saml, Seahorse::Model::Operation.new.tap do |o|
o.name = "AssumeRoleWithSAML"
o.http_method = "POST"
o.http_request_uri = "/"
o['authtype'] = "none"
o.input = Shapes::ShapeRef.new(shape: AssumeRoleWithSAMLRequest)
o.output = Shapes::ShapeRef.new(shape: AssumeRoleWithSAMLResponse)
o.errors << Shapes::ShapeRef.new(shape: MalformedPolicyDocumentException)
o.errors << Shapes::ShapeRef.new(shape: PackedPolicyTooLargeException)
o.errors << Shapes::ShapeRef.new(shape: IDPRejectedClaimException)
o.errors << Shapes::ShapeRef.new(shape: InvalidIdentityTokenException)
o.errors << Shapes::ShapeRef.new(shape: ExpiredTokenException)
o.errors << Shapes::ShapeRef.new(shape: RegionDisabledException)
end)
api.add_operation(:assume_role_with_web_identity, Seahorse::Model::Operation.new.tap do |o|
o.name = "AssumeRoleWithWebIdentity"
o.http_method = "POST"
o.http_request_uri = "/"
o['authtype'] = "none"
o.input = Shapes::ShapeRef.new(shape: AssumeRoleWithWebIdentityRequest)
o.output = Shapes::ShapeRef.new(shape: AssumeRoleWithWebIdentityResponse)
o.errors << Shapes::ShapeRef.new(shape: MalformedPolicyDocumentException)
o.errors << Shapes::ShapeRef.new(shape: PackedPolicyTooLargeException)
o.errors << Shapes::ShapeRef.new(shape: IDPRejectedClaimException)
o.errors << Shapes::ShapeRef.new(shape: IDPCommunicationErrorException)
o.errors << Shapes::ShapeRef.new(shape: InvalidIdentityTokenException)
o.errors << Shapes::ShapeRef.new(shape: ExpiredTokenException)
o.errors << Shapes::ShapeRef.new(shape: RegionDisabledException)
end)
api.add_operation(:decode_authorization_message, Seahorse::Model::Operation.new.tap do |o|
o.name = "DecodeAuthorizationMessage"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: DecodeAuthorizationMessageRequest)
o.output = Shapes::ShapeRef.new(shape: DecodeAuthorizationMessageResponse)
o.errors << Shapes::ShapeRef.new(shape: InvalidAuthorizationMessageException)
end)
api.add_operation(:get_access_key_info, Seahorse::Model::Operation.new.tap do |o|
o.name = "GetAccessKeyInfo"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: GetAccessKeyInfoRequest)
o.output = Shapes::ShapeRef.new(shape: GetAccessKeyInfoResponse)
end)
api.add_operation(:get_caller_identity, Seahorse::Model::Operation.new.tap do |o|
o.name = "GetCallerIdentity"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: GetCallerIdentityRequest)
o.output = Shapes::ShapeRef.new(shape: GetCallerIdentityResponse)
end)
api.add_operation(:get_federation_token, Seahorse::Model::Operation.new.tap do |o|
o.name = "GetFederationToken"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: GetFederationTokenRequest)
o.output = Shapes::ShapeRef.new(shape: GetFederationTokenResponse)
o.errors << Shapes::ShapeRef.new(shape: MalformedPolicyDocumentException)
o.errors << Shapes::ShapeRef.new(shape: PackedPolicyTooLargeException)
o.errors << Shapes::ShapeRef.new(shape: RegionDisabledException)
end)
api.add_operation(:get_session_token, Seahorse::Model::Operation.new.tap do |o|
o.name = "GetSessionToken"
o.http_method = "POST"
o.http_request_uri = "/"
o.input = Shapes::ShapeRef.new(shape: GetSessionTokenRequest)
o.output = Shapes::ShapeRef.new(shape: GetSessionTokenResponse)
o.errors << Shapes::ShapeRef.new(shape: RegionDisabledException)
end)
end
end
end
| 71.886957 | 181 | 0.779646 |
0325892a38c02800e5336e57f72bcb8246022bdc | 6,197 | require 'formula'
class Gcc46 < Formula
def arch
if Hardware::CPU.type == :intel
if MacOS.prefer_64_bit?
'x86_64'
else
'i686'
end
elsif Hardware::CPU.type == :ppc
if MacOS.prefer_64_bit?
'powerpc64'
else
'powerpc'
end
end
end
def osmajor
`uname -r`.chomp
end
homepage 'https://gcc.gnu.org'
url 'http://ftpmirror.gnu.org/gcc/gcc-4.6.4/gcc-4.6.4.tar.bz2'
mirror 'https://ftp.gnu.org/gnu/gcc/gcc-4.6.4/gcc-4.6.4.tar.bz2'
sha1 '63933a8a5cf725626585dbba993c8b0f6db1335d'
option 'enable-fortran', 'Build the gfortran compiler'
option 'enable-java', 'Build the gcj compiler'
option 'enable-all-languages', 'Enable all compilers and languages, except Ada'
option 'enable-nls', 'Build with native language support (localization)'
option 'enable-profiled-build', 'Make use of profile guided optimization when bootstrapping GCC'
# enabling multilib on a host that can't run 64-bit results in build failures
option 'disable-multilib', 'Build without multilib support' if MacOS.prefer_64_bit?
depends_on 'gmp4'
depends_on 'libmpc08'
depends_on 'mpfr2'
depends_on 'ppl011'
depends_on 'cloog-ppl015'
depends_on 'ecj' if build.include? 'enable-java' or build.include? 'enable-all-languages'
fails_with :llvm
# GCC bootstraps itself, so it is OK to have an incompatible C++ stdlib
cxxstdlib_check :skip
# Fix 10.10 issues: https://gcc.gnu.org/viewcvs/gcc?view=revision&revision=215251
patch :p0 do
url "https://trac.macports.org/export/126996/trunk/dports/lang/gcc48/files/patch-10.10.diff"
sha1 "4fb0ededa7b8105c3bdffa15469b589b272b7788"
end
def install
# GCC will suffer build errors if forced to use a particular linker.
ENV.delete 'LD'
if build.include? 'enable-all-languages'
# Everything but Ada, which requires a pre-existing GCC Ada compiler
# (gnat) to bootstrap. GCC 4.6.0 add go as a language option, but it is
# currently only compilable on Linux.
languages = %w[c c++ fortran java objc obj-c++]
else
# C, C++, ObjC compilers are always built
languages = %w[c c++ objc obj-c++]
languages << 'fortran' if build.include? 'enable-fortran'
languages << 'java' if build.include? 'enable-java'
end
version_suffix = version.to_s.slice(/\d\.\d/)
args = [
"--build=#{arch}-apple-darwin#{osmajor}",
"--prefix=#{prefix}",
"--enable-languages=#{languages.join(',')}",
# Make most executables versioned to avoid conflicts.
"--program-suffix=-#{version_suffix}",
"--with-gmp=#{Formula["gmp4"].opt_prefix}",
"--with-mpfr=#{Formula["mpfr2"].opt_prefix}",
"--with-mpc=#{Formula["libmpc08"].opt_prefix}",
"--with-ppl=#{Formula["ppl011"].opt_prefix}",
"--with-cloog=#{Formula["cloog-ppl015"].opt_prefix}",
"--with-system-zlib",
# This ensures lib, libexec, include are sandboxed so that they
# don't wander around telling little children there is no Santa
# Claus.
"--enable-version-specific-runtime-libs",
"--enable-libstdcxx-time=yes",
"--enable-stage1-checking",
"--enable-checking=release",
"--enable-lto",
# A no-op unless --HEAD is built because in head warnings will
# raise errors. But still a good idea to include.
"--disable-werror",
"--with-pkgversion=Homebrew #{name} #{pkg_version} #{build.used_options*" "}".strip,
"--with-bugurl=https://github.com/Homebrew/homebrew-versions/issues",
]
# "Building GCC with plugin support requires a host that supports
# -fPIC, -shared, -ldl and -rdynamic."
args << "--enable-plugin" if MacOS.version > :tiger
# Otherwise make fails during comparison at stage 3
# See: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=45248
args << '--with-dwarf2' if MacOS.version < :leopard
args << '--disable-nls' unless build.include? 'enable-nls'
if build.include? 'enable-java' or build.include? 'enable-all-languages'
args << "--with-ecj-jar=#{Formula["ecj"].opt_prefix}/share/java/ecj.jar"
end
if !MacOS.prefer_64_bit? || build.include?('disable-multilib')
args << '--disable-multilib'
else
args << '--enable-multilib'
end
mkdir 'build' do
unless MacOS::CLT.installed?
# For Xcode-only systems, we need to tell the sysroot path.
# 'native-system-header's will be appended
args << "--with-native-system-header-dir=/usr/include"
args << "--with-sysroot=#{MacOS.sdk_path}"
end
system '../configure', *args
if build.include? 'enable-profiled-build'
# Takes longer to build, may bug out. Provided for those who want to
# optimise all the way to 11.
system 'make profiledbootstrap'
else
system 'make bootstrap'
end
# At this point `make check` could be invoked to run the testsuite. The
# deja-gnu and autogen formulae must be installed in order to do this.
system 'make install'
end
# Handle conflicts between GCC formulae.
# Remove libffi stuff, which is not needed after GCC is built.
Dir.glob(prefix/"**/libffi.*") { |file| File.delete file }
# Rename libiberty.a.
Dir.glob(prefix/"**/libiberty.*") { |file| add_suffix file, version_suffix }
# Rename man7.
Dir.glob(man7/"*.7") { |file| add_suffix file, version_suffix }
# Even when suffixes are appended, the info pages conflict when
# install-info is run. TODO fix this.
info.rmtree
# Rename java properties
if build.include? 'enable-java' or build.include? 'enable-all-languages'
config_files = [
"#{lib}/logging.properties",
"#{lib}/security/classpath.security",
"#{lib}/i386/logging.properties",
"#{lib}/i386/security/classpath.security"
]
config_files.each do |file|
add_suffix file, version_suffix if File.exist? file
end
end
end
def add_suffix file, suffix
dir = File.dirname(file)
ext = File.extname(file)
base = File.basename(file, ext)
File.rename file, "#{dir}/#{base}-#{suffix}#{ext}"
end
end
| 34.049451 | 98 | 0.650799 |
6299e58f6ea6753791ecd8477afe2ad9baff27af | 785 | # frozen_string_literal: true
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
module Google
module Cloud
module Monitoring
module V3
VERSION = "0.3.0"
end
end
end
end
| 27.068966 | 74 | 0.732484 |
39d7207344bb2d9533f399988c61cfb73c2ee71b | 1,049 | require 'ruby/reflection/support/shift_reset'
require 'continuation' unless defined? callcc
module Ruby
class Reflection
class ThreadMirror < ObjectMirror
include AbstractReflection::ThreadMirror
include ShiftReset
reflect! Thread
Frame = Struct.new :method, :index, :file, :line, :thread
def status
s = @subject.status
if s.respond_to? :to_str
s.to_str
elsif s.nil?
"aborted"
else
"dead"
end
end
def run
@subject.run
end
def stack
if bt = @subject.backtrace
bt.each_with_index.collect do |str, idx|
file, line, method_spec = str.split(':')
method_spec =~ /\`([^']+)'/
method = $1
frame = Frame.new method, idx, file, line, self
reflection.reflect frame
end
else
[]
end
end
def return_value
return nil if @subject.alive?
@subject.value
end
end
end
end
| 21.854167 | 63 | 0.544328 |
bf124171e5b2de8fae9f9c48b1b2c512f31d0e3d | 18,811 | # Authorization
require File.dirname(__FILE__) + '/reader.rb'
require "set"
module Authorization
# An exception raised if anything goes wrong in the Authorization realm
class AuthorizationError < StandardError ; end
# NotAuthorized is raised if the current user is not allowed to perform
# the given operation possibly on a specific object.
class NotAuthorized < AuthorizationError ; end
# AttributeAuthorizationError is more specific than NotAuthorized, signalling
# that the access was denied on the grounds of attribute conditions.
class AttributeAuthorizationError < NotAuthorized ; end
# AuthorizationUsageError is used whenever a situation is encountered
# in which the application misused the plugin. That is, if, e.g.,
# authorization rules may not be evaluated.
class AuthorizationUsageError < AuthorizationError ; end
# NilAttributeValueError is raised by Attribute#validate? when it hits a nil attribute value.
# The exception is raised to ensure that the entire rule is invalidated.
class NilAttributeValueError < AuthorizationError; end
AUTH_DSL_FILE = "#{RAILS_ROOT}/config/authorization_rules.rb"
# Controller-independent method for retrieving the current user.
# Needed for model security where the current controller is not available.
def self.current_user
Thread.current["current_user"] || GuestUser.new
end
# Controller-independent method for setting the current user.
def self.current_user=(user)
Thread.current["current_user"] = user
end
@@ignore_access_control = false
# For use in test cases only
def self.ignore_access_control (state = nil) # :nodoc:
false
end
def self.activate_authorization_rules_browser? # :nodoc:
::RAILS_ENV == 'development'
end
# Authorization::Engine implements the reference monitor. It may be used
# for querying the permission and retrieving obligations under which
# a certain privilege is granted for the current user.
#
class Engine
attr_reader :roles, :role_titles, :role_descriptions, :privileges,
:privilege_hierarchy, :auth_rules, :role_hierarchy, :rev_priv_hierarchy
# If +reader+ is not given, a new one is created with the default
# authorization configuration of +AUTH_DSL_FILE+. If given, may be either
# a Reader object or a path to a configuration file.
def initialize (reader = nil)
if reader.nil?
begin
reader = Reader::DSLReader.load(AUTH_DSL_FILE)
rescue SystemCallError
reader = Reader::DSLReader.new
end
elsif reader.is_a?(String)
reader = Reader::DSLReader.load(reader)
end
@privileges = reader.privileges_reader.privileges
# {priv => [[priv, ctx],...]}
@privilege_hierarchy = reader.privileges_reader.privilege_hierarchy
@auth_rules = reader.auth_rules_reader.auth_rules
@roles = reader.auth_rules_reader.roles
@role_hierarchy = reader.auth_rules_reader.role_hierarchy
@role_titles = reader.auth_rules_reader.role_titles
@role_descriptions = reader.auth_rules_reader.role_descriptions
# {[priv, ctx] => [priv, ...]}
@rev_priv_hierarchy = {}
@privilege_hierarchy.each do |key, value|
value.each do |val|
@rev_priv_hierarchy[val] ||= []
@rev_priv_hierarchy[val] << key
end
end
end
# Returns true if privilege is met by the current user. Raises
# AuthorizationError otherwise. +privilege+ may be given with or
# without context. In the latter case, the :+context+ option is
# required.
#
# Options:
# [:+context+]
# The context part of the privilege.
# Defaults either to the +table_name+ of the given :+object+, if given.
# That is, either :+users+ for :+object+ of type User.
# Raises AuthorizationUsageError if
# context is missing and not to be infered.
# [:+object+] An context object to test attribute checks against.
# [:+skip_attribute_test+]
# Skips those attribute checks in the
# authorization rules. Defaults to false.
# [:+user+]
# The user to check the authorization for.
# Defaults to Authorization#current_user.
#
def permit! (privilege, options = {})
return true if Authorization.ignore_access_control
options = {
:object => nil,
:skip_attribute_test => false,
:context => nil
}.merge(options)
# Make sure we're handling all privileges as symbols.
privilege = privilege.is_a?( Array ) ?
privilege.flatten.collect { |priv| priv.to_sym } :
privilege.to_sym
#
# If the object responds to :new, we're probably working with an association collection. Use
# 'new' to leverage ActiveRecord's builder functionality to obtain an object against which we
# can check permissions.
#
# Example: permit!( :edit, user.posts )
#
if options[:object].respond_to?( :new )
options[:object] = options[:object].new
end
options[:context] ||= options[:object] && options[:object].class.table_name.to_sym rescue NoMethodError
user, roles, privileges = user_roles_privleges_from_options(privilege, options)
# find a authorization rule that matches for at least one of the roles and
# at least one of the given privileges
attr_validator = AttributeValidator.new(self, user, options[:object])
rules = matching_auth_rules(roles, privileges, options[:context])
if rules.empty?
raise NotAuthorized, "No matching rules found for #{privilege} for #{user.inspect} " +
"(roles #{roles.inspect}, privileges #{privileges.inspect}, " +
"context #{options[:context].inspect})."
end
# Test each rule in turn to see whether any one of them is satisfied.
grant_permission = rules.any? do |rule|
begin
options[:skip_attribute_test] or
rule.attributes.empty? or
rule.attributes.any? do |attr|
begin
attr.validate?( attr_validator )
rescue NilAttributeValueError => e
nil # Bumping up against a nil attribute value flunks the rule.
end
end
end
end
unless grant_permission
raise AttributeAuthorizationError, "#{privilege} not allowed for #{user.inspect} on #{options[:object].inspect}."
end
true
end
# Calls permit! but rescues the AuthorizationException and returns false
# instead. If no exception is raised, permit? returns true and yields
# to the optional block.
def permit? (privilege, options = {}, &block) # :yields:
permit!(privilege, options)
yield if block_given?
true
rescue NotAuthorized
false
end
# Returns the obligations to be met by the current user for the given
# privilege as an array of obligation hashes in form of
# [{:object_attribute => obligation_value, ...}, ...]
# where +obligation_value+ is either (recursively) another obligation hash
# or a value spec, such as
# [operator, literal_value]
# The obligation hashes in the array should be OR'ed, conditions inside
# the hashes AND'ed.
#
# Example
# {:branch => {:company => [:is, 24]}, :active => [:is, true]}
#
# Options
# [:+context+] See permit!
# [:+user+] See permit!
#
def obligations (privilege, options = {})
options = {:context => nil}.merge(options)
user, roles, privileges = user_roles_privleges_from_options(privilege, options)
attr_validator = AttributeValidator.new(self, user)
matching_auth_rules(roles, privileges, options[:context]).collect do |rule|
obligation = rule.attributes.collect {|attr| attr.obligation(attr_validator) }
obligation.empty? ? [{}] : obligation
end.flatten
end
# Returns the description for the given role. The description may be
# specified with the authorization rules. Returns +nil+ if none was
# given.
def description_for (role)
role_descriptions[role]
end
# Returns the title for the given role. The title may be
# specified with the authorization rules. Returns +nil+ if none was
# given.
def title_for (role)
role_titles[role]
end
# Returns the role symbols of the given user.
def roles_for (user)
raise AuthorizationUsageError, "User object doesn't respond to roles" \
if !user.respond_to?(:role_symbols) and !user.respond_to?(:roles)
RAILS_DEFAULT_LOGGER.info("The use of user.roles is deprecated. Please add a method " +
"role_symbols to your User model.") if defined?(RAILS_DEFAULT_LOGGER) and !user.respond_to?(:role_symbols)
roles = user.respond_to?(:role_symbols) ? user.role_symbols : user.roles
raise AuthorizationUsageError, "User.#{user.respond_to?(:role_symbols) ? 'role_symbols' : 'roles'} " +
"doesn't return an Array of Symbols (#{roles.inspect})" \
if !roles.is_a?(Array) or (!roles.empty? and !roles[0].is_a?(Symbol))
(roles.empty? ? [:guest] : roles)
end
# Returns an instance of Engine, which is created if there isn't one
# yet. If +dsl_file+ is given, it is passed on to Engine.new and
# a new instance is always created.
def self.instance (dsl_file = nil)
if dsl_file or ENV['RAILS_ENV'] == 'development'
@@instance = new(dsl_file)
else
@@instance ||= new
end
end
class AttributeValidator # :nodoc:
attr_reader :user, :object, :engine
def initialize (engine, user, object = nil)
@engine = engine
@user = user
@object = object
end
def evaluate (value_block)
# TODO cache?
instance_eval(&value_block)
end
end
private
def user_roles_privleges_from_options(privilege, options)
options = {
:user => nil,
:context => nil
}.merge(options)
user = options[:user] || Authorization.current_user
privileges = privilege.is_a?(Array) ? privilege : [privilege]
raise AuthorizationUsageError, "No user object given (#{user.inspect})" \
unless user
roles = flatten_roles(roles_for(user))
privileges = flatten_privileges privileges, options[:context]
[user, roles, privileges]
end
def flatten_roles (roles)
# TODO caching?
flattened_roles = roles.clone.to_a
flattened_roles.each do |role|
flattened_roles.concat(@role_hierarchy[role]).uniq! if @role_hierarchy[role]
end
end
# Returns the privilege hierarchy flattened for given privileges in context.
def flatten_privileges (privileges, context = nil)
# TODO caching?
#if context.nil?
# context = privileges.collect { |p| p.to_s.split('_') }.
# reject { |p_p| p_p.length < 2 }.
# collect { |p_p| (p_p[1..-1] * '_').to_sym }.first
# raise AuthorizationUsageError, "No context given or inferable from privileges #{privileges.inspect}" unless context
#end
raise AuthorizationUsageError, "No context given or inferable from object" unless context
#context_regex = Regexp.new "_#{context}$"
# TODO work with contextless privileges
#flattened_privileges = privileges.collect {|p| p.to_s.sub(context_regex, '')}
flattened_privileges = privileges.clone #collect {|p| p.to_s.end_with?(context.to_s) ?
# p : [p, "#{p}_#{context}".to_sym] }.flatten
flattened_privileges.each do |priv|
flattened_privileges.concat(@rev_priv_hierarchy[[priv, nil]]).uniq! if @rev_priv_hierarchy[[priv, nil]]
flattened_privileges.concat(@rev_priv_hierarchy[[priv, context]]).uniq! if @rev_priv_hierarchy[[priv, context]]
end
end
def matching_auth_rules (roles, privileges, context)
@auth_rules.select {|rule| rule.matches? roles, privileges, context}
end
end
class AuthorizationRule
attr_reader :attributes, :contexts, :role, :privileges
def initialize (role, privileges = [], contexts = nil)
@role = role
@privileges = Set.new(privileges)
@contexts = Set.new((contexts && !contexts.is_a?(Array) ? [contexts] : contexts))
@attributes = []
end
def append_privileges (privs)
@privileges.merge(privs)
end
def append_attribute (attribute)
@attributes << attribute
end
def matches? (roles, privs, context = nil)
roles = [roles] unless roles.is_a?(Array)
@contexts.include?(context) and roles.include?(@role) and
not (@privileges & privs).empty?
end
end
class Attribute
# attr_conditions_hash of form
# { :object_attribute => [operator, value_block], ... }
# { :object_attribute => { :attr => ... } }
def initialize (conditions_hash)
@conditions_hash = conditions_hash
end
def validate? (attr_validator, object = nil, hash = nil)
object ||= attr_validator.object
return false unless object
(hash || @conditions_hash).all? do |attr, value|
attr_value = object_attribute_value(object, attr)
if value.is_a?(Hash)
if attr_value.is_a?(Array)
raise AuthorizationUsageError, "Unable evaluate multiple attributes " +
"on a collection. Cannot use '=>' operator on #{attr.inspect} " +
"(#{attr_value.inspect}) for attributes #{value.inspect}."
elsif attr_value.nil?
raise NilAttributeValueError, "Attribute #{attr.inspect} is nil in #{object.inspect}."
end
validate?(attr_validator, attr_value, value)
elsif value.is_a?(Array) and value.length == 2
evaluated = if value[1].is_a?(Proc)
attr_validator.evaluate(value[1])
else
value[1]
end
case value[0]
when :is
attr_value == evaluated
when :is_not
attr_value != evaluated
when :contains
attr_value.include?(evaluated)
when :does_not_contain
!attr_value.include?(evaluated)
when :is_in
evaluated.include?(attr_value)
when :is_not_in
!evaluated.include?(attr_value)
when :lt
attr_value && attr_value < evaluated
when :lte
attr_value && attr_value <= evaluated
when :gt
attr_value && attr_value > evaluated
when :gte
attr_value && attr_value <= evaluated
else
raise AuthorizationError, "Unknown operator #{value[0]}"
end
else
raise AuthorizationError, "Wrong conditions hash format"
end
end
end
# resolves all the values in condition_hash
def obligation (attr_validator, hash = nil)
hash = (hash || @conditions_hash).clone
hash.each do |attr, value|
if value.is_a?(Hash)
hash[attr] = obligation(attr_validator, value)
elsif value.is_a?(Array) and value.length == 2
hash[attr] = [value[0], attr_validator.evaluate(value[1])]
else
raise AuthorizationError, "Wrong conditions hash format"
end
end
hash
end
protected
def object_attribute_value (object, attr)
begin
object.send(attr)
rescue ArgumentError, NoMethodError => e
raise AuthorizationUsageError, "Error when calling #{attr} on " +
"#{object.inspect} for validating attribute: #{e}"
end
end
end
# An attribute condition that uses existing rules to decide validation
# and create obligations.
class AttributeWithPermission < Attribute
# E.g. privilege :read, attr_or_hash either :attribute or
# { :attribute => :deeper_attribute }
def initialize (privilege, attr_or_hash, context = nil)
@privilege = privilege
@context = context
@attr_hash = attr_or_hash
end
def validate? (attr_validator, object = nil, hash_or_attr = nil)
object ||= attr_validator.object
hash_or_attr ||= @attr_hash
return false unless object
case hash_or_attr
when Symbol
attr_value = object_attribute_value(object, hash_or_attr)
attr_validator.engine.permit? @privilege, :object => attr_value, :user => attr_validator.user
when Hash
hash_or_attr.all? do |attr, sub_hash|
attr_value = object_attribute_value(object, attr)
if attr_value.nil?
raise AuthorizationError, "Attribute #{attr.inspect} is nil in #{object.inspect}."
end
validate?(attr_validator, attr_value, sub_hash)
end
else
raise AuthorizationError, "Wrong conditions hash format: #{hash_or_attr.inspect}"
end
end
# may return an array of obligations to be OR'ed
def obligation (attr_validator, hash_or_attr = nil)
hash_or_attr ||= @attr_hash
case hash_or_attr
when Symbol
obligations = attr_validator.engine.obligations(@privilege,
:context => @context || hash_or_attr.to_s.pluralize.to_sym,
:user => attr_validator.user)
obligations.collect {|obl| {hash_or_attr => obl} }
when Hash
obligations_array_attrs = []
obligations =
hash_or_attr.inject({}) do |all, pair|
attr, sub_hash = pair
all[attr] = obligation(attr_validator, sub_hash)
if all[attr].length > 1
obligations_array_attrs << attr
else
all[attr] = all[attr].first
end
all
end
obligations = [obligations]
obligations_array_attrs.each do |attr|
next_array_size = obligations.first[attr].length
obligations = obligations.collect do |obls|
(0...next_array_size).collect do |idx|
obls_wo_array = obls.clone
obls_wo_array[attr] = obls_wo_array[attr][idx]
obls_wo_array
end
end.flatten
end
obligations
else
raise AuthorizationError, "Wrong conditions hash format: #{hash_or_attr.inspect}"
end
end
end
# Represents a pseudo-user to facilitate guest users in applications
class GuestUser
attr_reader :role_symbols
def initialize (roles = [:guest])
@role_symbols = roles
end
end
end
| 37.622 | 124 | 0.635479 |
0393f430ed33c98a971e095b891938d96bf70caa | 7,842 | =begin
#Datadog API V2 Collection
#Collection of all Datadog Public endpoints.
The version of the OpenAPI document: 1.0
Contact: support@datadoghq.com
Generated by: https://openapi-generator.tech
Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
This product includes software developed at Datadog (https://www.datadoghq.com/).
Copyright 2020-Present Datadog, Inc.
=end
require 'date'
require 'time'
module DatadogAPIClient::V2
# Incident Team data from a response.
class IncidentTeamResponseData
# whether the object has unparsed attributes
attr_accessor :_unparsed
attr_accessor :attributes
# The incident team's ID.
attr_accessor :id
attr_accessor :relationships
attr_accessor :type
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'attributes' => :'attributes',
:'id' => :'id',
:'relationships' => :'relationships',
:'type' => :'type'
}
end
# Returns all the JSON keys this model knows about
def self.acceptable_attributes
attribute_map.values
end
# Attribute type mapping.
def self.openapi_types
{
:'attributes' => :'IncidentTeamResponseAttributes',
:'id' => :'String',
:'relationships' => :'IncidentTeamRelationships',
:'type' => :'IncidentTeamType'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `DatadogAPIClient::V2::IncidentTeamResponseData` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `DatadogAPIClient::V2::IncidentTeamResponseData`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'attributes')
self.attributes = attributes[:'attributes']
end
if attributes.key?(:'id')
self.id = attributes[:'id']
end
if attributes.key?(:'relationships')
self.relationships = attributes[:'relationships']
end
if attributes.key?(:'type')
self.type = attributes[:'type']
else
self.type = 'teams'
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
attributes == o.attributes &&
id == o.id &&
relationships == o.relationships &&
type == o.type
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[attributes, id, relationships, type].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
elsif type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :Time
Time.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when :Array
# generic array, return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
# models (e.g. Pet) or oneOf
klass = DatadogAPIClient::V2.const_get(type)
res = klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
if res.instance_of? DatadogAPIClient::V2::UnparsedObject
self._unparsed = true
end
res
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 29.81749 | 224 | 0.624968 |
01b697ec910d2dacf92c68e624a5ef54f2bfc25d | 314 | name 'cdo-postfix'
maintainer 'Code.org'
maintainer_email 'will@code.org'
license 'All rights reserved'
description 'Installs/Configures cdo-postfix'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.2.11'
depends 'apt'
depends 'postfix'
| 28.545455 | 72 | 0.678344 |
1d6678d0937d750f8591c26a27c2d3746f1ea646 | 2,596 | #encoding: utf-8
include ERB::Util
class WoodEggWT < Sinatra::Base
configure do
# set root one level up, since this routes file is inside subdirectory
set :root, File.dirname(File.dirname(File.realpath(__FILE__)))
set :views, Proc.new { File.join(root, 'views/wt') }
# re-use the Q&A public CSS
set :public_folder, Proc.new { File.join(root, 'public-qa') }
end
use Rack::Auth::Basic, 'WoodEgg Writer Test' do |email, id|
@@person = Person.find(id: id, email: email)
end
before do
pass if request.path_info == '/country'
@userstat = @@person.userstats_dataset.select(:statkey).where(statvalue: '14w').first
redirect '/wt/country' if @userstat.nil?
/\Awoodegg-([a-z]{2})\Z/.match @userstat[:statkey]
redirect '/wt/country' if $1.nil?
@country = $1.upcase
@person = @@person
# template_ids = [130, 200]
# cc_qids = {'KH'=>[108, 178], 'CN'=>[329, 399], 'HK'=>[532, 602], 'IN'=>[753, 823], 'ID'=>[962, 1032], 'JP'=>[1169, 1239], 'KR'=>[1370, 1440], 'MY'=>[1579, 1649], 'MN'=>[1985, 2055], 'MM'=>[1784, 1854], 'PH'=>[2190, 2260], 'SG'=>[2403, 2473], 'LK'=>[2602, 2672], 'TW'=>[2807, 2877], 'TH'=>[3014, 3084], 'VN'=>[3221, 3291]}
template_ids = [112]
cc_qids = {'KH'=>[90], 'CN'=>[311], 'HK'=>[514], 'IN'=>[735], 'ID'=>[944], 'JP'=>[1151], 'KR'=>[1352], 'MY'=>[1561], 'MM'=>[1766], 'MN'=>[1967], 'SG'=>[2385], 'LK'=>[2584], 'TW'=>[2789], 'TH'=>[2996], 'VN'=>[3203], 'PH'=>[2172]}
@question_ids = cc_qids[@country]
end
get '/' do
@pagetitle = 'START'
@questions = Question.where(id: @question_ids).all
@questions.each do |q|
q[:finished] = TestEssay.for_pq(@person.id, q.id).finished_at
end
erb :home
end
get %r{\A/question/([0-9]+)\Z} do |id|
# tester can only do assigned questions.
redirect '/wt/' unless @question_ids.include? id.to_i
@question = Question[id]
@answers = @question.answers
@test_essay = TestEssay.for_pq(@person.id, @question.id)
@pagetitle = @question.question
erb :question
end
post %r{\A/question/([0-9]+)\Z} do |id|
redirect '/wt/' unless @question_ids.include? id.to_i
t = TestEssay.for_pq(@person.id, id)
if params[:submit] == 'FINISHED'
t.update(content: params[:content], finished_at: Time.now())
redirect '/wt/'
else
t.update(content: params[:content])
redirect "/wt/question/#{id}#youranswer"
end
end
get '/help' do
@pagetitle = 'HELP'
erb :help
end
# just an error page:
get '/country' do
@pagetitle = 'MISSING COUNTRY'
erb :country
end
end
| 33.714286 | 327 | 0.597072 |
d5cdea941def581bad8577615a316225ec07bb89 | 745 | class TweakSourceColumns < ActiveRecord::Migration[4.2]
def change
add_column :sources, :day, :integer
remove_column :sources, :year
add_column :sources, :year, :integer
rename_column :sources, :LCCN, :doi
remove_column :sources, :ISBN
add_column :sources, :isbn, :string
remove_column :sources, :ISSN
add_column :sources, :issn, :string
remove_column :sources, :contents
remove_column :sources, :keywords
add_column :sources, :verbatim_contents, :text
add_column :sources, :verbatim_keywords, :text
add_column :sources, :language_id, :integer
# remove_column :sources, :url
add_column :sources, :translator, :string
remove_column :sources, :price
end
end
| 24.032258 | 55 | 0.69396 |
ed72d6fe13d19744bdbc1b1baaf5508d2d372883 | 1,494 | #!/usr/bin/env ruby
#
# Sensu-mutator
# ===
#
# DESCRIPTION:
# Base mutator class. All you need to do is extend this class and implement a
# #mutate function. Uses the autorun feature just like sensu-handler and sensu-plugin/cli
#
# Example Implementation: described https://sensuapp.org/docs/latest/mutators#example-mutator-plugin
#
# class Helper < Sensu::Mutator
# def mutate
# @event.merge!(mutated: true)
# end
# end
#
# PLATFORM:
# all
#
# DEPENDENCIES:
# sensu-plugin/utils
# mixlib/cli
#
# Copyright 2015 Zach Bintliff <https://github.com/zbintliff>
#
# Released under the same terms as Sensu (the MIT license); see LICENSE
# for details.
require 'json'
require 'sensu-plugin/utils'
require 'mixlib/cli'
module Sensu
class Mutator
include Sensu::Plugin::Utils
include Mixlib::CLI
attr_accessor :argv
def initialize(argv = ARGV)
super()
self.argv = parse_options(argv)
end
def mutate
## Override this, be sure any changes are made to @event
nil
end
def dump
puts JSON.dump(@event)
end
# This works just like Plugin::CLI's autorun.
@@autorun = self
class << self
def method_added(name)
@@autorun = self if name == :mutate
end
end
def self.disable_autorun
@@autorun = false
end
at_exit do
return unless @@autorun
mutator = @@autorun.new
mutator.read_event(STDIN)
mutator.mutate
mutator.dump
end
end
end
| 19.92 | 100 | 0.654618 |
2116dc33b803e5b811d9ed7a1a2969d0adc643b2 | 139 | module IconHelper
def check_icon(checked)
return if !checked
content_tag :i, 'done', class: 'material-icons check-icon'
end
end | 23.166667 | 62 | 0.719424 |
d5135cd0c715f81e1f660aa614663110190b1967 | 13,442 | require "test_helper"
class TypeCheckServiceTest < Minitest::Test
include Steep
include TestHelper
ContentChange = Services::ContentChange
TypeCheckService = Services::TypeCheckService
TargetRequest = Services::TypeCheckService::TargetRequest
def project
@project ||= Project.new(steepfile_path: Pathname.pwd + "Steepfile").tap do |project|
Project::DSL.parse(project, <<EOF)
target :lib do
check "lib"
signature "lib.rbs", "private.rbs", "private/*.rbs"
end
target :test do
check "test"
signature "lib.rbs", "test.rbs"
end
EOF
end
end
def assignment
@assignment ||= Services::PathAssignment.new(max_index: 1, index: 0)
end
def reported_diagnostics
@reported_diagnostics ||= {}
end
def reporter
-> ((path, diagnostics)) {
formatter = Diagnostic::LSPFormatter.new({}, **{})
reported_diagnostics[path] = diagnostics.map {|diagnostic| formatter.format(diagnostic) }.uniq
}
end
def assert_empty_diagnostics(enum)
enum.each do |path, diagnostics|
assert_instance_of Pathname, path
assert_empty diagnostics
end
end
def test_update_files
service = Services::TypeCheckService.new(project: project)
# lib.rbs is used in both `lib` and `test`
{
Pathname("lib.rbs") => [ContentChange.string(<<RBS)],
class Customer
end
RBS
}.tap do |changes|
requests = service.update(changes: changes)
assert_predicate requests[:lib], :signature_updated?
assert_predicate requests[:test], :signature_updated?
end
# private.rbs is used only in both `lib`
{
Pathname("private.rbs") => [ContentChange.string(<<RBS)],
module CustomerHelper
end
RBS
}.tap do |changes|
requests = service.update(changes: changes)
assert_predicate requests[:lib], :signature_updated?
assert_nil requests[:test]
end
# test/customer_test.rb is in `test`
{
Pathname("test/customer_test.rb") => [ContentChange.string(<<RUBY)],
RUBY
}.tap do |changes|
requests = service.update(changes: changes)
assert_nil requests[:lib]
requests[:test].tap do |request|
refute_predicate request, :signature_updated?
assert_equal Set[Pathname("test/customer_test.rb")], request.source_paths
end
end
# test.rbs is in `test`
{
Pathname("test.rbs") => [ContentChange.string(<<RBS)],
class CustomerTest
end
RBS
}.tap do |changes|
requests = service.update(changes: changes)
assert_nil requests[:lib]
requests[:test].tap do |request|
assert_predicate request, :signature_updated?
assert_equal Set[Pathname("test/customer_test.rb")], request.source_paths
end
end
end
def test_update_ruby_syntax_error
service = Services::TypeCheckService.new(project: project)
{
Pathname("lib/syntax_error.rb") => [ContentChange.string(<<RUBY)],
class Account
RUBY
}.tap do |changes|
service.update_and_check(changes: changes, assignment: assignment, &reporter)
service.source_files[Pathname("lib/syntax_error.rb")].tap do |file|
assert_any!(file.errors, size: 1) do |error|
assert_instance_of Diagnostic::Ruby::SyntaxError, error
assert_equal 2, error.location.line
assert_equal 0, error.location.column
assert_equal 2, error.location.last_line
assert_equal 0, error.location.last_column
end
end
reported_diagnostics.clear
end
end
def test_update_encoding_error
service = Services::TypeCheckService.new(project: project)
broken = "寿限無寿限無".encode(Encoding::EUC_JP)
broken.force_encoding(Encoding::UTF_8)
{
Pathname("lib/syntax_error.rb") => [ContentChange.string(broken)]
}.tap do |changes|
service.update_and_check(changes: changes, assignment: assignment, &reporter)
service.source_files[Pathname("lib/syntax_error.rb")].tap do |file|
assert_nil file.errors
assert_equal "", file.content
end
reported_diagnostics.clear
end
end
def test_update_ruby_annotation_syntax_error
service = Services::TypeCheckService.new(project: project)
{
Pathname("lib/annotation_syntax_error.rb") => [ContentChange.string(<<RUBY)],
class Account
# @type self: Array[
end
RUBY
}.tap do |changes|
service.update_and_check(changes: changes, assignment: assignment, &reporter)
service.source_files[Pathname("lib/annotation_syntax_error.rb")].tap do |file|
assert_any!(file.errors, size: 1) do |error|
assert_instance_of Diagnostic::Ruby::SyntaxError, error
assert_equal " @type self: Array[", error.location.source
assert_equal "Syntax error caused by token `pEOF`", error.message
end
end
reported_diagnostics.clear
end
end
def test_update_ruby
# Update Ruby code notifies diagnostics found in updated files and sets up #diagnostics.
service = Services::TypeCheckService.new(project: project)
{
Pathname("lib/no_error.rb") => [ContentChange.string(<<RUBY)],
class Account
end
RUBY
Pathname("lib/type_error.rb") => [ContentChange.string(<<RUBY)],
1+""
RUBY
}.tap do |changes|
service.update_and_check(changes: changes, assignment: assignment, &reporter)
assert_equal [], reported_diagnostics.dig(Pathname("lib/no_error.rb"))
assert_equal "Ruby::UnresolvedOverloading", reported_diagnostics.dig(Pathname("lib/type_error.rb"), 0, :code)
assert_equal [], service.diagnostics.dig(Pathname("lib/no_error.rb"))
service.diagnostics[Pathname("lib/type_error.rb")].tap do |errors|
assert_equal 1, errors.size
assert_instance_of Diagnostic::Ruby::UnresolvedOverloading, errors[0]
end
reported_diagnostics.clear
end
end
def test_update_signature_1
# Updating signature runs type check
service = Services::TypeCheckService.new(project: project)
{
Pathname("lib/a.rb") => [ContentChange.string(<<RUBY)],
account = Account.new
RUBY
}.tap do |changes|
# Account is not defined.
service.update_and_check(changes: changes, assignment: assignment, &reporter)
assert_equal "Ruby::FallbackAny", reported_diagnostics.dig(Pathname("lib/a.rb"), 0, :code)
service.diagnostics[Pathname("lib/a.rb")].tap do |errors|
assert_equal 1, errors.size
assert_instance_of Diagnostic::Ruby::FallbackAny, errors[0]
end
reported_diagnostics.clear
end
{
Pathname("lib.rbs") => [ContentChange.string(<<RUBY)],
class Account
end
RUBY
}.tap do |changes|
# Adding RBS file removes the type errors.
service.update_and_check(changes: changes, assignment: assignment, &reporter)
assert_empty_diagnostics reported_diagnostics
assert_empty_diagnostics service.diagnostics
reported_diagnostics.clear
end
end
def test_update_signature_2
# Reports signature errors from all targets
service = Services::TypeCheckService.new(project: project)
{
Pathname("lib.rbs") => [ContentChange.string(<<RBS)],
class Account
def foo: () -> User[String]
def bar: () -> User
end
RBS
Pathname("private.rbs") => [ContentChange.string(<<RBS)],
class User[A]
end
RBS
Pathname("test.rbs") => [ContentChange.string(<<RBS)],
class User
end
RBS
}.tap do |changes|
# lib target reports an error on `User`
# test target reports an error on `User[String]`
service.update_and_check(changes: changes, assignment: assignment, &reporter)
reported_diagnostics[Pathname("lib.rbs")].tap do |errors|
assert_equal 2, errors.size
assert_any!(errors) do |error|
# One error is reported from `test` target.
assert_equal "RBS::InvalidTypeApplication", error[:code]
assert_equal 1, error.dig(:range, :start, :line)
end
assert_any!(errors) do |error|
# Another error is reported from `lib` target.
assert_equal "RBS::InvalidTypeApplication", error[:code]
assert_equal 2, error.dig(:range, :start, :line)
end
end
service.diagnostics[Pathname("lib.rbs")].tap do |errors|
assert_equal 2, errors.size
errors.each do |error|
assert_instance_of Diagnostic::Signature::InvalidTypeApplication, error
end
end
reported_diagnostics.clear
end
end
def test_update_signature_3
# Syntax error in RBS will be reported
service = Services::TypeCheckService.new(project: project)
{
Pathname("lib.rbs") => [ContentChange.string(<<RBS)],
class Account[z]
end
RBS
}.tap do |changes|
service.update_and_check(changes: changes, assignment: assignment, &reporter)
reported_diagnostics[Pathname("lib.rbs")].tap do |errors|
assert_equal 1, errors.size
assert_equal "RBS::SyntaxError", errors[0][:code]
end
service.diagnostics[Pathname("lib.rbs")].tap do |errors|
assert_equal 2, errors.size
errors.each do |error|
assert_instance_of Diagnostic::Signature::SyntaxError, error
end
end
reported_diagnostics.clear
end
end
def test_update_signature_4
# Target with syntax error RBS won't report new type errors.
service = Services::TypeCheckService.new(project: project)
{
Pathname("lib/a.rb") => [ContentChange.string(<<RBS)],
1 + ""
RBS
}.tap do |changes|
service.update_and_check(changes: changes, assignment: assignment, &reporter)
reported_diagnostics[Pathname("lib/a.rb")].tap do |errors|
assert_equal 1, errors.size
assert_equal "Ruby::UnresolvedOverloading", errors[0][:code]
end
reported_diagnostics.clear
end
{
Pathname("lib.rbs") => [ContentChange.string(<<RBS)],
class Account[z]
end
RBS
}.tap do |changes|
service.update_and_check(changes: changes, assignment: assignment, &reporter)
reported_diagnostics[Pathname("lib.rbs")].tap do |errors|
assert_equal 1, errors.size
assert_equal "RBS::SyntaxError", errors[0][:code]
end
# No error reported for lib/a.rb
reported_diagnostics[Pathname("lib/a.rb")].tap do |errors|
assert_nil errors
end
service.diagnostics[Pathname("lib.rbs")].tap do |errors|
assert_equal 2, errors.size
errors.each do |error|
assert_instance_of Diagnostic::Signature::SyntaxError, error
end
end
# #diagnostics not updated
service.diagnostics[Pathname("lib/a.rb")].tap do |errors|
assert_equal 1, errors.size
errors.each do |error|
assert_instance_of Diagnostic::Ruby::UnresolvedOverloading, error
end
end
reported_diagnostics.clear
end
end
def test_update_signature_5
# Target with syntax error RBS won't report new validation errors.
service = Services::TypeCheckService.new(project: project)
{
Pathname("lib.rbs") => [ContentChange.string(<<RBS)],
class A
end
RBS
Pathname("private.rbs") => [ContentChange.string(<<RBS)],
B: Array
RBS
}.tap do |changes|
service.update_and_check(changes: changes, assignment: assignment, &reporter)
reported_diagnostics[Pathname("lib.rbs")].tap do |errors|
assert_empty errors
end
reported_diagnostics[Pathname("private.rbs")].tap do |errors|
assert_any! errors, size: 1 do |error|
assert_equal "RBS::InvalidTypeApplication", error[:code]
end
end
reported_diagnostics.clear
end
{
Pathname("lib.rbs") => [ContentChange.string(<<RBS)],
class A < FooBar
end
RBS
}.tap do |changes|
service.update_and_check(changes: changes, assignment: assignment, &reporter)
reported_diagnostics[Pathname("lib.rbs")].tap do |errors|
assert_any! errors, size: 1 do |error|
assert_equal "RBS::UnknownTypeName", error[:code]
end
end
# No error can be reported/registered because of ancestor error.
reported_diagnostics[Pathname("private.rbs")].tap do |errors|
assert_empty errors
end
service.diagnostics[Pathname("private.rbs")].tap do |errors|
assert_empty errors
end
reported_diagnostics.clear
end
end
def test_update_signature_6
# Recovering from syntax error test
service = Services::TypeCheckService.new(project: project)
{
Pathname("private.rbs") => [ContentChange.string(<<RBS)],
class A
RBS
Pathname("private/test.rbs") => [ContentChange.string(<<RBS)],
class B
end
RBS
}.tap do |changes|
service.update_and_check(changes: changes, assignment: assignment, &reporter)
reported_diagnostics[Pathname("private.rbs")].tap do |errors|
assert_any! errors, size: 1 do |error|
assert_equal "RBS::SyntaxError", error[:code]
end
end
reported_diagnostics[Pathname("private/test.rbs")].tap do |errors|
assert_nil errors
end
reported_diagnostics.clear
end
{
Pathname("private.rbs") => [ContentChange.string(<<RBS)],
class A
def foo: () -> B
end
RBS
}.tap do |changes|
service.update_and_check(changes: changes, assignment: assignment, &reporter)
assert_empty_diagnostics reported_diagnostics
assert_empty_diagnostics service.diagnostics
reported_diagnostics.clear
end
end
end
| 28.35865 | 115 | 0.673858 |
4a9070c894852a986e3625099c07bdbef1a36622 | 2,196 | class Libsecret < Formula
desc "Library for storing/retrieving passwords and other secrets"
homepage "https://wiki.gnome.org/Projects/Libsecret"
url "https://download.gnome.org/sources/libsecret/0.20/libsecret-0.20.5.tar.xz"
sha256 "3fb3ce340fcd7db54d87c893e69bfc2b1f6e4d4b279065ffe66dac9f0fd12b4d"
license "LGPL-2.1-or-later"
bottle do
root_url "https://github.com/gromgit/homebrew-core-mojave/releases/download/libsecret"
rebuild 1
sha256 cellar: :any, mojave: "f941b92f0e6a54d2796d55308fe56c34c34c6a55909876de48787a05069c6881"
end
depends_on "docbook-xsl" => :build
depends_on "gettext" => :build
depends_on "gobject-introspection" => :build
depends_on "meson" => :build
depends_on "ninja" => :build
depends_on "pkg-config" => :build
depends_on "vala" => :build
depends_on "glib"
depends_on "libgcrypt"
uses_from_macos "libxslt" => :build
def install
ENV["XML_CATALOG_FILES"] = "#{etc}/xml/catalog"
mkdir "build" do
system "meson", "..", "-Dbashcompdir=#{bash_completion}",
"-Dgtk_doc=false",
*std_meson_args
system "ninja", "--verbose"
system "ninja", "install", "--verbose"
end
end
test do
(testpath/"test.c").write <<~EOS
#include <libsecret/secret.h>
const SecretSchema * example_get_schema (void) G_GNUC_CONST;
const SecretSchema *
example_get_schema (void)
{
static const SecretSchema the_schema = {
"org.example.Password", SECRET_SCHEMA_NONE,
{
{ "number", SECRET_SCHEMA_ATTRIBUTE_INTEGER },
{ "string", SECRET_SCHEMA_ATTRIBUTE_STRING },
{ "even", SECRET_SCHEMA_ATTRIBUTE_BOOLEAN },
{ "NULL", 0 },
}
};
return &the_schema;
}
int main()
{
example_get_schema();
return 0;
}
EOS
flags = [
"-I#{include}/libsecret-1",
"-I#{HOMEBREW_PREFIX}/include/glib-2.0",
"-I#{HOMEBREW_PREFIX}/lib/glib-2.0/include",
]
system ENV.cc, "test.c", "-o", "test", *flags
system "./test"
end
end
| 29.28 | 99 | 0.60929 |
bf88006d3dc0c034ceadedb38325ca8e427d5545 | 2,473 | class PurchasesController < ApplicationController
before_action :authenticate_user!
before_action :set_purchase, only: [:show, :edit, :update, :destroy]
# GET /purchases
# GET /purchases.json
def index
@purchases = Purchase.all
end
# GET /purchases/1
# GET /purchases/1.json
def show
end
# GET /purchases/new
def new
@purchase = Purchase.new
end
# GET /purchases/1/edit
def edit
end
# POST /purchases
# POST /purchases.json
def create
@purchase = Purchase.new(purchase_params)
@purchase.receipt = Receipt.find(purchase_params[:receipt])
save_relations
respond_to do |format|
if @purchase.save
format.html { redirect_to @purchase.receipt, notice: 'Purchase was successfully added.' }
format.json { render :show, status: :created, location: @purchase }
else
format.html { render :new }
format.json { render json: @purchase.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /purchases/1
# PATCH/PUT /purchases/1.json
def update
save_relations
respond_to do |format|
if @purchase.update(purchase_params)
format.html { redirect_to @purchase.receipt, notice: 'Purchase was successfully updated.' }
format.json { render :show, status: :ok, location: @purchase }
else
format.html { render :edit }
format.json { render json: @purchase.errors, status: :unprocessable_entity }
end
end
end
# DELETE /purchases/1
# DELETE /purchases/1.json
def destroy
receipt = @purchase.receipt
@purchase.destroy
respond_to do |format|
format.html { redirect_to receipt, notice: 'Purchase was successfully removed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_purchase
@purchase = Purchase.find(params[:id])
end
def save_relations
@purchase.product = Product.find_or_create(purchase_name_params[:product_name])
@purchase.country_origin = Country.find_or_create(purchase_name_params[:country_origin_name])
end
# Never trust parameters from the scary internet, only allow the white list through.
def purchase_params
params.require(:purchase).permit(:weight, :receipt)
end
def purchase_name_params
params.require(:purchase).permit(:product_name, :country_origin_name)
end
end
| 27.477778 | 99 | 0.680954 |
1a776769f8ed370e0e7c03ddbc23ed4934cd4612 | 607 | ActiveAdmin.register User do
actions :index, :show
index do
selectable_column
id_column
column :email
column :full_name
column :postal_code
column :district do |obj|
obj.location.district
end
column :province do |obj|
obj.location.province
end
column :disaster do |obj|
pluralize(obj.location.events.count, 'time')
end
column :last_sign_in_at
column :sign_in_count
actions
end
filter :email
filter :full_name
filter :location, as: :select,
collection: -> { Location.all.map{ |l| [l.postal_code, l.id] } }
end
| 20.931034 | 74 | 0.654036 |
611fb474d495d8fdffb13e82a9f0daa7f4cbdf05 | 259 | # Don't forget! This file needs to be 'required' in its spec file
# See README.md for instructions on how to do this
def fizzbuzz(int)
if int % 5 == 0 && int % 3 == 0
"FizzBuzz"
elsif int % 3 == 0
"Fizz"
elsif int % 5 == 0
"Buzz"
else nil
end
end
| 18.5 | 65 | 0.625483 |
b9bb1e44f186fb11e30e83c44f09f60727c66aea | 211 | class RemoveNotNullFromPiecesColumnPieceHeadId < ActiveRecord::Migration[5.2]
def change
execute <<-DDL.gsub /^\s+/, ''
ALTER TABLE pieces ALTER COLUMN piece_head_id DROP NOT NULL;
DDL
end
end
| 26.375 | 77 | 0.720379 |
1daa7ad161f6ff847cdcd1a776d2b8288a70ea6c | 363 | class TSheets::Repos::CurrentTotals < TSheets::Repository
url "/reports/current_totals"
model TSheets::Models::CurrentTotals
actions :report
filter :user_ids, [ :integer ]
filter :group_ids, [ :integer ]
filter :on_the_clock, :string
filter :page, :integer
filter :per_page, :integer
filter :order_by, :string
filter :order_desc, :boolean
end
| 27.923077 | 57 | 0.732782 |
ff59b354fa6aa54479ae36782e3db5059bbd2e10 | 524 | class GithubInfo
include Mongoid::Document
field :pushEvents
field :pullEvents
field :gistEvents
field :forkEvents
field :mostRecentEventDate
field :oldestEventDate
field :commits
field :lineAdditions
field :lineDeletions
field :commitMessages
field :languages
field :github_handle
field :fullName
field :aviurl
field :profileurl
field :location
field :followersnum
field :followingnum
field :reposnum
field :blog_link
field :eventDates
field :reposData
belongs_to :user
end | 18.714286 | 28 | 0.76145 |
790f2b32876f31d067b8144c58d5777d4481aca2 | 4,378 | # enable all linting rules by default, then override below
all
# Some files hard-wrap lines to around 80 characters, others do not. We don't
# have a definitive guide in the GDS Way, so we shouldn't enforce either way here.
exclude_rule "line-length"
# Middleman starts .md files with Frontmatter (https://middlemanapp.com/basics/frontmatter/)
# which describe the title of the page, category, review date and so on.
# Thus we don't need to define the title of the page with a header.
exclude_rule "first-line-h1"
exclude_rule "first-header-h1"
# Some documents may want to be explicit about the step numbers so that they
# can refer to them later. For example, "go back to step 3 and repeat".
# In those cases, forcing every item to be prefixed with `1` is unhelpful.
exclude_rule "ol-prefix"
# Sometimes we use code blocks to show example log file content or console
# output, so a particular syntax highlight would not be appropriate. We should
# leave it to the developer to decide whether or not a code language should
# be provided.
exclude_rule "fenced-code-language"
# We use `$` as a hint that 'this line is run in isolation'.
# We may batch up multiple of these in one code block, for example:
#
# ```
# $ sudo -i aptly repo edit -distribution="stable" govuk-jenkins
# $ sudo -i aptly repo add govuk-jenkins /path/to/jenkins.deb
# $ sudo aptly snapshot create govuk-jenkins-$(date +%Y%m%d) from repo govuk-jenkins
# $ sudo -i aptly publish snapshot govuk-jenkins-$(date +%Y%m%d) govuk-jenkins
# ```
#
# We've also not been particularly consistent with our use of `$` to
# represent the shell prompt - some code examples have it and some don't.
# We don't appear to have prescribed a style, so let's just leave this to
# developer choice for now.
exclude_rule "commands-show-output"
# At time of writing, this rule is quite buggy.
#
# 1.
# - Foo
# - Bar
#
# ...and then later on in the doc:
#
# - Baz
#
# ...it will complain that the `-` isn't at the same indentation level as the ones
# encountered earlier. But this is deliberate because the previous hyphens were
# sublists within the `1.` numbered list.
#
# So, better to turn the rule off for now.
exclude_rule "list-indent"
# Some pages, such as the "Architectural deep-dive of GOV.UK", break into
# sections which all follow the same format, e.g.
#
# ## Foo
# ### Problem
# ### Solution
# ## Bar
# ### Problem
# ### Solution
#
# This seems a reasonable thing to be able to do and so we leave it up to
# developers' discretion.
exclude_rule "no-duplicate-header"
# This is quite an opinionated rule that disallows characters like
# !, ? or : at the end of headings.
# We use these in various places and it's not clear what benefit there is
# to disallowing them.
exclude_rule "no-trailing-punctuation"
# This rule should be triggered when blockquotes have more than one space
# after the blockquote (>) symbol. However, it's a bit buggy, and fails for
# markdown like this:
#
# > Foo
# > [bar](https://example.com) baz
#
# ...so best to disable it.
exclude_rule "no-multiple-space-blockquote"
# This rule errors if it encounters a bare URL, e.g. https://example.com,
# which is neither in markdown form (`[link](https://example.com`) nor
# wrapped in `<https://example.com>`.
#
# This is a good rule to enable, however we have numerous use cases where
# it isn't appropriate to make the URL linkable. For example, when
# describing dynamic portions of the URL, which the reader should
# substitute for their own use case:
#
# - https://example.com/{YOUR_ORGANISATION_ID}/bla
#
# So, unfortunately, we'll have to exclude the rule.
exclude_rule "no-bare-urls"
# This rule is a little buggy, treating the following URL markdown
# as HTML:
# <https://www.direct.gov.uk/__canary__>
# We also have some legitimate use cases for inline HTML: for instance,
# embedding an iframe on the architecture page.
# So, we'll need to disable the rule. Keep an eye on the 'inline ignore'
# issue: https://github.com/markdownlint/markdownlint/issues/16
# If that is implemented, we'll be able to override the rule only
# in the places we want to allow inline HTML.
exclude_rule "no-inline-html"
# This rule stops us from having correctly rendered nested unordered
# lists within an ordered list.
# It is a known issue with this gem:
# https://github.com/markdownlint/markdownlint/issues/296
exclude_rule "ul-indent"
| 37.101695 | 92 | 0.736638 |
ff8048a06401dcd7aedf79769d45f154ee794012 | 93 | class State < ActiveRecord::Base
# Remember to create a migration!
has_many :cities
end
| 15.5 | 35 | 0.741935 |
62c0b127eba269329ac0e47fee5a21360599c681 | 45 | module PrAppointment
VERSION = "0.1.0"
end
| 11.25 | 20 | 0.711111 |
bfa8815c3b2c5ac061a3aff37019c0272c48bdb7 | 225 | ENV['RACK_ENV'] ||= "development"
require 'bundler/setup'
Bundler.require(:default, ENV['RACK_ENV'].to_sym)
configure ENV['RACK_ENV'].to_sym do
set :database, "sqlite3:db/#{ENV['RACK_ENV']}.sqlite"
end
require_all 'app'
| 20.454545 | 55 | 0.715556 |
b9bfaf85febf88e54ef827479ae4c0664cac595c | 1,033 | #
# Be sure to run `pod lib lint ZPlaceholderTextView.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'ZPlaceholderTextView'
s.version = '1.4.1'
s.summary = 'A short description of ZPlaceholderTextView.'
s.description = <<-DESC
TODO: Add long description of the pod here.
DESC
s.homepage = 'https://github.com/sapphirezzz/ZPlaceholderTextView'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Zack Zheng' => 'zhengzuanzhe@gmail.com' }
s.source = { :git => 'https://github.com/sapphirezzz/ZPlaceholderTextView.git', :tag => s.version.to_s }
s.swift_version = '5.0'
s.ios.deployment_target = '8.0'
s.source_files = 'ZPlaceholderTextView/Classes/**/*'
s.frameworks = 'UIKit', 'Foundation'
end
| 35.62069 | 116 | 0.635044 |
5da1bea8b21ad32a4502c5aaa22a132cb89824a9 | 3,535 | =begin
* Name: bars.rb
* Creates the different smithing bars definitions
* Author: Davidi2 (David Insley)
* Date: November 11, 2013
=end
require 'java'
module Smithing
BARS = {}
class << self
def create_bar(name, &block)
BARS[name] = Bar.new block
SMITHING_TABLES[BARS[name]] = []
end
def create_bars
create_bar :bronze do
@smelt_lvl_req = 1
@smelt_xp = 6.2
@bar_id = 2349
@primary_ore = 436
@secondary_ore = 438
@secondary_amt = 1
@smith_xp = 12.5
end
create_bar :blurite do
@smelt_lvl_req = 8
@smelt_xp = 8
@bar_id = 9467
@primary_ore = 668
end
create_bar :iron do
@smelt_lvl_req = 15
@smelt_xp = 12.5
@bar_id = 2351
@primary_ore = 440
@smith_xp = 25
end
create_bar :silver do
@smelt_lvl_req = 20
@smelt_xp = 13.7
@bar_id = 2355
@primary_ore = 442
end
create_bar :steel do
@smelt_lvl_req = 30
@smelt_xp = 17.5
@bar_id = 2353
@primary_ore = 440
@secondary_amt = 2
@smith_xp = 37.5
end
create_bar :gold do
@smelt_lvl_req = 40
@smelt_xp = 22.5
@bar_id = 2357
@primary_ore = 444
end
create_bar :mithril do
@smelt_lvl_req = 50
@smelt_xp = 17.5
@bar_id = 2359
@primary_ore = 447
@secondary_amt = 4
@smith_xp = 50
end
create_bar :adamant do
@smelt_lvl_req = 70
@smelt_xp = 37.5
@bar_id = 2361
@primary_ore = 449
@secondary_amt = 6
@smith_xp = 62.5
end
create_bar :rune do
@smelt_lvl_req = 85
@smelt_xp = 50
@bar_id = 2363
@primary_ore = 451
@secondary_amt = 8
@smith_xp = 75
end
end
end
class Bar
attr_reader :smelt_lvl_req, :smelt_xp, :bar_id, :primary_ore, :primary_amt, :secondary_ore, :secondary_amt, :smith_xp
def initialize(block)
@smelt_lvl_req = 99
@smelt_xp = 0
@bar_id = 0
@primary_ore = nil
@primary_amt = 1
@secondary_ore = 453
@secondary_amt = 0
@smith_xp = 0
instance_eval(&block)
end
def check_reqs(player, first=false)
if player.get_skill_set.get_current_level(Skill::SMITHING) < @smelt_lvl_req
player.send_message "You need a Smithing level of #{@smelt_lvl_req} to smelt that."
return false
end
if (player.get_inventory.get_amount(@secondary_ore) < @secondary_amt) || (player.get_inventory.get_amount(@primary_ore) < @primary_amt)
if !first
player.send_message 'You have run out of ores to smelt.'
else
player.send_message 'You do not have the ores required to smelt that.'
end
return false
end
true
end
def smith(player)
player.get_inventory.remove Item.new(@primary_ore, @primary_amt)
player.get_inventory.remove Item.new(@secondary_ore, @secondary_amt) if @secondary_amt > 0
bar_item = Item.new @bar_id
player.get_inventory.add bar_item
player.play_animation SMELTING_ANIMATION
player.get_skill_set.add_experience(Skill::SMITHING, @smelt_xp)
player.send_message "You smelt a #{bar_item.definition.name.downcase}."
end
end
end | 26.984733 | 142 | 0.568034 |
f84e42f0f56109b4845edd5f11a6f13d52612e2e | 767 | # This file was generated by GoReleaser. DO NOT EDIT.
class Wsgnatsd < Formula
desc "A websocket server proxy for nats-server"
homepage "https://github.com/aricart/wsgnatsd"
version "0.8.10"
bottle :unneeded
if OS.mac?
url "https://github.com/aricart/wsgnatsd/releases/download/v0.8.10/wsgnatsd-v0.8.10-darwin-amd64.zip"
sha256 "38a1e1242a6a429a92849333956244edd53123e05e8461171a3900b3b1a2bb23"
elsif OS.linux?
if Hardware::CPU.intel?
url "https://github.com/aricart/wsgnatsd/releases/download/v0.8.10/wsgnatsd-v0.8.10-darwin-amd64.zip"
sha256 "d758aa5ff8903b0c25cf267c16697810ccb7ec769a8b658f62e0019e7f035943"
end
end
def install
bin.install "wsgnatsd"
end
test do
system "#{bin}/wsgnatsd --help"
end
end
| 29.5 | 107 | 0.740548 |
382ea7d16d835a0f3588302dbc4ec373b13ddb51 | 47 | module Canteen
module ImagesHelper
end
end
| 9.4 | 21 | 0.787234 |
ff84210585eed11d5d0db2c8ad5c2d99d7048989 | 1,114 | module S3Secure::Lifecycle
class Builder
# Note: put_bucket_lifecycle_configuration and put_bucket_lifecycle understand different payloads.
# put_bucket_lifecycle is old and shouldnt be used
RULE_ID = Base::RULE_ID
DEFAULT_RULE = {
expiration: {expired_object_delete_marker: true},
id: RULE_ID,
status: "Enabled",
prefix: "",
noncurrent_version_expiration: {noncurrent_days: 365},
abort_incomplete_multipart_upload: {days_after_initiation: 30}
}
def initialize(rules)
@rules = rules || []
end
def has?(id)
!!@rules.detect { |rule| rule[:id] == id }
end
def rules_with_addition(prefix=nil)
rules = @rules.dup
unless has?(RULE_ID)
rule = DEFAULT_RULE
rule[:prefix] = prefix if prefix
rules << rule
end
rules
end
def rules_with_removal
rules = @rules.dup
rules.delete_if { |rule| rule[:id] == RULE_ID }
rules
end
def build(type)
if type == :remove
remove_lifecycle
else
add_lifecycle
end
end
end
end
| 23.208333 | 102 | 0.623878 |
18ab7de768f3f3d1ae224bd7b81e1c0b94bef008 | 1,210 | # frozen_string_literal: true
RSpec.shared_examples_for 'auditable' do
let(:model) { described_class }
let(:model_name) { model.name.underscore.to_sym }
describe 'before validation' do
let(:current_user) { build_stubbed(:user, id: 1) }
let(:existing_user) { build_stubbed(:user, id: 2) }
it 'adds the current user id to created_by and updated_by' do
allow(User).to receive(:current).and_return(current_user)
resource = build(model_name, created_by: nil, updated_by: nil)
resource.valid?
expect(resource.created_by).to eq(current_user.id)
end
it 'does not change created_by or updated_by if they already exist' do
allow(User).to receive(:current).and_return(current_user)
resource = build(model_name, created_by: existing_user.id, updated_by: existing_user.id)
resource.valid?
expect(resource.created_by).to eq(existing_user.id)
end
it 'does not change created_by or updated_by if User.current is not available' do
allow(User).to receive(:current).and_return(nil)
resource = build(model_name, created_by: nil, updated_by: nil)
resource.valid?
expect(resource.created_by).to eq(nil)
end
end
end
| 36.666667 | 94 | 0.713223 |
26270b1c3c9c9b4da0ec4c03f6a8d6fd861fbe70 | 14,155 | # Copyright (C) The Arvados Authors. All rights reserved.
#
# SPDX-License-Identifier: AGPL-3.0
require 'test_helper'
class Arvados::V1::FiltersTest < ActionController::TestCase
test '"not in" filter passes null values' do
@controller = Arvados::V1::ContainerRequestsController.new
authorize_with :admin
get :index, params: {
filters: [ ['container_uuid', 'not in', ['zzzzz-dz642-queuedcontainer', 'zzzzz-dz642-runningcontainr']] ],
controller: 'container_requests',
}
assert_response :success
found = assigns(:objects)
assert_includes(found.collect(&:container_uuid), nil,
"'container_uuid not in [zzzzz-dz642-queuedcontainer, zzzzz-dz642-runningcontainr]' filter should pass null")
end
test 'error message for non-array element in filters array' do
@controller = Arvados::V1::CollectionsController.new
authorize_with :active
get :index, params: {
filters: [{bogus: 'filter'}],
}
assert_response 422
assert_match(/Invalid element in filters array/,
json_response['errors'].join(' '))
end
test 'error message for full text search on a specific column' do
@controller = Arvados::V1::CollectionsController.new
authorize_with :active
get :index, params: {
filters: [['uuid', '@@', 'abcdef']],
}
assert_response 422
assert_match(/not supported/, json_response['errors'].join(' '))
end
test 'difficult characters in full text search' do
@controller = Arvados::V1::CollectionsController.new
authorize_with :active
get :index, params: {
filters: [['any', '@@', 'a|b"c']],
}
assert_response :success
# (Doesn't matter so much which results are returned.)
end
test 'array operand in full text search' do
@controller = Arvados::V1::CollectionsController.new
authorize_with :active
get :index, params: {
filters: [['any', '@@', ['abc', 'def']]],
}
assert_response 422
assert_match(/not supported/, json_response['errors'].join(' '))
end
test 'api responses provide timestamps with nanoseconds' do
@controller = Arvados::V1::CollectionsController.new
authorize_with :active
get :index
assert_response :success
assert_not_empty json_response['items']
json_response['items'].each do |item|
%w(created_at modified_at).each do |attr|
# Pass fixtures with null timestamps.
next if item[attr].nil?
assert_match(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d.\d{9}Z$/, item[attr])
end
end
end
%w(< > <= >= =).each do |operator|
test "timestamp #{operator} filters work with nanosecond precision" do
# Python clients like Node Manager rely on this exact format.
# If you must change this format for some reason, make sure you
# coordinate the change with them.
expect_match = !!operator.index('=')
mine = act_as_user users(:active) do
Collection.create!(manifest_text: '')
end
timestamp = mine.modified_at.strftime('%Y-%m-%dT%H:%M:%S.%NZ')
@controller = Arvados::V1::CollectionsController.new
authorize_with :active
get :index, params: {
filters: [['modified_at', operator, timestamp],
['uuid', '=', mine.uuid]],
}
assert_response :success
uuids = json_response['items'].map { |item| item['uuid'] }
if expect_match
assert_includes uuids, mine.uuid
else
assert_not_includes uuids, mine.uuid
end
end
end
test "full text search with count='none'" do
@controller = Arvados::V1::GroupsController.new
authorize_with :admin
get :contents, params: {
format: :json,
count: 'none',
limit: 1000,
filters: [['any', '@@', Rails.configuration.ClusterID]],
}
assert_response :success
all_objects = Hash.new(0)
json_response['items'].map{|o| o['kind']}.each{|t| all_objects[t] += 1}
assert_equal true, all_objects['arvados#group']>0
assert_equal true, all_objects['arvados#job']>0
assert_equal true, all_objects['arvados#pipelineInstance']>0
assert_equal true, all_objects['arvados#pipelineTemplate']>0
# Perform test again mimicking a second page request with:
# last_object_class = PipelineInstance
# and hence groups and jobs should not be included in the response
# offset = 5, which means first 5 pipeline instances were already received in page 1
# and hence the remaining pipeline instances and all other object types should be included in the response
@test_counter = 0 # Reset executed action counter
@controller = Arvados::V1::GroupsController.new
get :contents, params: {
format: :json,
count: 'none',
limit: 1000,
offset: '5',
last_object_class: 'PipelineInstance',
filters: [['any', '@@', Rails.configuration.ClusterID]],
}
assert_response :success
second_page = Hash.new(0)
json_response['items'].map{|o| o['kind']}.each{|t| second_page[t] += 1}
assert_equal false, second_page.include?('arvados#group')
assert_equal false, second_page.include?('arvados#job')
assert_equal true, second_page['arvados#pipelineInstance']>0
assert_equal all_objects['arvados#pipelineInstance'], second_page['arvados#pipelineInstance']+5
assert_equal true, second_page['arvados#pipelineTemplate']>0
end
[['prop1', '=', 'value1', [:collection_with_prop1_value1], [:collection_with_prop1_value2, :collection_with_prop2_1]],
['prop1', '!=', 'value1', [:collection_with_prop1_value2, :collection_with_prop2_1], [:collection_with_prop1_value1]],
['prop1', 'exists', true, [:collection_with_prop1_value1, :collection_with_prop1_value2, :collection_with_prop1_value3, :collection_with_prop1_other1], [:collection_with_prop2_1]],
['prop1', 'exists', false, [:collection_with_prop2_1], [:collection_with_prop1_value1, :collection_with_prop1_value2, :collection_with_prop1_value3, :collection_with_prop1_other1]],
['prop1', 'in', ['value1', 'value2'], [:collection_with_prop1_value1, :collection_with_prop1_value2], [:collection_with_prop1_value3, :collection_with_prop2_1]],
['prop1', 'in', ['value1', 'valueX'], [:collection_with_prop1_value1], [:collection_with_prop1_value3, :collection_with_prop2_1]],
['prop1', 'not in', ['value1', 'value2'], [:collection_with_prop1_value3, :collection_with_prop1_other1, :collection_with_prop2_1], [:collection_with_prop1_value1, :collection_with_prop1_value2]],
['prop1', 'not in', ['value1', 'valueX'], [:collection_with_prop1_value2, :collection_with_prop1_value3, :collection_with_prop1_other1, :collection_with_prop2_1], [:collection_with_prop1_value1]],
['prop1', '>', 'value2', [:collection_with_prop1_value3], [:collection_with_prop1_other1, :collection_with_prop1_value1]],
['prop1', '<', 'value2', [:collection_with_prop1_other1, :collection_with_prop1_value1], [:collection_with_prop1_value2, :collection_with_prop1_value2]],
['prop1', '<=', 'value2', [:collection_with_prop1_other1, :collection_with_prop1_value1, :collection_with_prop1_value2], [:collection_with_prop1_value3]],
['prop1', '>=', 'value2', [:collection_with_prop1_value2, :collection_with_prop1_value3], [:collection_with_prop1_other1, :collection_with_prop1_value1]],
['prop1', 'like', 'value%', [:collection_with_prop1_value1, :collection_with_prop1_value2, :collection_with_prop1_value3], [:collection_with_prop1_other1]],
['prop1', 'like', '%1', [:collection_with_prop1_value1, :collection_with_prop1_other1], [:collection_with_prop1_value2, :collection_with_prop1_value3]],
['prop1', 'ilike', 'VALUE%', [:collection_with_prop1_value1, :collection_with_prop1_value2, :collection_with_prop1_value3], [:collection_with_prop1_other1]],
['prop2', '>', 1, [:collection_with_prop2_5], [:collection_with_prop2_1]],
['prop2', '<', 5, [:collection_with_prop2_1], [:collection_with_prop2_5]],
['prop2', '<=', 5, [:collection_with_prop2_1, :collection_with_prop2_5], []],
['prop2', '>=', 1, [:collection_with_prop2_1, :collection_with_prop2_5], []],
['<http://schema.org/example>', '=', "value1", [:collection_with_uri_prop], []],
['listprop', 'contains', 'elem1', [:collection_with_list_prop_odd, :collection_with_listprop_elem1], [:collection_with_list_prop_even]],
['listprop', '=', 'elem1', [:collection_with_listprop_elem1], [:collection_with_list_prop_odd]],
['listprop', 'contains', 5, [:collection_with_list_prop_odd], [:collection_with_list_prop_even, :collection_with_listprop_elem1]],
['listprop', 'contains', 'elem2', [:collection_with_list_prop_even], [:collection_with_list_prop_odd, :collection_with_listprop_elem1]],
['listprop', 'contains', 'ELEM2', [], [:collection_with_list_prop_even]],
['listprop', 'contains', 'elem8', [], [:collection_with_list_prop_even]],
['listprop', 'contains', 4, [:collection_with_list_prop_even], [:collection_with_list_prop_odd, :collection_with_listprop_elem1]],
].each do |prop, op, opr, inc, ex|
test "jsonb filter properties.#{prop} #{op} #{opr})" do
@controller = Arvados::V1::CollectionsController.new
authorize_with :admin
get :index, params: {
filters: SafeJSON.dump([ ["properties.#{prop}", op, opr] ]),
limit: 1000
}
assert_response :success
found = assigns(:objects).collect(&:uuid)
inc.each do |i|
assert_includes(found, collections(i).uuid)
end
ex.each do |e|
assert_not_includes(found, collections(e).uuid)
end
end
end
test "jsonb hash 'exists' and '!=' filter" do
@controller = Arvados::V1::CollectionsController.new
authorize_with :admin
get :index, params: {
filters: [ ['properties.prop1', 'exists', true], ['properties.prop1', '!=', 'value1'] ]
}
assert_response :success
found = assigns(:objects).collect(&:uuid)
assert_equal found.length, 3
assert_not_includes(found, collections(:collection_with_prop1_value1).uuid)
assert_includes(found, collections(:collection_with_prop1_value2).uuid)
assert_includes(found, collections(:collection_with_prop1_value3).uuid)
assert_includes(found, collections(:collection_with_prop1_other1).uuid)
end
test "jsonb array 'exists'" do
@controller = Arvados::V1::CollectionsController.new
authorize_with :admin
get :index, params: {
filters: [ ['storage_classes_confirmed.default', 'exists', true] ]
}
assert_response :success
found = assigns(:objects).collect(&:uuid)
assert_equal 2, found.length
assert_not_includes(found,
collections(:storage_classes_desired_default_unconfirmed).uuid)
assert_includes(found,
collections(:storage_classes_desired_default_confirmed_default).uuid)
assert_includes(found,
collections(:storage_classes_desired_archive_confirmed_default).uuid)
end
test "jsonb hash alternate form 'exists' and '!=' filter" do
@controller = Arvados::V1::CollectionsController.new
authorize_with :admin
get :index, params: {
filters: [ ['properties', 'exists', 'prop1'], ['properties.prop1', '!=', 'value1'] ]
}
assert_response :success
found = assigns(:objects).collect(&:uuid)
assert_equal found.length, 3
assert_not_includes(found, collections(:collection_with_prop1_value1).uuid)
assert_includes(found, collections(:collection_with_prop1_value2).uuid)
assert_includes(found, collections(:collection_with_prop1_value3).uuid)
assert_includes(found, collections(:collection_with_prop1_other1).uuid)
end
test "jsonb array alternate form 'exists' filter" do
@controller = Arvados::V1::CollectionsController.new
authorize_with :admin
get :index, params: {
filters: [ ['storage_classes_confirmed', 'exists', 'default'] ]
}
assert_response :success
found = assigns(:objects).collect(&:uuid)
assert_equal 2, found.length
assert_not_includes(found,
collections(:storage_classes_desired_default_unconfirmed).uuid)
assert_includes(found,
collections(:storage_classes_desired_default_confirmed_default).uuid)
assert_includes(found,
collections(:storage_classes_desired_archive_confirmed_default).uuid)
end
test "jsonb 'exists' must be boolean" do
@controller = Arvados::V1::CollectionsController.new
authorize_with :admin
get :index, params: {
filters: [ ['properties.prop1', 'exists', nil] ]
}
assert_response 422
assert_match(/Invalid operand '' for 'exists' must be true or false/,
json_response['errors'].join(' '))
end
test "jsonb checks column exists" do
@controller = Arvados::V1::CollectionsController.new
authorize_with :admin
get :index, params: {
filters: [ ['puppies.prop1', '=', 'value1'] ]
}
assert_response 422
assert_match(/Invalid attribute 'puppies' for subproperty filter/,
json_response['errors'].join(' '))
end
test "jsonb checks column is valid" do
@controller = Arvados::V1::CollectionsController.new
authorize_with :admin
get :index, params: {
filters: [ ['name.prop1', '=', 'value1'] ]
}
assert_response 422
assert_match(/Invalid attribute 'name' for subproperty filter/,
json_response['errors'].join(' '))
end
test "jsonb invalid operator" do
@controller = Arvados::V1::CollectionsController.new
authorize_with :admin
get :index, params: {
filters: [ ['properties.prop1', '###', 'value1'] ]
}
assert_response 422
assert_match(/Invalid operator for subproperty search '###'/,
json_response['errors'].join(' '))
end
test "replication_desired = 2" do
@controller = Arvados::V1::CollectionsController.new
authorize_with :admin
get :index, params: {
filters: SafeJSON.dump([ ['replication_desired', '=', 2] ])
}
assert_response :success
found = assigns(:objects).collect(&:uuid)
assert_includes(found, collections(:replication_desired_2_unconfirmed).uuid)
assert_includes(found, collections(:replication_desired_2_confirmed_2).uuid)
end
end
| 43.823529 | 199 | 0.695585 |
1ae7cb9e6b775e31cf9a085d2f7bb6eaaec74547 | 3,157 | # frozen_string_literal: true
require 'spec_helper'
describe Lightning::Router::RouteFinder do
describe '#find' do
subject { described_class.find(source, target, updates, assisted_routes, assisted_channels) }
let(:public_key0) { '02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619' }
let(:public_key1) { '0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c' }
let(:public_key2) { '027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007' }
let(:public_key3) { '032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991' }
let(:public_key4) { '02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145' }
let(:source) { public_key0 }
let(:target) { public_key4 }
let(:updates) do
{
Lightning::Router::Messages::ChannelDesc[1, public_key1, public_key2] => build(:channel_update),
Lightning::Router::Messages::ChannelDesc[0, public_key0, public_key1] => build(:channel_update),
Lightning::Router::Messages::ChannelDesc[3, public_key4, public_key3] => build(:channel_update),
Lightning::Router::Messages::ChannelDesc[2, public_key2, public_key3] => build(:channel_update),
}
end
let(:assisted_routes) { [] }
let(:assisted_channels) { [] }
describe '1st node' do
it { expect(subject[0][:node_id]).to eq source }
end
describe 'next to 1st node' do
it { expect(subject[0][:next_node_id]).to eq public_key1 }
end
describe '2nd node' do
it { expect(subject[1][:node_id]).to eq public_key1 }
end
describe 'next to 2nd node' do
it { expect(subject[1][:next_node_id]).to eq public_key2 }
end
describe '3rd node' do
it { expect(subject[2][:node_id]).to eq public_key2 }
end
describe 'next to 3rd node' do
it { expect(subject[2][:next_node_id]).to eq public_key3 }
end
describe '4th node' do
it { expect(subject[3][:node_id]).to eq public_key3 }
end
describe 'next to 4th node' do
it { expect(subject[3][:next_node_id]).to eq public_key4 }
end
context 'has two route' do
let(:updates) do
{
Lightning::Router::Messages::ChannelDesc[1, public_key1, public_key4] => build(:channel_update),
Lightning::Router::Messages::ChannelDesc[0, public_key0, public_key1] => build(:channel_update),
Lightning::Router::Messages::ChannelDesc[2, public_key0, public_key4] => build(:channel_update),
}
end
context 'no assisted_channels' do
it { expect(subject.length).to eq 1 }
it { expect(subject[0][:node_id]).to eq public_key0 }
it { expect(subject[0][:next_node_id]).to eq public_key4 }
end
context 'with assisted_channels' do
let(:assisted_channels) { [0, 1] }
it { expect(subject.length).to eq 2 }
it { expect(subject[0][:node_id]).to eq public_key0 }
it { expect(subject[0][:next_node_id]).to eq public_key1 }
it { expect(subject[1][:node_id]).to eq public_key1 }
it { expect(subject[1][:next_node_id]).to eq public_key4 }
end
end
end
end | 38.036145 | 106 | 0.672474 |
110c98c9589afdbb0a145f766300a71764c68854 | 375 | require 'test_helper'
require_relative 'lua_generator_test'
class Apicast::LuaThreescaleUtilsGeneratorTest < Apicast::LuaGeneratorTest
def test_filename
super
assert_equal 'threescale_utils.lua', @generator.filename
end
def test_emit
super
assert config = @generator.emit(mock('provider'))
assert_match '-- threescale_utils.lua', config
end
end
| 23.4375 | 74 | 0.765333 |
28a2dd1dbc9245339bc58004f8675e4795960f38 | 886 | require 'spec_helper'
RSpec.describe LocaleSet do
describe "#for" do
subject { LocaleSet.new(['en_gb', 'EN-US', :es, :fr]).for(format) }
let!(:format) { :i18n }
it "converts each item to a string" do
subject.each do |item|
expect(item).to be_a(String)
end
end
it "removes duplicate items" do
@locale_set = LocaleSet.new([:es, :es])
expect(@locale_set).to have(1).item
end
context "when format is :i18n" do
let!(:format) { :i18n }
it "returns each item in i18n format" do
expect(subject).to eql(['en-GB', 'en-US', 'es', 'fr'].to_set)
end
end
context "when format is :fast_gettext" do
let!(:format) { :fast_gettext }
it "returns each item in fast_gettext format" do
expect(subject).to eql(['en_GB', 'en_US', 'es', 'fr'].to_set)
end
end
end
end
| 19.688889 | 71 | 0.58465 |
011136b0691a012d0994122c118d07689d977728 | 1,651 | require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
require File.expand_path(File.dirname(__FILE__) + '/../lib/pedump')
describe 'corkami/imports_vterm.exe' do
# http://code.google.com/p/corkami/source/browse/trunk/asm/PE/imports_vterm.asm
#describe "import terminator in virtual space" do
before :all do
@imports = sample.imports
end
it "should have 2 IMAGE_IMPORT_DESCRIPTORs" do
@imports.size.should == 2
end
it "should have only IMAGE_IMPORT_DESCRIPTORs" do
@imports.map(&:class).uniq.should == [PEdump::IMAGE_IMPORT_DESCRIPTOR]
end
# it "should have all entries thunks equal" do
# @imports.each do |iid|
# iid.first_thunk.should == iid.original_first_thunk
# end
# end
describe "1st image_import_descriptor" do
it "should be from kernel32.dll" do
@imports[0].module_name.should == "kernel32.dll"
end
it "should have 1 function" do
@imports[0].first_thunk.size.should == 1
end
it "should have ExitProcess" do
@imports[0].first_thunk.first.name.should == "ExitProcess"
@imports[0].first_thunk.first.hint.should == 0
@imports[0].first_thunk.first.ordinal.should be_nil
end
end
describe "2nd image_import_descriptor" do
it "should be from msvcrt.dll" do
@imports[1].module_name.should == "msvcrt.dll"
end
it "should have 1 function" do
@imports[1].first_thunk.size.should == 1
end
it "should have printf" do
@imports[1].first_thunk.first.name.should == "printf"
@imports[1].first_thunk.first.hint.should == 0
@imports[1].first_thunk.first.ordinal.should be_nil
end
end
end
| 31.150943 | 81 | 0.692913 |
e9be46097e6a4ed9ae0eb335a394081cbf00c8c8 | 15,051 | require_relative 'globals'
require_relative 'tunes/tunes_client'
module Spaceship
class Client
def handle_two_step_or_factor(response)
raise "2FA can only be performed in interactive mode" if ENV["SPACESHIP_ONLY_ALLOW_INTERACTIVE_2FA"] == "true" && ENV["FASTLANE_IS_INTERACTIVE"] == "false"
# extract `x-apple-id-session-id` and `scnt` from response, to be used by `update_request_headers`
@x_apple_id_session_id = response["x-apple-id-session-id"]
@scnt = response["scnt"]
# get authentication options
r = request(:get) do |req|
req.url("https://idmsa.apple.com/appleauth/auth")
update_request_headers(req)
end
if r.body.kind_of?(Hash) && r.body["trustedDevices"].kind_of?(Array)
handle_two_step(r)
elsif r.body.kind_of?(Hash) && r.body["trustedPhoneNumbers"].kind_of?(Array) && r.body["trustedPhoneNumbers"].first.kind_of?(Hash)
handle_two_factor(r)
else
raise "Although response from Apple indicated activated Two-step Verification or Two-factor Authentication, spaceship didn't know how to handle this response: #{r.body}"
end
end
def handle_two_step(response)
if response.body.fetch("securityCode", {})["tooManyCodesLock"].to_s.length > 0
raise Tunes::Error.new, "Too many verification codes have been sent. Enter the last code you received, use one of your devices, or try again later."
end
puts("Two-step Verification (4 digits code) is enabled for account '#{self.user}'")
puts("More information about Two-step Verification: https://support.apple.com/en-us/HT204152")
puts("")
puts("Please select a trusted device to verify your identity")
available = response.body["trustedDevices"].collect do |current|
"#{current['name']}\t#{current['modelName'] || 'SMS'}\t(#{current['id']})"
end
result = choose(*available)
device_id = result.match(/.*\t.*\t\((.*)\)/)[1]
handle_two_step_for_device(device_id)
end
# this is extracted into its own method so it can be called multiple times (see end)
def handle_two_step_for_device(device_id)
# Request token to device
r = request(:put) do |req|
req.url("https://idmsa.apple.com/appleauth/auth/verify/device/#{device_id}/securitycode")
update_request_headers(req)
end
# we use `Spaceship::TunesClient.new.handle_itc_response`
# since this might be from the Dev Portal, but for 2 step
Spaceship::TunesClient.new.handle_itc_response(r.body)
puts("Successfully requested notification")
code = ask("Please enter the 4 digit code: ")
puts("Requesting session...")
# Send token to server to get a valid session
r = request(:post) do |req|
req.url("https://idmsa.apple.com/appleauth/auth/verify/device/#{device_id}/securitycode")
req.headers['Content-Type'] = 'application/json'
req.body = { "code" => code.to_s }.to_json
update_request_headers(req)
end
begin
Spaceship::TunesClient.new.handle_itc_response(r.body) # this will fail if the code is invalid
rescue => ex
# If the code was entered wrong
# {
# "securityCode": {
# "code": "1234"
# },
# "securityCodeLocked": false,
# "recoveryKeyLocked": false,
# "recoveryKeySupported": true,
# "manageTrustedDevicesLinkName": "appleid.apple.com",
# "suppressResend": false,
# "authType": "hsa",
# "accountLocked": false,
# "validationErrors": [{
# "code": "-21669",
# "title": "Incorrect Verification Code",
# "message": "Incorrect verification code."
# }]
# }
if ex.to_s.include?("verification code") # to have a nicer output
puts("Error: Incorrect verification code")
return handle_two_step_for_device(device_id)
end
raise ex
end
store_session
return true
end
def handle_two_factor(response, depth = 0)
if depth == 0
puts("Two-factor Authentication (6 digits code) is enabled for account '#{self.user}'")
puts("More information about Two-factor Authentication: https://support.apple.com/en-us/HT204915")
puts("")
two_factor_url = "https://github.com/fastlane/fastlane/tree/master/spaceship#2-step-verification"
puts("If you're running this in a non-interactive session (e.g. server or CI)")
puts("check out #{two_factor_url}")
end
# "verification code" has already be pushed to devices
security_code = response.body["securityCode"]
# "securityCode": {
# "length": 6,
# "tooManyCodesSent": false,
# "tooManyCodesValidated": false,
# "securityCodeLocked": false
# },
code_length = security_code["length"]
puts("")
env_2fa_sms_default_phone_number = ENV["SPACESHIP_2FA_SMS_DEFAULT_PHONE_NUMBER"]
if env_2fa_sms_default_phone_number
raise Tunes::Error.new, "Environment variable SPACESHIP_2FA_SMS_DEFAULT_PHONE_NUMBER is set, but empty." if env_2fa_sms_default_phone_number.empty?
puts("Environment variable `SPACESHIP_2FA_SMS_DEFAULT_PHONE_NUMBER` is set, automatically requesting 2FA token via SMS to that number")
puts("SPACESHIP_2FA_SMS_DEFAULT_PHONE_NUMBER = #{env_2fa_sms_default_phone_number}")
puts("")
phone_number = env_2fa_sms_default_phone_number
phone_id = phone_id_from_number(response.body["trustedPhoneNumbers"], phone_number)
push_mode = push_mode_from_masked_number(response.body["trustedPhoneNumbers"], phone_number)
# don't request sms if no trusted devices and env default is the only trusted number,
# code was automatically sent
should_request_code = !sms_automatically_sent(response)
code_type = 'phone'
body = request_two_factor_code_from_phone(phone_id, phone_number, code_length, push_mode, should_request_code)
elsif sms_automatically_sent(response) # sms fallback, code was automatically sent
fallback_number = response.body["trustedPhoneNumbers"].first
phone_number = fallback_number["numberWithDialCode"]
phone_id = fallback_number["id"]
push_mode = fallback_number['pushMode']
code_type = 'phone'
body = request_two_factor_code_from_phone(phone_id, phone_number, code_length, push_mode, false)
elsif sms_fallback(response) # sms fallback but code wasn't sent bec > 1 phone number
code_type = 'phone'
body = request_two_factor_code_from_phone_choose(response.body["trustedPhoneNumbers"], code_length)
else
puts("(Input `sms` to escape this prompt and select a trusted phone number to send the code as a text message)")
puts("")
puts("(You can also set the environment variable `SPACESHIP_2FA_SMS_DEFAULT_PHONE_NUMBER` to automate this)")
puts("(Read more at: https://github.com/fastlane/fastlane/blob/master/spaceship/docs/Authentication.md#auto-select-sms-via-spaceship_2fa_sms_default_phone_number)")
puts("")
code = ask_for_2fa_code("Please enter the #{code_length} digit code:")
code_type = 'trusteddevice'
body = { "securityCode" => { "code" => code.to_s } }.to_json
# User exited by entering `sms` and wants to choose phone number for SMS
if code == 'sms'
code_type = 'phone'
body = request_two_factor_code_from_phone_choose(response.body["trustedPhoneNumbers"], code_length)
end
end
puts("Requesting session...")
# Send "verification code" back to server to get a valid session
r = request(:post) do |req|
req.url("https://idmsa.apple.com/appleauth/auth/verify/#{code_type}/securitycode")
req.headers['Content-Type'] = 'application/json'
req.body = body
update_request_headers(req)
end
begin
# we use `Spaceship::TunesClient.new.handle_itc_response`
# since this might be from the Dev Portal, but for 2 factor
Spaceship::TunesClient.new.handle_itc_response(r.body) # this will fail if the code is invalid
rescue => ex
# If the code was entered wrong
# {
# "service_errors": [{
# "code": "-21669",
# "title": "Incorrect Verification Code",
# "message": "Incorrect verification code."
# }],
# "hasError": true
# }
if ex.to_s.include?("verification code") # to have a nicer output
puts("Error: Incorrect verification code")
depth += 1
return handle_two_factor(response, depth)
end
raise ex
end
store_session
return true
end
# For reference in case auth behavior changes:
# The "noTrustedDevices" field is only present
# in the response for `GET /appleauth/auth`
# Account is not signed into any devices that can display a verification code
def sms_fallback(response)
response.body["noTrustedDevices"]
end
# see `sms_fallback` + account has only one trusted number for receiving an sms
def sms_automatically_sent(response)
(response.body["trustedPhoneNumbers"] || []).count == 1 && sms_fallback(response)
end
# extracted into its own method for testing
def ask_for_2fa_code(text)
ask(text)
end
# extracted into its own method for testing
def choose_phone_number(opts)
choose(*opts)
end
def phone_id_from_number(phone_numbers, phone_number)
characters_to_remove_from_phone_numbers = ' \-()"'
# start with e.g. +49 162 1234585 or +1-123-456-7866
phone_number = phone_number.tr(characters_to_remove_from_phone_numbers, '')
# cleaned: +491621234585 or +11234567866
phone_numbers.each do |phone|
# rubocop:disable Style/AsciiComments
# start with: +49 •••• •••••85 or +1 (•••) •••-••66
number_with_dialcode_masked = phone['numberWithDialCode'].tr(characters_to_remove_from_phone_numbers, '')
# cleaned: +49•••••••••85 or +1••••••••66
# rubocop:enable Style/AsciiComments
maskings_count = number_with_dialcode_masked.count('•') # => 9 or 8
pattern = /^([0-9+]{2,4})([•]{#{maskings_count}})([0-9]{2})$/
# following regex: range from maskings_count-2 because sometimes the masked number has 1 or 2 dots more than the actual number
# e.g. https://github.com/fastlane/fastlane/issues/14969
replacement = "\\1([0-9]{#{maskings_count - 2},#{maskings_count}})\\3"
number_with_dialcode_regex_part = number_with_dialcode_masked.gsub(pattern, replacement)
# => +49([0-9]{8,9})85 or +1([0-9]{7,8})66
backslash = '\\'
number_with_dialcode_regex_part = backslash + number_with_dialcode_regex_part
number_with_dialcode_regex = /^#{number_with_dialcode_regex_part}$/
# => /^\+49([0-9]{8})85$/ or /^\+1([0-9]{7,8})66$/
return phone['id'] if phone_number =~ number_with_dialcode_regex
# +491621234585 matches /^\+49([0-9]{8})85$/
end
# Handle case of phone_number not existing in phone_numbers because ENV var is wrong or matcher is broken
raise Tunes::Error.new, %(
Could not find a matching phone number to #{phone_number} in #{phone_numbers}.
Make sure your environment variable is set to the correct phone number.
If it is, please open an issue at https://github.com/fastlane/fastlane/issues/new and include this output so we can fix our matcher. Thanks.
)
end
def phone_id_from_masked_number(phone_numbers, masked_number)
phone_numbers.each do |phone|
return phone['id'] if phone['numberWithDialCode'] == masked_number
end
end
def push_mode_from_masked_number(phone_numbers, masked_number)
phone_numbers.each do |phone|
return phone['pushMode'] if phone['numberWithDialCode'] == masked_number
end
# If no pushMode was supplied, assume sms
return "sms"
end
def request_two_factor_code_from_phone_choose(phone_numbers, code_length)
puts("Please select a trusted phone number to send code to:")
available = phone_numbers.collect do |current|
current['numberWithDialCode']
end
chosen = choose_phone_number(available)
phone_id = phone_id_from_masked_number(phone_numbers, chosen)
push_mode = push_mode_from_masked_number(phone_numbers, chosen)
request_two_factor_code_from_phone(phone_id, chosen, code_length, push_mode)
end
# this is used in two places: after choosing a phone number and when a phone number is set via ENV var
def request_two_factor_code_from_phone(phone_id, phone_number, code_length, push_mode = "sms", should_request_code = true)
if should_request_code
# Request code
r = request(:put) do |req|
req.url("https://idmsa.apple.com/appleauth/auth/verify/phone")
req.headers['Content-Type'] = 'application/json'
req.body = { "phoneNumber" => { "id" => phone_id }, "mode" => push_mode }.to_json
update_request_headers(req)
end
# we use `Spaceship::TunesClient.new.handle_itc_response`
# since this might be from the Dev Portal, but for 2 step
Spaceship::TunesClient.new.handle_itc_response(r.body)
puts("Successfully requested text message to #{phone_number}")
end
code = ask_for_2fa_code("Please enter the #{code_length} digit code you received at #{phone_number}:")
return { "securityCode" => { "code" => code.to_s }, "phoneNumber" => { "id" => phone_id }, "mode" => push_mode }.to_json
end
def store_session
# If the request was successful, r.body is actually nil
# The previous request will fail if the user isn't on a team
# on App Store Connect, but it still works, so we're good
# Tell iTC that we are trustworthy (obviously)
# This will update our local cookies to something new
# They probably have a longer time to live than the other poor cookies
# Changed Keys
# - myacinfo
# - DES5c148586dfd451e55afb0175f62418f91
# We actually only care about the DES value
request(:get) do |req|
req.url("https://idmsa.apple.com/appleauth/auth/2sv/trust")
update_request_headers(req)
end
# This request will fail if the user isn't added to a team on iTC
# However we don't really care, this request will still return the
# correct DES... cookie
self.store_cookie
end
# Responsible for setting all required header attributes for the requests
# to succeed
def update_request_headers(req)
req.headers["X-Apple-Id-Session-Id"] = @x_apple_id_session_id
req.headers["X-Apple-Widget-Key"] = self.itc_service_key
req.headers["Accept"] = "application/json"
req.headers["scnt"] = @scnt
end
end
end
| 41.808333 | 177 | 0.664607 |
f8e1361e18cd482922d6042c78cd2eb7202b387b | 167 | class RolesRepository
def all
@all ||= Role.includes(:users).all
end
def all_technical
all.technical
end
def all_by_name
all.by_name
end
end
| 11.928571 | 38 | 0.676647 |
2854376db7464646d5ebba282ef460110698ea04 | 231 | # frozen_string_literal: true
RSpec.describe DxrubyEditor do
it 'has a version number' do
expect(DxrubyEditor::VERSION).not_to be nil
end
it 'does something useful' do
expect(false).to eq(true)
end
end
| 19.25 | 48 | 0.692641 |
21de6750e0688fd69bab0416737a761d39cccc99 | 9,846 | #!/usr/bin/env ruby
$:.unshift(File.dirname(__FILE__) + '/../lib')
require 'rubygems'
require 'bundler'
Bundler.setup
require 'test/unit'
require 'active_shipping'
require 'mocha'
XmlNode # trigger autorequire
module Test
module Unit
class TestCase
include ActiveMerchant::Shipping
LOCAL_CREDENTIALS = ENV['HOME'] + '/.active_merchant/fixtures.yml' unless defined?(LOCAL_CREDENTIALS)
DEFAULT_CREDENTIALS = File.dirname(__FILE__) + '/fixtures.yml' unless defined?(DEFAULT_CREDENTIALS)
MODEL_FIXTURES = File.dirname(__FILE__) + '/fixtures/' unless defined?(MODEL_FIXTURES)
def all_fixtures
@@fixtures ||= load_fixtures
end
def fixtures(key)
data = all_fixtures[key] || raise(StandardError, "No fixture data was found for '#{key}'")
data.dup
end
def load_fixtures
file = File.exists?(LOCAL_CREDENTIALS) ? LOCAL_CREDENTIALS : DEFAULT_CREDENTIALS
yaml_data = YAML.load(File.read(file))
model_fixtures = Dir.glob(File.join(MODEL_FIXTURES,'**','*.yml'))
model_fixtures.each do |file|
name = File.basename(file, '.yml')
yaml_data[name] = YAML.load(File.read(file))
end
symbolize_keys(yaml_data)
yaml_data
end
def xml_fixture(path) # where path is like 'usps/beverly_hills_to_ottawa_response'
open(File.join(File.dirname(__FILE__),'fixtures','xml',"#{path}.xml")) {|f| f.read}
end
def json_fixture(path) # where path is like 'usps/beverly_hills_to_ottawa_response'
open(File.join(File.dirname(__FILE__),'fixtures','json',"#{path}.json")) {|f| f.read}
end
def symbolize_keys(hash)
return unless hash.is_a?(Hash)
hash.symbolize_keys!
hash.each{|k,v| symbolize_keys(v)}
end
end
end
end
module ActiveMerchant
module Shipping
module TestFixtures
mattr_reader :packages, :locations
@@packages = {
:just_ounces => Package.new(16, nil, :units => :imperial),
:just_grams => Package.new(1000, nil),
:just_zero_grams => Package.new(0, nil),
:all_imperial => Package.new(16, [1,8,12], :units => :imperial),
:all_metric => Package.new(1000, [2,20,40]),
:book => Package.new(250, [14, 19, 2]),
:wii => Package.new((7.5 * 16), [15, 10, 4.5], :units => :imperial, :value => 269.99, :currency => 'GBP'),
:american_wii => Package.new((7.5 * 16), [15, 10, 4.5], :units => :imperial, :value => 269.99, :currency => 'USD'),
:new_zealand_wii => Package.new((7.5 * 16), [15, 10, 4.5], :units => :imperial, :value => 269.99, :currency => 'NZD'),
:worthless_wii => Package.new((7.5 * 16), [15, 10, 4.5], :units => :imperial, :value => 0.0, :currency => 'USD'),
:poster => Package.new(100, [93,10], :cylinder => true),
:small_half_pound => Package.new(8, [1,1,1], :units => :imperial),
:big_half_pound => Package.new((16 * 50), [24,24,36], :units => :imperial),
:chocolate_stuff => Package.new(80, [2,6,12], :units => :imperial),
:shipping_container => Package.new(2200000, [2440, 2600, 6058], :description => '20 ft Standard Container', :units => :metric),
:largest_gold_bar => Package.new(250000, [ 45.5, 22.5, 17 ], :value => 15300000)
}
@@locations = {
:bare_ottawa => Location.new(:country => 'CA', :postal_code => 'K1P 1J1'),
:bare_beverly_hills => Location.new(:country => 'US', :zip => '90210'),
:ottawa => Location.new( :country => 'CA',
:province => 'ON',
:city => 'Ottawa',
:address1 => '110 Laurier Avenue West',
:postal_code => 'K1P 1J1',
:phone => '1-613-580-2400',
:fax => '1-613-580-2495'),
:beverly_hills => Location.new(
:country => 'US',
:state => 'CA',
:city => 'Beverly Hills',
:address1 => '455 N. Rexford Dr.',
:address2 => '3rd Floor',
:zip => '90210',
:phone => '1-310-285-1013',
:fax => '1-310-275-8159'),
:real_home_as_commercial => Location.new(
:country => 'US',
:city => 'Tampa',
:state => 'FL',
:address1 => '7926 Woodvale Circle',
:zip => '33615',
:address_type => 'commercial'), # means that UPS will default to commercial if it doesn't know
:fake_home_as_commercial => Location.new(
:country => 'US',
:state => 'FL',
:address1 => '123 fake st.',
:zip => '33615',
:address_type => 'commercial'),
:real_google_as_commercial => Location.new(
:country => 'US',
:city => 'Mountain View',
:state => 'CA',
:address1 => '1600 Amphitheatre Parkway',
:zip => '94043',
:address_type => 'commercial'),
:real_google_as_residential => Location.new(
:country => 'US',
:city => 'Mountain View',
:state => 'CA',
:address1 => '1600 Amphitheatre Parkway',
:zip => '94043',
:address_type => 'residential'), # means that will default to residential if it doesn't know
:fake_google_as_commercial => Location.new(
:country => 'US',
:city => 'Mountain View',
:state => 'CA',
:address1 => '123 bogusland dr.',
:zip => '94043',
:address_type => 'commercial'),
:fake_google_as_residential => Location.new(
:country => 'US',
:city => 'Mountain View',
:state => 'CA',
:address1 => '123 bogusland dr.',
:zip => '94043',
:address_type => 'residential'), # means that will default to residential if it doesn't know
:fake_home_as_residential => Location.new(
:country => 'US',
:state => 'FL',
:address1 => '123 fake st.',
:zip => '33615',
:address_type => 'residential'),
:real_home_as_residential => Location.new(
:country => 'US',
:city => 'Tampa',
:state => 'FL',
:address1 => '7926 Woodvale Circle',
:zip => '33615',
:address_type => 'residential'),
:london => Location.new(
:country => 'GB',
:city => 'London',
:address1 => '170 Westminster Bridge Rd.',
:zip => 'SE1 7RW'),
:new_york => Location.new(
:country => 'US',
:city => 'New York',
:state => 'NY',
:address1 => '780 3rd Avenue',
:address2 => 'Suite 2601',
:zip => '10017'),
:new_york_with_name => Location.new(
:name => "Bob Bobsen",
:country => 'US',
:city => 'New York',
:state => 'NY',
:address1 => '780 3rd Avenue',
:address2 => 'Suite 2601',
:zip => '10017'),
:wellington => Location.new(
:country => 'NZ',
:city => 'Wellington',
:address1 => '85 Victoria St',
:address2 => 'Te Aro',
:postal_code => '6011'),
:auckland => Location.new(
:country => 'NZ',
:city => 'Auckland',
:address1 => '192 Victoria St West',
:postal_code => '1010')
}
end
end
end
| 48.502463 | 135 | 0.400264 |
bb65a115be01177f56138be4d89013d358b64aec | 144 | require 'elasticsearch/rails/instrumentation/railtie'
module Elasticsearch
module Persistence
module Instrumentation
end
end
end
| 13.090909 | 53 | 0.784722 |
ff60300902afef6572bf8d20f63b45ba3d9f43d1 | 1,069 | # frozen_string_literal: true
Rails.application.configure do
config.cache_classes = false
config.eager_load = false
config.consider_all_requests_local = true
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age=172800',
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
config.active_support.deprecation = :log
config.active_record.migration_error = :page_load
config.assets.debug = true
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
config.logger = Logger.new(Rails.root.join('log', 'development.log'), 1, 100 * 1024)
config.after_initialize do
Bullet.enable = true
Bullet.bullet_logger = true
Bullet.console = true
Bullet.rails_logger = true
Bullet.add_footer = true
end
end
| 30.542857 | 86 | 0.751169 |
fff57184292070c710dcbc1d034c2d0398ad8f8d | 4,027 | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Product.create(
name: "Haitian Blue Mountain",
image: "https://images.unsplash.com/photo-1580933073521-dc49ac0d4e6a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1949&q=80",
category: "Food",
description: "Medium Roast - 1 lb of coffee beans from Bason Coffee Roasting - Grind: Drip",
price: 12.00,
stock: 25
)
Product.create(
name: "Colombian Supremo Medium Roast",
image: "https://images.unsplash.com/photo-1580933073521-dc49ac0d4e6a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1949&q=80",
category: "Food",
description: "1 lb of coffee beans from Bason Coffee Roasting - Grind: Drip",
price: 8.00,
stock: 25
)
Product.create(
name: "Fall Wildflower Honey",
image: "https://images.unsplash.com/photo-1550411294-098af68c8c2d?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=934&q=80",
category: "Food",
description: "Keiner's Apiary local honey - Save our bees!",
price: 9.50,
stock: 25
)
Product.create(
name: "Wildflower Honey",
image: "https://images.unsplash.com/photo-1550411294-098af68c8c2d?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=934&q=80",
category: "Food",
description: "Keiner's Apiary local honey - Save our bees!",
price: 9.50,
stock: 30
)
Product.create(
name: "Ginger Peach - Gayle's Kombucha",
image: "https://gayleskombucha.com/wp-content/uploads/2020/05/Six-bottles-on-back-porch-rail-2048x1099.jpg",
category: "Drinks",
description: "The zesty flavor of ginger paired with peaches giving this kombucha a finishing taste of fresh picked peaches.",
price: 6.50,
stock: 15
)
Product.create(
name: "Mountains",
image: "https://scontent-iad3-2.xx.fbcdn.net/v/t1.6435-9/185039451_291915769084557_8742994522455112830_n.jpg?_nc_cat=100&ccb=1-3&_nc_sid=a26aad&_nc_ohc=4gUVXbOkNKQAX_9-_ej&_nc_ht=scontent-iad3-2.xx&oh=53a477d56c5b660cdaa0997d9e95c6b3&oe=60CC3369",
category: "Decor",
description: "To the mountains we go to find ourselves. Kerri Lovette Designs",
price: 60,
stock: 5
)
Product.create(
name: "Wall Mount Grandma Clip Sign",
image: "https://scontent-iad3-2.xx.fbcdn.net/v/t1.6435-9/182341554_288599946082806_6853644690957395965_n.jpg?_nc_cat=111&ccb=1-3&_nc_sid=a26aad&_nc_ohc=e5tl8a32xwIAX9lhTbb&_nc_oc=AQm2V4xIJx_o5nvo3hgBCmhLyAzlcHrpApy1nIzZbHOIJI1rnFQEu1NV8cy7ye6q36A&_nc_ht=scontent-iad3-2.xx&oh=3506b27335fc5feeaf35e86991218fa9&oe=60CE8118",
category: "Decor",
description: "My greatest blessing call me GRANDMA. Kerri Lovette Designs",
price: 25,
stock: 5
)
Product.create(
name: "Wall Mount Mom Clip Sign",
image: "https://scontent-iad3-2.xx.fbcdn.net/v/t1.6435-9/182055609_287952156147585_3085251966797354300_n.jpg?_nc_cat=103&ccb=1-3&_nc_sid=a26aad&_nc_ohc=0POLkfek-GgAX8eF-bk&_nc_ht=scontent-iad3-2.xx&oh=70857f350e9587e6ee31e3ebe1b39214&oe=60CD465B",
category: "Decor",
description: "If mothers were flowers I would pick you. Kerri Lovette Designs",
price: 25,
stock: 5
)
Product.create(
name: "Wood Earrings",
image: "https://scontent-iad3-2.xx.fbcdn.net/v/t1.6435-9/183087838_290053052604162_6443301198184404802_n.jpg?_nc_cat=101&ccb=1-3&_nc_sid=a26aad&_nc_ohc=4G1H9HTfZIAAX83D5pR&_nc_ht=scontent-iad3-2.xx&oh=f1bcd4b73a38b42db6a30a2caaf3d376&oe=60CF9C3F",
category: "Fashion",
description: "Come see my new hobby with wood earring. Light and non allergenic metal used. Kerri Lovette Designs",
price: 18,
stock: 5
) | 44.744444 | 326 | 0.740998 |
ac91d3770e6eec327811c6e1143c11c269b54cee | 627 | require 'rails_helper'
module Subscribem
RSpec.describe AccountsController, type: :controller do
context 'creates the account schema' do
let!(:account) { Subscribem::Account.new }
before do
expect(Subscribem::Account).to receive(:create_with_owner).and_return(account)
allow(account).to receive(:valid?).and_return(true)
allow(controller).to receive(:force_authentication!).and_return(true)
end
specify do
expect(account).to receive(:create_schema)
post :create, account: { name: 'First Account'}, use_route: :subscribem
end
end
end
end
| 31.35 | 86 | 0.681021 |
ac2fb78b0a29cf90e4be9e6ff07f721527dd22c1 | 1,699 | module Abstractor
##
# A collection of helper methods used in the Abstactor user interface.
module UserInterface
#2/16/2014 MGURLEY Stolen from http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html. Rails 3.2.16.
# Removed the cleverness trying skip highlighting content it thinks is html markup.
def self.highlight(text, phrases, *args)
options = args.extract_options!
unless args.empty?
options[:highlighter] = args[0] || '<strong class="abstractor_highlight">\1</strong>'
end
options.reverse_merge!(:highlighter => '<strong class="abstractor_highlight">\1</strong>')
# text = sanitize(text) unless options[:sanitize] == false
if text.blank? || phrases.blank?
text
else
match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')
text = text.gsub(/(#{match})/i) { |m| options[:highlighter].gsub('\\1', m) }
end.html_safe
end
##
# Transforms a path to account for a relative url root.
# URL helpers in Rails Engine views and partials embedded in view in the host application don't play well with relative url roots.
# @param path [String] the URL path that should have a relative prefix added if needed
# @return [String] the processed URL
def self.abstractor_relative_path(path)
prefix = Rails.application.config.action_controller.relative_url_root
if prefix.blank? || path.include?(prefix)
url = path
else
url = prefix + path
end
url
end
def self.generate_source_id(source)
"#{source[:source_type].to_s}_#{source[:source_id]}_#{source[:source_method]}"
end
end
end | 38.613636 | 134 | 0.662743 |
bf9fc240aa9411ee2d20e037a8be9be4c9694c69 | 1,218 | require "csv"
module FlatFile
module CSV
# Read a CSV file and return its contents as an array of hashes.
#
# @param filepath [String] Path to the CSV file.
# @return [Array<Hash>]
def self.from_file(filepath)
rows = []
begin
::CSV.foreach(filepath, headers: true) do |row|
rows.append(row)
end
return rows
rescue StandardError => e
# if defined?(Rails)
# Rails.logger.error({
# message: "Error reading CSV file",
# filepath: filepath,
# error: e,
# })
# end
return rows
end
end
# Read a CSV stream and return its contents as an array of hashes.
#
# @param data [String, IO] Stream of CSV data.
# @return [Array<Hash>]
def self.from_stream(data)
rows = []
begin
::CSV.new(data, headers: true).each do |row|
rows.append(row)
end
return rows
rescue StandardError => e
# if defined?(Rails)
# Rails.logger.error({
# message: "Error reading CSV data",
# error: e,
# })
# end
return rows
end
end
end
end
| 22.981132 | 70 | 0.520525 |
9147e95a1f72ab65e08c67310e80328808a06432 | 53 | json.array! @tacos, partial: "tacos/taco", as: :taco
| 26.5 | 52 | 0.679245 |
f7730f9135d0c37b7f48cbf7d745400c87e651dd | 395 | module Api
module V1
class OneSidedFollowersController < ::Api::V1::Base
private
def summary_uids(limit: 3)
uids = @twitter_user.one_sided_followerships.limit(limit).pluck(:follower_uid)
size = @twitter_user.one_sided_followerships.size
[uids, size]
end
def list_users
@twitter_user.one_sided_followers
end
end
end
end | 21.944444 | 86 | 0.663291 |
265977b6cfe5d65f520c7066d035d3f5ebb02d72 | 774 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# 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.
# Cookbook Name:: cpe_dconf
# Recipe:: default
return unless node.fedora?
cpe_kernel_channel 'Configure kernel channel' do
only_if { node['cpe_kernel_channel']['enable'] }
end
| 33.652174 | 74 | 0.760982 |
0806665c27f0044e4d3b66fe284397bd349d18f1 | 13,683 | # frozen_string_literal: true
# Tests the base functionality that should be identical across all cache stores.
module CacheStoreBehavior
def test_should_read_and_write_strings
assert @cache.write("foo", "bar")
assert_equal "bar", @cache.read("foo")
end
def test_should_overwrite
@cache.write("foo", "bar")
@cache.write("foo", "baz")
assert_equal "baz", @cache.read("foo")
end
def test_fetch_without_cache_miss
@cache.write("foo", "bar")
assert_not_called(@cache, :write) do
assert_equal "bar", @cache.fetch("foo") { "baz" }
end
end
def test_fetch_with_cache_miss
assert_called_with(@cache, :write, ["foo", "baz", @cache.options]) do
assert_equal "baz", @cache.fetch("foo") { "baz" }
end
end
def test_fetch_with_cache_miss_passes_key_to_block
cache_miss = false
assert_equal 3, @cache.fetch("foo") { |key| cache_miss = true; key.length }
assert cache_miss
cache_miss = false
assert_equal 3, @cache.fetch("foo") { |key| cache_miss = true; key.length }
assert !cache_miss
end
def test_fetch_with_forced_cache_miss
@cache.write("foo", "bar")
assert_not_called(@cache, :read) do
assert_called_with(@cache, :write, ["foo", "bar", @cache.options.merge(force: true)]) do
@cache.fetch("foo", force: true) { "bar" }
end
end
end
def test_fetch_with_cached_nil
@cache.write("foo", nil)
assert_not_called(@cache, :write) do
assert_nil @cache.fetch("foo") { "baz" }
end
end
def test_fetch_with_forced_cache_miss_with_block
@cache.write("foo", "bar")
assert_equal "foo_bar", @cache.fetch("foo", force: true) { "foo_bar" }
end
def test_fetch_with_forced_cache_miss_without_block
@cache.write("foo", "bar")
assert_raises(ArgumentError) do
@cache.fetch("foo", force: true)
end
assert_equal "bar", @cache.read("foo")
end
def test_should_read_and_write_hash
assert @cache.write("foo", a: "b")
assert_equal({ a: "b" }, @cache.read("foo"))
end
def test_should_read_and_write_integer
assert @cache.write("foo", 1)
assert_equal 1, @cache.read("foo")
end
def test_should_read_and_write_nil
assert @cache.write("foo", nil)
assert_nil @cache.read("foo")
end
def test_should_read_and_write_false
assert @cache.write("foo", false)
assert_equal false, @cache.read("foo")
end
def test_read_multi
@cache.write("foo", "bar")
@cache.write("fu", "baz")
@cache.write("fud", "biz")
assert_equal({ "foo" => "bar", "fu" => "baz" }, @cache.read_multi("foo", "fu"))
end
def test_read_multi_with_expires
time = Time.now
@cache.write("foo", "bar", expires_in: 10)
@cache.write("fu", "baz")
@cache.write("fud", "biz")
Time.stub(:now, time + 11) do
assert_equal({ "fu" => "baz" }, @cache.read_multi("foo", "fu"))
end
end
def test_fetch_multi
@cache.write("foo", "bar")
@cache.write("fud", "biz")
values = @cache.fetch_multi("foo", "fu", "fud") { |value| value * 2 }
assert_equal({ "foo" => "bar", "fu" => "fufu", "fud" => "biz" }, values)
assert_equal("fufu", @cache.read("fu"))
end
def test_fetch_multi_without_expires_in
@cache.write("foo", "bar")
@cache.write("fud", "biz")
values = @cache.fetch_multi("foo", "fu", "fud", expires_in: nil) { |value| value * 2 }
assert_equal({ "foo" => "bar", "fu" => "fufu", "fud" => "biz" }, values)
assert_equal("fufu", @cache.read("fu"))
end
def test_multi_with_objects
cache_struct = Struct.new(:cache_key, :title)
foo = cache_struct.new("foo", "FOO!")
bar = cache_struct.new("bar")
@cache.write("bar", "BAM!")
values = @cache.fetch_multi(foo, bar) { |object| object.title }
assert_equal({ foo => "FOO!", bar => "BAM!" }, values)
end
def test_fetch_multi_without_block
assert_raises(ArgumentError) do
@cache.fetch_multi("foo")
end
end
# Use strings that are guarenteed to compress well, so we can easily tell if
# the compression kicked in or not.
SMALL_STRING = "0" * 100
LARGE_STRING = "0" * 2.kilobytes
SMALL_OBJECT = { data: SMALL_STRING }
LARGE_OBJECT = { data: LARGE_STRING }
def test_nil_with_default_compression_settings
assert_uncompressed(nil)
end
def test_nil_with_compress_true
assert_uncompressed(nil, compress: true)
end
def test_nil_with_compress_false
assert_uncompressed(nil, compress: false)
end
def test_nil_with_compress_low_compress_threshold
assert_uncompressed(nil, compress: true, compress_threshold: 1)
end
def test_small_string_with_default_compression_settings
assert_uncompressed(SMALL_STRING)
end
def test_small_string_with_compress_true
assert_uncompressed(SMALL_STRING, compress: true)
end
def test_small_string_with_compress_false
assert_uncompressed(SMALL_STRING, compress: false)
end
def test_small_string_with_low_compress_threshold
assert_compressed(SMALL_STRING, compress: true, compress_threshold: 1)
end
def test_small_object_with_default_compression_settings
assert_uncompressed(SMALL_OBJECT)
end
def test_small_object_with_compress_true
assert_uncompressed(SMALL_OBJECT, compress: true)
end
def test_small_object_with_compress_false
assert_uncompressed(SMALL_OBJECT, compress: false)
end
def test_small_object_with_low_compress_threshold
assert_compressed(SMALL_OBJECT, compress: true, compress_threshold: 1)
end
def test_large_string_with_default_compression_settings
assert_compressed(LARGE_STRING)
end
def test_large_string_with_compress_true
assert_compressed(LARGE_STRING, compress: true)
end
def test_large_string_with_compress_false
assert_uncompressed(LARGE_STRING, compress: false)
end
def test_large_string_with_high_compress_threshold
assert_uncompressed(LARGE_STRING, compress: true, compress_threshold: 1.megabyte)
end
def test_large_object_with_default_compression_settings
assert_compressed(LARGE_OBJECT)
end
def test_large_object_with_compress_true
assert_compressed(LARGE_OBJECT, compress: true)
end
def test_large_object_with_compress_false
assert_uncompressed(LARGE_OBJECT, compress: false)
end
def test_large_object_with_high_compress_threshold
assert_uncompressed(LARGE_OBJECT, compress: true, compress_threshold: 1.megabyte)
end
def test_incompressable_data
assert_uncompressed(nil, compress: true, compress_threshold: 1)
assert_uncompressed(true, compress: true, compress_threshold: 1)
assert_uncompressed(false, compress: true, compress_threshold: 1)
assert_uncompressed(0, compress: true, compress_threshold: 1)
assert_uncompressed(1.2345, compress: true, compress_threshold: 1)
assert_uncompressed("", compress: true, compress_threshold: 1)
incompressible = nil
# generate an incompressible string
loop do
incompressible = SecureRandom.bytes(1.kilobyte)
break if incompressible.bytesize < Zlib::Deflate.deflate(incompressible).bytesize
end
assert_uncompressed(incompressible, compress: true, compress_threshold: 1)
end
def test_cache_key
obj = Object.new
def obj.cache_key
:foo
end
@cache.write(obj, "bar")
assert_equal "bar", @cache.read("foo")
end
def test_param_as_cache_key
obj = Object.new
def obj.to_param
"foo"
end
@cache.write(obj, "bar")
assert_equal "bar", @cache.read("foo")
end
def test_unversioned_cache_key
obj = Object.new
def obj.cache_key
"foo"
end
def obj.cache_key_with_version
"foo-v1"
end
@cache.write(obj, "bar")
assert_equal "bar", @cache.read("foo")
end
def test_array_as_cache_key
@cache.write([:fu, "foo"], "bar")
assert_equal "bar", @cache.read("fu/foo")
end
def test_hash_as_cache_key
@cache.write({ foo: 1, fu: 2 }, "bar")
assert_equal "bar", @cache.read("foo=1/fu=2")
end
def test_keys_are_case_sensitive
@cache.write("foo", "bar")
assert_nil @cache.read("FOO")
end
def test_exist
@cache.write("foo", "bar")
assert_equal true, @cache.exist?("foo")
assert_equal false, @cache.exist?("bar")
end
def test_nil_exist
@cache.write("foo", nil)
assert @cache.exist?("foo")
end
def test_delete
@cache.write("foo", "bar")
assert @cache.exist?("foo")
assert @cache.delete("foo")
assert !@cache.exist?("foo")
end
def test_original_store_objects_should_not_be_immutable
bar = "bar".dup
@cache.write("foo", bar)
assert_nothing_raised { bar.gsub!(/.*/, "baz") }
end
def test_expires_in
time = Time.local(2008, 4, 24)
Time.stub(:now, time) do
@cache.write("foo", "bar")
assert_equal "bar", @cache.read("foo")
end
Time.stub(:now, time + 30) do
assert_equal "bar", @cache.read("foo")
end
Time.stub(:now, time + 61) do
assert_nil @cache.read("foo")
end
end
def test_race_condition_protection_skipped_if_not_defined
@cache.write("foo", "bar")
time = @cache.send(:read_entry, @cache.send(:normalize_key, "foo", {}), {}).expires_at
Time.stub(:now, Time.at(time)) do
result = @cache.fetch("foo") do
assert_nil @cache.read("foo")
"baz"
end
assert_equal "baz", result
end
end
def test_race_condition_protection_is_limited
time = Time.now
@cache.write("foo", "bar", expires_in: 60)
Time.stub(:now, time + 71) do
result = @cache.fetch("foo", race_condition_ttl: 10) do
assert_nil @cache.read("foo")
"baz"
end
assert_equal "baz", result
end
end
def test_race_condition_protection_is_safe
time = Time.now
@cache.write("foo", "bar", expires_in: 60)
Time.stub(:now, time + 61) do
begin
@cache.fetch("foo", race_condition_ttl: 10) do
assert_equal "bar", @cache.read("foo")
raise ArgumentError.new
end
rescue ArgumentError
end
assert_equal "bar", @cache.read("foo")
end
Time.stub(:now, time + 91) do
assert_nil @cache.read("foo")
end
end
def test_race_condition_protection
time = Time.now
@cache.write("foo", "bar", expires_in: 60)
Time.stub(:now, time + 61) do
result = @cache.fetch("foo", race_condition_ttl: 10) do
assert_equal "bar", @cache.read("foo")
"baz"
end
assert_equal "baz", result
end
end
def test_crazy_key_characters
crazy_key = "#/:*(<+=> )&$%@?;'\"\'`~-"
assert @cache.write(crazy_key, "1", raw: true)
assert_equal "1", @cache.read(crazy_key)
assert_equal "1", @cache.fetch(crazy_key)
assert @cache.delete(crazy_key)
assert_equal "2", @cache.fetch(crazy_key, raw: true) { "2" }
assert_equal 3, @cache.increment(crazy_key)
assert_equal 2, @cache.decrement(crazy_key)
end
def test_really_long_keys
key = "x" * 2048
assert @cache.write(key, "bar")
assert_equal "bar", @cache.read(key)
assert_equal "bar", @cache.fetch(key)
assert_nil @cache.read("#{key}x")
assert_equal({ key => "bar" }, @cache.read_multi(key))
assert @cache.delete(key)
end
def test_cache_hit_instrumentation
key = "test_key"
@events = []
ActiveSupport::Notifications.subscribe "cache_read.active_support" do |*args|
@events << ActiveSupport::Notifications::Event.new(*args)
end
assert @cache.write(key, "1", raw: true)
assert @cache.fetch(key) {}
assert_equal 1, @events.length
assert_equal "cache_read.active_support", @events[0].name
assert_equal :fetch, @events[0].payload[:super_operation]
assert @events[0].payload[:hit]
ensure
ActiveSupport::Notifications.unsubscribe "cache_read.active_support"
end
def test_cache_miss_instrumentation
@events = []
ActiveSupport::Notifications.subscribe(/^cache_(.*)\.active_support$/) do |*args|
@events << ActiveSupport::Notifications::Event.new(*args)
end
assert_not @cache.fetch("bad_key") {}
assert_equal 3, @events.length
assert_equal "cache_read.active_support", @events[0].name
assert_equal "cache_generate.active_support", @events[1].name
assert_equal "cache_write.active_support", @events[2].name
assert_equal :fetch, @events[0].payload[:super_operation]
assert_not @events[0].payload[:hit]
ensure
ActiveSupport::Notifications.unsubscribe "cache_read.active_support"
end
private
def assert_compressed(value, **options)
assert_compression(true, value, **options)
end
def assert_uncompressed(value, **options)
assert_compression(false, value, **options)
end
def assert_compression(should_compress, value, **options)
freeze_time do
@cache.write("actual", value, **options)
@cache.write("uncompressed", value, **options, compress: false)
end
if value.nil?
assert_nil @cache.read("actual")
assert_nil @cache.read("uncompressed")
else
assert_equal value, @cache.read("actual")
assert_equal value, @cache.read("uncompressed")
end
actual_entry = @cache.send(:read_entry, @cache.send(:normalize_key, "actual", {}), {})
uncompressed_entry = @cache.send(:read_entry, @cache.send(:normalize_key, "uncompressed", {}), {})
actual_size = Marshal.dump(actual_entry).bytesize
uncompressed_size = Marshal.dump(uncompressed_entry).bytesize
if should_compress
assert_operator actual_size, :<, uncompressed_size, "value should be compressed"
else
assert_equal uncompressed_size, actual_size, "value should not be compressed"
end
end
end
| 28.387967 | 104 | 0.680626 |
87144afc8671b4ecd0a1c23b48a33bac2f1a3a9c | 5,628 | =begin
#NSX-T Data Center Policy API
#VMware NSX-T Data Center Policy REST API
OpenAPI spec version: 3.1.0.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.17
=end
require 'date'
module NSXTPolicy
# Represents the Site resource information for a Span entity including both the internal id as well as the site path.
class SpanSiteInfo
# Path of the Site resource
attr_accessor :site_path
# Site UUID representing the Site resource
attr_accessor :site_id
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'site_path' => :'site_path',
:'site_id' => :'site_id'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'site_path' => :'String',
:'site_id' => :'String'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.has_key?(:'site_path')
self.site_path = attributes[:'site_path']
end
if attributes.has_key?(:'site_id')
self.site_id = attributes[:'site_id']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
site_path == o.site_path &&
site_id == o.site_id
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[site_path, site_id].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = NSXTPolicy.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 28.568528 | 120 | 0.618159 |
bf895d43f3d2498b8a4495d900c86cd1ea249e8e | 357 | class CreateLegalTermAcceptances < ActiveRecord::Migration
def self.up
create_table :legal_term_acceptances do |t|
t.references :legal_term
t.integer :legal_term_version
t.string :resource_type
t.integer :resource_id
t.timestamps
end
end
def self.down
drop_table :legal_term_acceptances
end
end
| 21 | 58 | 0.70028 |
1dcc2583d4f88c519e2ecfc53458a905c39f8909 | 1,704 | # == Schema Information
#
# Table name: automation_rules
#
# id :bigint not null, primary key
# actions :jsonb not null
# active :boolean default(TRUE), not null
# conditions :jsonb not null
# description :text
# event_name :string not null
# name :string not null
# created_at :datetime not null
# updated_at :datetime not null
# account_id :bigint not null
#
# Indexes
#
# index_automation_rules_on_account_id (account_id)
#
class AutomationRule < ApplicationRecord
belongs_to :account
has_many_attached :files
validate :json_conditions_format
validate :json_actions_format
validates :account_id, presence: true
scope :active, -> { where(active: true) }
CONDITIONS_ATTRS = %w[content email country_code status message_type browser_language assignee_id team_id referer city company].freeze
ACTIONS_ATTRS = %w[send_message add_label send_email_to_team assign_team assign_best_agents send_attachments].freeze
private
def json_conditions_format
return if conditions.nil?
attributes = conditions.map { |obj, _| obj['attribute_key'] }
conditions = attributes - CONDITIONS_ATTRS
conditions -= account.custom_attribute_definitions.pluck(:attribute_key)
errors.add(:conditions, "Automation conditions #{conditions.join(',')} not supported.") if conditions.any?
end
def json_actions_format
return if actions.nil?
attributes = actions.map { |obj, _| obj['attribute_key'] }
actions = attributes - ACTIONS_ATTRS
errors.add(:actions, "Automation actions #{actions.join(',')} not supported.") if actions.any?
end
end
| 32.150943 | 136 | 0.699531 |
26d50ee5f4ef046c9bf401cec69c739faed30876 | 4,849 | require 'test_helper'
class PublicSuffix::ListTest < Test::Unit::TestCase
def setup
@list = PublicSuffix::List.new
end
def teardown
PublicSuffix::List.clear
end
def test_initialize
assert_instance_of PublicSuffix::List, @list
assert_equal 0, @list.length
end
def test_initialize_create_index_when_empty
assert_equal({}, @list.indexes)
end
def test_indexes
assert !list.indexes.empty?
assert_equal [1,2,3,4], list.indexes.delete('uk')
assert_equal [0], list.indexes.delete('com')
assert list.indexes.empty?
end
def test_equality_with_self
list = PublicSuffix::List.new
assert_equal list, list
end
def test_equality_with_internals
rule = PublicSuffix::Rule.factory("com")
assert_equal PublicSuffix::List.new.add(rule), PublicSuffix::List.new.add(rule)
end
def test_add
assert_equal @list, @list.add(PublicSuffix::Rule.factory(""))
assert_equal @list, @list << PublicSuffix::Rule.factory("")
assert_equal 2, @list.length
end
def test_add_should_recreate_index
@list = PublicSuffix::List.parse("com")
assert_equal PublicSuffix::Rule.factory("com"), @list.find("google.com")
assert_equal nil, @list.find("google.net")
@list << PublicSuffix::Rule.factory("net")
assert_equal PublicSuffix::Rule.factory("com"), @list.find("google.com")
assert_equal PublicSuffix::Rule.factory("net"), @list.find("google.net")
end
def test_empty?
assert @list.empty?
@list.add(PublicSuffix::Rule.factory(""))
assert !@list.empty?
end
def test_size
assert_equal 0, @list.length
assert_equal @list, @list.add(PublicSuffix::Rule.factory(""))
assert_equal 1, @list.length
end
def test_clear
assert_equal 0, @list.length
assert_equal @list, @list.add(PublicSuffix::Rule.factory(""))
assert_equal 1, @list.length
assert_equal @list, @list.clear
assert_equal 0, @list.length
end
def test_find
assert_equal PublicSuffix::Rule.factory("com"), list.find("google.com")
assert_equal PublicSuffix::Rule.factory("com"), list.find("foo.google.com")
assert_equal PublicSuffix::Rule.factory("*.uk"), list.find("google.uk")
assert_equal PublicSuffix::Rule.factory("*.uk"), list.find("google.co.uk")
assert_equal PublicSuffix::Rule.factory("*.uk"), list.find("foo.google.co.uk")
assert_equal PublicSuffix::Rule.factory("!british-library.uk"), list.find("british-library.uk")
assert_equal PublicSuffix::Rule.factory("!british-library.uk"), list.find("foo.british-library.uk")
end
def test_select
assert_equal 2, list.select("british-library.uk").size
end
def test_select_returns_empty_when_domain_has_scheme
assert_equal [], list.select("http://google.com")
assert_not_equal [], list.select("google.com")
end
def test_select_returns_empty_when_domain_is_nil
assert_equal [], list.select(nil)
end
def test_select_returns_empty_when_domain_is_blank
assert_equal [], list.select("")
assert_equal [], list.select(" ")
end
def test_self_default_getter
assert_equal nil, PublicSuffix::List.class_eval { @default }
PublicSuffix::List.default
assert_not_equal nil, PublicSuffix::List.class_eval { @default }
end
def test_self_default_setter
PublicSuffix::List.default
assert_not_equal nil, PublicSuffix::List.class_eval { @default }
PublicSuffix::List.default = nil
assert_equal nil, PublicSuffix::List.class_eval { @default }
end
def test_self_clear
PublicSuffix::List.default
assert_not_equal nil, PublicSuffix::List.class_eval { @default }
PublicSuffix::List.clear
assert_equal nil, PublicSuffix::List.class_eval { @default }
end
def test_self_reload
PublicSuffix::List.default
PublicSuffix::List.expects(:default_definition).returns("")
PublicSuffix::List.reload
assert_equal PublicSuffix::List.new, PublicSuffix::List.default
end
def test_self_parse
list = PublicSuffix::List.parse(<<EOS)
// ***** BEGIN LICENSE BLOCK *****
// Version: MPL 1.1/GPL 2.0/LGPL 2.1
//
// ***** END LICENSE BLOCK *****
// ac : http://en.wikipedia.org/wiki/.ac
ac
com.ac
// ad : http://en.wikipedia.org/wiki/.ad
ad
// ar : http://en.wikipedia.org/wiki/.ar
*.ar
!congresodelalengua3.ar
EOS
assert_instance_of PublicSuffix::List, list
assert_equal 5, list.length
assert_equal %w(ac com.ac ad *.ar !congresodelalengua3.ar).map { |name| PublicSuffix::Rule.factory(name) }, list.to_a
end
def test_self_parse_should_create_cache
assert_equal PublicSuffix::Rule.factory("com"), list.find("google.com")
end
private
def list
@_list ||= PublicSuffix::List.parse(<<EOS)
// com : http://en.wikipedia.org/wiki/.com
com
// uk : http://en.wikipedia.org/wiki/.uk
*.uk
*.sch.uk
!bl.uk
!british-library.uk
EOS
end
end
| 26.938889 | 121 | 0.707156 |
ff0d8502ec2868eec83ad67888b1a646d05060d0 | 10,985 | require 'rubygems'
require 'redis'
def init_external(r)
r.create_table("external", "(id int primary key, division int, health int, salary TEXT, name TEXT)")
r.create_index("external:division:index", "external", "division")
r.create_index("external:health:index ", "external", "health")
end
def init_healthplan(r)
r.create_table("healthplan", "(id int primary key, name TEXT)")
end
def init_division(r)
r.create_table("division", "(id int primary key, name TEXT, location TEXT)")
r.create_index("division:name:index", "division", "name")
end
def init_subdivision(r)
r.create_table("subdivision", "(id int primary key, division int, name TEXT)")
r.create_index("subdivision:division:index", "subdivision", "division")
end
def init_employee(r)
r.create_table("employee", "(id int primary key, division int, salary TEXT, name TEXT)")
r.create_index("employee:name:index", "employee", "name")
r.create_index("employee:division:index", "employee", "division")
end
def init_customer(r)
r.create_table("customer", "(id int primary key, employee int, name TEXT, hobby TEXT)")
r.create_index("customer:employee:index", "customer", "employee")
r.create_index("customer:hobby:index ", "customer", "hobby")
end
def init_worker(r)
r.create_table("worker", "(id int primary key, division int, health int, salary TEXT, name TEXT)")
r.create_index("worker:division:index", "worker", "division")
r.create_index("worker:health:index ", "worker", "health")
end
def insert_external(r)
r.insert("external", "1,66,1,15000.99,marieanne")
r.insert("external", "2,33,3,75000.77,rosemarie")
r.insert("external", "3,11,2,55000.55,johnathan")
r.insert("external", "4,22,1,25000.99,bartholemew")
end
def insert_healthplan(r)
r.insert("healthplan", "1,none")
r.insert("healthplan", "2,kaiser")
r.insert("healthplan", "3,general")
r.insert("healthplan", "4,extended")
r.insert("healthplan", "5,foreign")
end
def insert_subdivision(r)
r.insert("subdivision", "1,11,middle-management")
r.insert("subdivision", "2,11,top-level")
r.insert("subdivision", "3,44,trial")
r.insert("subdivision", "4,44,research")
r.insert("subdivision", "5,22,factory")
r.insert("subdivision", "6,22,field")
end
def insert_division(r)
r.insert("division", "11,bosses,N.Y.C")
r.insert("division", "22,workers,Chicago")
r.insert("division", "33,execs,Dubai")
r.insert("division", "55,bankers,Zurich")
r.insert("division", "66,janitors,Detroit")
r.insert("division", "44,lawyers,L.A.")
end
def insert_employee(r)
r.insert("employee", "1,11,10000.99,jim")
r.insert("employee", "2,22,2000.99,jack")
r.insert("employee", "3,33,30000.99,bob")
r.insert("employee", "4,22,3000.99,bill")
r.insert("employee", "5,22,5000.99,tim")
r.insert("employee", "6,66,60000.99,jan")
r.insert("employee", "7,77,7000.99,beth")
r.insert("employee", "8,88,80000.99,kim")
r.insert("employee", "9,99,9000.99,pam")
r.insert("employee", "11,111,111000.99,sammy")
end
def insert_customer(r)
r.insert("customer", "1,2,johnathan,sailing")
r.insert("customer", "2,3,bartholemew,fencing")
r.insert("customer", "3,3,jeremiah,yachting")
r.insert("customer", "4,4,christopher,curling")
r.insert("customer", "6,4,jennifer,stamps")
r.insert("customer", "7,4,marieanne,painting")
r.insert("customer", "8,5,rosemarie,violin")
r.insert("customer", "9,5,bethany,choir")
r.insert("customer", "10,6,gregory,dance")
end
def insert_worker(r)
r.insert_and_return_size("worker", "1,11,2,60000.66,jim")
r.insert_and_return_size("worker", "2,22,1,30000.33,jack")
r.insert_and_return_size("worker", "3,33,4,90000.99,bob")
r.insert_and_return_size("worker", "4,44,3,70000.77,bill")
r.insert_and_return_size("worker", "6,66,1,10000.99,jan")
r.insert_and_return_size("worker", "7,66,1,11000.99,beth")
r.insert_and_return_size("worker", "8,11,2,68888.99,mac")
r.insert_and_return_size("worker", "9,22,1,31111.99,ken")
r.insert_and_return_size("worker", "10,33,4,111111.99,seth")
end
def initer(r)
begin
init_worker(r)
init_customer(r)
init_employee(r)
init_division(r)
init_subdivision(r)
init_healthplan(r)
init_external(r)
rescue StandardError => bang
puts "EXCEPTION IN INITER: " + bang
end
end
def inserter(r)
begin
insert_worker(r)
insert_customer(r)
insert_employee(r)
insert_division(r)
insert_subdivision(r)
insert_healthplan(r)
insert_external(r)
rescue StandardError => bang
puts "EXCEPTION IN INSERTER: " + bang
end
end
def selecter(r)
p r.select("*", "division", "id = 22")
p r.select("name, location", "division", "id = 22")
p r.select("*", "employee", "id = 2")
p r.select("name,salary", "employee", "id = 2")
p r.select("*", "customer", "id = 2")
p r.select("name", "customer", "id = 2")
p r.select("*", "worker", "id = 7")
p r.select("name, salary, division", "worker", "id = 7")
p r.select("*", "subdivision", "id = 2")
p r.select("name,division", "subdivision", "id = 2")
p r.select("*", "healthplan", "id = 2")
p r.select("name", "healthplan", "id = 2")
p r.select("*", "external", "id = 3")
p r.select("name,salary,division", "external", "id = 3")
end
def updater(r)
p r.select("*", "employee", "id = 1")
p r.update("employee", "salary=50000,name=NEWNAME,division=66", "id = 1")
p r.select("*", "employee", "id = 1")
p r.update("employee", "id=100", "id = 1")
p r.select("*", "employee", "id = 100")
end
def delete_employee(r)
p r.select("name,salary", "employee", "id = 3")
p r.delete("employee", "id = 3")
p r.select("name,salary", "employee", "id = 3")
end
def delete_customer(r)
p r.select("name, hobby", "customer", "id = 7")
p r.delete("customer", "id = 7")
p r.select("name, hobby", "customer", "id = 7")
end
def delete_division(r)
p r.select("name, location", "division", "id = 33")
p r.delete("division", "id = 33")
p r.select("name, location", "division", "id = 33")
end
def deleter(r)
delete_employee(r)
delete_customer(r)
delete_division(r)
end
def iselecter_division(r)
p r.select("id,name,location", "division", "name BETWEEN a AND z")
end
def iselecter_employee(r)
p r.select("id,name,salary,division", "employee", "division BETWEEN 11 AND 55")
end
def iselecter_customer(r)
p r.select("hobby,id,name,employee", "customer", "hobby BETWEEN a AND z")
end
def iselecter_customer_employee(r)
p r.select("employee,name,id", "customer", "employee BETWEEN 3 AND 6")
end
def iselecter_worker(r)
p r.select("id,health,name,salary,division", "worker", "health BETWEEN 1 AND 3")
end
def iselecter(r)
iselecter_division(r)
iselecter_employee(r)
iselecter_customer(r)
end
def iupdater_customer(r)
p r.update("customer", "hobby=fishing,employee=6", "hobby BETWEEN v AND z")
end
def iupdater_customer_rev(r)
p r.update("customer", "hobby=ziplining,employee=7", "hobby BETWEEN f AND g")
end
def ideleter_customer(r)
p r.delete("customer", "employee BETWEEN 4 AND 5")
end
def join_div_extrnl(r)
p r.select("division.name,division.location,external.name,external.salary", "division,external", "division.id=external.division AND division.id BETWEEN 11 AND 80")
end
def join_div_wrkr(r)
p r.select("division.name,division.location,worker.name,worker.salary", "division,worker", "division.id = worker.division AND division.id BETWEEN 11 AND 33")
end
def join_wrkr_health(r)
p r.select("worker.name,worker.salary,healthplan.name", "worker,healthplan", "worker.health = healthplan.id AND healthplan.id BETWEEN 1 AND 5")
p r.select("healthplan.name,worker.name,worker.salary", "healthplan,worker", "healthplan.id=worker.health AND healthplan.id BETWEEN 1 AND 5")
end
def join_div_wrkr_sub(r)
p r.select("division.name,division.location,worker.name,worker.salary,subdivision.name", "division,worker,subdivision", "division.id = worker.division AND division.id = subdivision.division AND division.id BETWEEN 11 AND 33")
end
def join_div_sub_wrkr(r)
p r.select("division.name,division.location,subdivision.name,worker.name,worker.salary", "division,subdivision,worker", "division.id = subdivision.division AND division.id = worker.division AND division.id BETWEEN 11 AND 33")
end
def joiner(r)
join_div_extrnl(r)
join_div_wrkr(r)
join_wrkr_health(r)
join_div_wrkr_sub(r)
join_div_sub_wrkr(r)
end
def works(r)
initer(r)
inserter(r)
selecter(r)
iselecter(r)
updater(r)
iselecter_employee(r)
deleter(r)
iselecter(r)
iupdater_customer(r)
iselecter_customer(r)
ideleter_customer(r)
iselecter_customer_employee(r)
joiner(r)
end
def single_join_div_extrnl(r)
init_division(r)
insert_division(r)
init_external(r)
insert_external(r)
join_div_extrnl(r)
end
def single_join_wrkr_health_rev(r)
init_worker(r)
insert_worker(r)
init_healthplan(r)
insert_healthplan(r)
p r.select("healthplan.name,worker.name,worker.salary", "healthplan,worker", "healthplan.id=worker.health AND healthplan.id BETWEEN 1 AND 5")
end
def single_join_wrkr_health(r)
init_worker(r)
insert_worker(r)
init_healthplan(r)
insert_healthplan(r)
p r.select("worker.name,worker.salary,healthplan.name", "worker,healthplan", "worker.health=healthplan.id AND healthplan.id BETWEEN 1 AND 5")
end
def single_join_sub_wrkr(r)
init_division(r)
insert_division(r)
init_worker(r)
insert_worker(r)
init_subdivision(r)
insert_subdivision(r)
join_div_sub_wrkr(r)
end
def scan_external(r)
p r.scanselect("name,salary", "external", "salary BETWEEN 15000.99 AND 25001.01")
end
def scan_healthpan(r)
p r.scanselect("*", "healthplan", "name BETWEEN a AND k")
end
def istore_worker_name_list(r)
p r.select_store("name", "worker", "division BETWEEN 11 AND 33", "RPUSH l_worker_name")
p r.lrange("l_worker_name", 0 -1)
end
def istore_worker_hash_name_salary(r)
p r.select_store("name,salary", "worker", "division BETWEEN 11 AND 33", "HSET h_worker_name_to_salary")
p r.hgetall("h_worker_name_to_salary")
end
def jstore_div_subdiv(r)
begin
r.drop_table("normal_div_subdiv")
rescue StandardError => bang
end
p r.select_store("subdivision.id,subdivision.name,division.name", "subdivision,division", "subdivision.division = division.id AND division.id BETWEEN 11 AND 44", "INSERT normal_div_subdiv")
p r.dump("normal_div_subdiv")
end
def jstore_worker_location_hash(r)
p r.select_store("external.name,division.location", "external,division", "external.division=division.id AND division.id BETWEEN 11 AND 80", "HSET worker_city_hash")
p r.hgetall("worker_city_hash")
puts
end
def jstore_worker_location_table(r)
begin
r.drop_table("w_c_tbl")
rescue StandardError => bang
end
p r.select_store("external.name,division.location", "external,division", "external.division=division.id AND division.id BETWEEN 11 AND 80", "INSERT w_c_tbl")
p r.dump("w_c_tbl")
puts
end
def lua_test(r)
p r.lua('return client("SET", "lua_R", 5*5);');
p r.lua('return client("GET", "lua_R");');
end
| 33.187311 | 227 | 0.7066 |
1cd6c5c86c885de7aeba920742d4483bc6acea68 | 376 | require 'rails_helper'
describe Business do
it { should validate_presence_of :biz_name }
it { should validate_presence_of :biz_type }
it { should validate_presence_of :biz_address }
it { should validate_presence_of :biz_phone }
it { should validate_presence_of :biz_contact }
it { should validate_presence_of :biz_number }
it { should have_many :requests }
end
| 31.333333 | 49 | 0.771277 |
f7a04cd1baa566c3ddb74b743cfacff50cb846c4 | 2,646 | # Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
require 'spec_helper'
describe 'client#update' do
let(:expected_args) do
[
'POST',
url,
params,
body,
{}
]
end
let(:body) do
{ doc: { } }
end
let(:url) do
'foo/bar/1/_update'
end
let(:client) do
Class.new { include Elasticsearch::API }.new
end
let(:params) do
{}
end
it 'requires the :index argument' do
expect {
client.update(type: 'bar', id: '1')
}.to raise_exception(ArgumentError)
end
it 'requires the :id argument' do
expect {
client.update(index: 'foo', type: 'bar')
}.to raise_exception(ArgumentError)
end
it 'performs the request' do
expect(client_double.update(index: 'foo', type: 'bar', id: '1', body: { doc: {} })).to eq({})
end
context 'when URL parameters are provided' do
let(:url) do
'foo/bar/1/_update'
end
let(:body) do
{}
end
it 'performs the request' do
expect(client_double.update(index: 'foo', type: 'bar', id: '1', body: {}))
end
end
context 'when the request needs to be URL-escaped' do
let(:url) do
'foo%5Ebar/bar%2Fbam/1/_update'
end
let(:body) do
{}
end
it 'escapes the parts' do
expect(client_double.update(index: 'foo^bar', type: 'bar/bam', id: '1', body: {}))
end
end
context 'when a NotFound exception is raised' do
before do
allow(client).to receive(:perform_request).and_raise(NotFound)
end
it 'raises it to the user' do
expect {
client.update(index: 'foo', type: 'bar', id: 'XXX', body: {})
}.to raise_exception(NotFound)
end
context 'when the :ignore parameter is specified' do
it 'does not raise the error to the user' do
expect(client.update(index: 'foo', type: 'bar', id: 'XXX', body: {}, ignore: 404)).to eq(false)
end
end
end
end
| 24.275229 | 103 | 0.640967 |
bf5e371bb6667536964c3790c9cd41fb7986ae08 | 118 | module Itamae
module Plugin
module Recipe
module Jq
VERSION = "0.1.0"
end
end
end
end
| 11.8 | 25 | 0.559322 |
7a4dc1e9be1ce33225c783baf9f8babe4de9940c | 258 | module MarkdownUI
class FieldTag < MarkdownUI::Shared::TagKlass
def initialize(_content, _klass = nil, __id = nil, _data = nil)
@content = _content
end
def render
"<field#{_id}#{klass}#{data}>#{@content}</field>"
end
end
end
| 21.5 | 67 | 0.631783 |
79cc5addd29dac40c0bed3001653f1bf43a395c1 | 2,786 | class Proftpd < Formula
desc "Highly configurable GPL-licensed FTP server software"
homepage "http://www.proftpd.org/"
url "https://github.com/proftpd/proftpd/archive/v1.3.7a.tar.gz"
mirror "https://fossies.org/linux/misc/proftpd-1.3.7a.tar.gz"
mirror "https://ftp.osuosl.org/pub/blfs/conglomeration/proftpd/proftpd-1.3.7a.tar.gz"
sha256 "8b7bbf9757988935352d9dec5ebf96b6a1e6b63a6cdac2e93202ac6c42c4cd96"
license "GPL-2.0"
# Proftpd uses an incrementing letter after the numeric version for
# maintenance releases. Versions like `1.2.3a` and `1.2.3b` are not alpha and
# beta respectively. Prerelease versions use a format like `1.2.3rc1`.
livecheck do
url "https://github.com/proftpd/proftpd/releases/latest"
regex(%r{href=.*?/tag/v?(\d+(?:\.\d+)+[a-z]?)["' >]}i)
end
bottle do
sha256 "a8ec8266a93ac34dde37fd36889e0d956e39fc6aca8efd57a0adef0f40db813e" => :big_sur
sha256 "b30ef0c9ea4f2642cb98e863c51ef8b337605ca5d9a3df8d2d9995ac00c6e9be" => :catalina
sha256 "2f529091ef2c1e07ca1db9ec0a974f639530cca275e2f3ebbd910b42a3cb5f12" => :mojave
sha256 "af399e07592ed468d356963c8a2b27318476dd422499ba0148d1579e4d80cd69" => :high_sierra
sha256 "e0af19955b0a97b339c1c3dfe460fe27212fbb3dbbb751687a43d66df54c3f9f" => :x86_64_linux
end
def install
# fixes unknown group 'nogroup'
# http://www.proftpd.org/docs/faq/linked/faq-ch4.html#AEN434
inreplace "sample-configurations/basic.conf", "nogroup", "nobody"
system "./configure", "--prefix=#{prefix}",
"--sysconfdir=#{etc}",
"--localstatedir=#{var}"
ENV.deparallelize
install_user = ENV["USER"]
install_group = `groups`.split[0]
system "make", "INSTALL_USER=#{install_user}", "INSTALL_GROUP=#{install_group}", "install"
end
plist_options manual: "proftpd"
def plist
<<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>#{plist_name}</string>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<false/>
<key>ProgramArguments</key>
<array>
<string>#{opt_sbin}/proftpd</string>
</array>
<key>UserName</key>
<string>root</string>
<key>WorkingDirectory</key>
<string>#{HOMEBREW_PREFIX}</string>
<key>StandardErrorPath</key>
<string>/dev/null</string>
<key>StandardOutPath</key>
<string>/dev/null</string>
</dict>
</plist>
EOS
end
test do
assert_match version.to_s, shell_output("#{opt_sbin}/proftpd -v")
end
end
| 37.146667 | 108 | 0.654343 |
01926a8fc49aeaec3a694a33c370dd46eb10a58a | 268 | class CreateHtmlDocuments < ActiveRecord::Migration
def self.up
create_table :html_documents do |t|
t.references :document
t.string :name
t.string :path
t.timestamps
end
end
def self.down
drop_table :html_documents
end
end
| 17.866667 | 51 | 0.679104 |
ff26aa5671b9d5ef551c0a1ea4673e9df4c864b8 | 1,374 | module VacancyExpiresAtFieldValidations
extend ActiveSupport::Concern
included do
validate :expires_at_must_not_be_blank, unless: proc { |v| validate_expires_at?(v) }
validate :expires_at_must_be_in_correct_range, unless: proc { |v| validate_expires_at?(v) }
validate :expires_at_meridiem_must_not_be_blank, unless: proc { |v| validate_expires_at?(v) }
end
private
def expires_at_must_not_be_blank
errors.add(:expires_at, I18n.t("activerecord.errors.models.vacancy.attributes.expires_at.blank")) if
expires_at_hh.blank? || expires_at_mm.blank?
end
def expires_at_must_be_in_correct_range
errors.add(:expires_at, I18n.t("activerecord.errors.models.vacancy.attributes.expires_at.wrong_format")) unless
in_range?(expires_at_hh, 1, 12) && in_range?(expires_at_mm, 0, 59)
end
def expires_at_meridiem_must_not_be_blank
errors.add(:expires_at, I18n.t("activerecord.errors.models.vacancy.attributes.expires_at.must_be_am_pm")) if
expires_at_meridiem.blank?
end
def in_range?(value, min, max)
number?(value) && value.to_i >= min && value.to_i <= max
end
def number?(value)
/\A[+-]?\d+\z/.match?(value.to_s)
end
def validate_expires_at?(vacancy)
vacancy.expires_at.present? &&
vacancy.expires_at_hh.blank? && vacancy.expires_at_mm.blank? && vacancy.expires_at_meridiem.blank?
end
end
| 34.35 | 115 | 0.746725 |
28156eafa5c2b6494cb4f449ceae0eea399d37c3 | 1,125 | require_relative 'lib/bradley_view_tool/version'
Gem::Specification.new do |spec|
spec.name = "bradley_view_tool"
spec.version = BradleyViewTool::VERSION
spec.authors = ["PatBradley88"]
spec.email = ["patrick_bradley1@yahoo.co.uk"]
spec.summary = %q{Various view specific methods for applications I use.}
spec.description = %q{Provides generated HTML data for Rails applications.}
spec.homepage = "https://pbradleyportfolio.com"
spec.license = "MIT"
spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
end
| 41.666667 | 87 | 0.662222 |
33e781412fa5832214485ceabed9e2f15dbc939c | 96 | begin
require 'spec'
rescue LoadError
require 'rubygems'
gem 'rspec'
require 'spec'
end
| 12 | 20 | 0.708333 |
edcedc172ae288ba2baf6efacd831c9f88bcc0c0 | 14,634 | class PeopleController < Devise::RegistrationsController
class PersonDeleted < StandardError; end
class PersonBanned < StandardError; end
skip_before_filter :verify_authenticity_token, :only => [:creates]
skip_before_filter :require_no_authentication, :only => [:new]
before_filter EnsureCanAccessPerson.new(
:id, error_message_key: "layouts.notifications.you_are_not_authorized_to_view_this_content"), only: [:update, :destroy]
LOOSER_ACCESS_CONTROL = [
:check_email_availability,
:check_email_availability_and_validity,
:check_invitation_code
]
skip_filter :cannot_access_if_banned, only: LOOSER_ACCESS_CONTROL
skip_filter :cannot_access_without_confirmation, only: LOOSER_ACCESS_CONTROL
skip_filter :ensure_consent_given, only: LOOSER_ACCESS_CONTROL
skip_filter :ensure_user_belongs_to_community, only: LOOSER_ACCESS_CONTROL
helper_method :show_closed?
def show
@person = Person.find_by!(username: params[:username], community_id: @current_community.id)
raise PersonDeleted if @person.deleted?
raise PersonBanned if @person.banned?
redirect_to landing_page_path and return if @current_community.private? && !@current_user
@selected_tribe_navi_tab = "members"
@community_membership = CommunityMembership.find_by_person_id_and_community_id_and_status(@person.id, @current_community.id, "accepted")
include_closed = @current_user == @person && params[:show_closed]
search = {
author_id: @person.id,
include_closed: include_closed,
page: 1,
per_page: 6
}
includes = [:author, :listing_images]
raise_errors = Rails.env.development?
listings =
ListingIndexService::API::Api
.listings
.search(
community_id: @current_community.id,
search: search,
engine: FeatureFlagHelper.search_engine,
raise_errors: raise_errors,
includes: includes
).and_then { |res|
Result::Success.new(
ListingIndexViewUtils.to_struct(
result: res,
includes: includes,
page: search[:page],
per_page: search[:per_page]
))
}.data
received_testimonials = TestimonialViewUtils.received_testimonials_in_community(@person, @current_community)
received_positive_testimonials = TestimonialViewUtils.received_positive_testimonials_in_community(@person, @current_community)
feedback_positive_percentage = @person.feedback_positive_percentage_in_community(@current_community)
render locals: { listings: listings,
followed_people: @person.followed_people,
received_testimonials: received_testimonials,
received_positive_testimonials: received_positive_testimonials,
feedback_positive_percentage: feedback_positive_percentage
}
end
def new
@selected_tribe_navi_tab = "members"
redirect_to search_path if logged_in?
session[:invitation_code] = params[:code] if params[:code]
@person = if params[:person] then
Person.new(params[:person].slice(:given_name, :family_name, :email, :username))
else
Person.new()
end
@container_class = params[:private_community] ? "container_12" : "container_24"
@grid_class = params[:private_community] ? "grid_6 prefix_3 suffix_3" : "grid_10 prefix_7 suffix_7"
end
def create
domain = @current_community ? @current_community.full_url : "#{request.protocol}#{request.host_with_port}"
error_redirect_path = domain + sign_up_path
if params[:person].blank? || params[:person][:input_again].present? # Honey pot for spammerbots
flash[:error] = t("layouts.notifications.registration_considered_spam")
ApplicationHelper.send_error_notification("Registration Honey Pot is hit.", "Honey pot")
redirect_to error_redirect_path and return
end
if @current_community && @current_community.join_with_invite_only? || params[:invitation_code]
unless Invitation.code_usable?(params[:invitation_code], @current_community)
# abort user creation if invitation is not usable.
# (This actually should not happen since the code is checked with javascript)
session[:invitation_code] = nil # reset code from session if there was issues so that's not used again
ApplicationHelper.send_error_notification("Invitation code check did not prevent submiting form, but was detected in the controller", "Invitation code error")
# TODO: if this ever happens, should change the message to something else than "unknown error"
flash[:error] = t("layouts.notifications.unknown_error")
redirect_to error_redirect_path and return
else
invitation = Invitation.find_by_code(params[:invitation_code].upcase)
end
end
# Check that email is not taken
unless Email.email_available?(params[:person][:email], @current_community.id)
flash[:error] = t("people.new.email_is_in_use")
redirect_to error_redirect_path and return
end
# Check that the email is allowed for current community
if @current_community && ! @current_community.email_allowed?(params[:person][:email])
flash[:error] = t("people.new.email_not_allowed")
redirect_to error_redirect_path and return
end
@person, email = new_person(params, @current_community)
# Make person a member of the current community
if @current_community
membership = CommunityMembership.new(:person => @person, :community => @current_community, :consent => @current_community.consent)
membership.status = "pending_email_confirmation"
membership.invitation = invitation if invitation.present?
# If the community doesn't have any members, make the first one an admin
if @current_community.members.count == 0
membership.admin = true
end
membership.save!
session[:invitation_code] = nil
end
# If invite was used, reduce usages left
invitation.use_once! if invitation.present?
Delayed::Job.enqueue(CommunityJoinedJob.new(@person.id, @current_community.id)) if @current_community
Analytics.record_event(flash, "SignUp", method: :email)
# send email confirmation
# (unless disabled for testing environment)
if APP_CONFIG.skip_email_confirmation
email.confirm!
redirect_to search_path
else
Email.send_confirmation(email, @current_community)
flash[:notice] = t("layouts.notifications.account_creation_succesful_you_still_need_to_confirm_your_email")
redirect_to confirmation_pending_path
end
end
def build_devise_resource_from_person(person_params)
person_params.delete(:terms) #remove terms part which confuses Devise
# This part is copied from Devise's regstration_controller#create
build_resource(person_params)
resource
end
def create_facebook_based
username = UserService::API::Users.username_from_fb_data(
username: session["devise.facebook_data"]["username"],
given_name: session["devise.facebook_data"]["given_name"],
family_name: session["devise.facebook_data"]["family_name"],
community_id: @current_community.id)
person_hash = {
:username => username,
:given_name => session["devise.facebook_data"]["given_name"],
:family_name => session["devise.facebook_data"]["family_name"],
:facebook_id => session["devise.facebook_data"]["id"],
:locale => I18n.locale,
:test_group_number => 1 + rand(4),
:password => Devise.friendly_token[0,20],
community_id: @current_community.id
}
@person = Person.create!(person_hash)
# We trust that Facebook has already confirmed these and save the user few clicks
Email.create!(:address => session["devise.facebook_data"]["email"], :send_notifications => true, :person => @person, :confirmed_at => Time.now, community_id: @current_community.id)
@person.set_default_preferences
@person.store_picture_from_facebook
sign_in(resource_name, @person)
flash[:notice] = t("layouts.notifications.login_successful", :person_name => view_context.link_to(PersonViewUtils.person_display_name_for_type(@person, "first_name_only"), person_path(@person))).html_safe
CommunityMembership.create(person: @person, community: @current_community, status: "pending_consent")
session[:fb_join] = "pending_analytics"
Analytics.record_event(flash, "SignUp", method: :facebook)
redirect_to pending_consent_path
end
def update
target_user = Person.find_by!(username: params[:id], community_id: @current_community.id)
# If setting new location, delete old one first
if params[:person] && params[:person][:location] && (params[:person][:location][:address].empty? || params[:person][:street_address].blank?)
params[:person].delete("location")
if target_user.location
target_user.location.delete
end
end
#Check that people don't exploit changing email to be confirmed to join an email restricted community
if params["request_new_email_confirmation"] && @current_community && ! @current_community.email_allowed?(params[:person][:email])
flash[:error] = t("people.new.email_not_allowed")
redirect_to :back and return
end
target_user.set_emails_that_receive_notifications(params[:person][:send_notifications])
begin
person_params = params.require(:person).permit(
:given_name,
:family_name,
:display_name,
:street_address,
:phone_number,
:image,
:description,
{ location: [:address, :google_address, :latitude, :longitude] },
:password,
:password2,
{ send_notifications: [] },
{ email_attributes: [:address] },
:min_days_between_community_updates,
{ preferences: [
:email_from_admins,
:email_about_new_messages,
:email_about_new_comments_to_own_listing,
:email_when_conversation_accepted,
:email_when_conversation_rejected,
:email_about_new_received_testimonials,
:email_about_confirm_reminders,
:email_about_testimonial_reminders,
:email_about_completed_transactions,
:email_about_new_payments,
:email_about_new_listings_by_followed_people,
] }
)
Maybe(person_params)[:location].each { |loc|
person_params[:location] = loc.merge(location_type: :person)
}
m_email_address = Maybe(person_params)[:email_attributes][:address]
m_email_address.each { |new_email_address|
# This only builds the emails, they will be saved when `update_attributes` is called
target_user.emails.build(address: new_email_address, community_id: @current_community.id)
}
if target_user.update_attributes(person_params.except(:email_attributes))
if params[:person][:password]
#if password changed Devise needs a new sign in.
sign_in target_user, :bypass => true
end
m_email_address.each {
# A new email was added, send confirmation email to the latest address
Email.send_confirmation(target_user.emails.last, @current_community)
}
flash[:notice] = t("layouts.notifications.person_updated_successfully")
# Send new confirmation email, if was changing for that
if params["request_new_email_confirmation"]
target_user.send_confirmation_instructions(request.host_with_port, @current_community)
flash[:notice] = t("layouts.notifications.email_confirmation_sent_to_new_address")
end
else
flash[:error] = t("layouts.notifications.#{target_user.errors.first}")
end
rescue RestClient::RequestFailed => e
flash[:error] = t("layouts.notifications.update_error")
end
redirect_to :back
end
def destroy
target_user = Person.find_by!(username: params[:id], community_id: @current_community.id)
has_unfinished = TransactionService::Transaction.has_unfinished_transactions(target_user.id)
return redirect_to search_path if has_unfinished
# Do all delete operations in transaction. Rollback if any of them fails
ActiveRecord::Base.transaction do
UserService::API::Users.delete_user(target_user.id)
MarketplaceService::Listing::Command.delete_listings(target_user.id)
PaypalService::API::Api.accounts.delete(community_id: target_user.community_id, person_id: target_user.id)
end
sign_out target_user
report_analytics_event('user', "deleted", "by user")
flash[:notice] = t("layouts.notifications.account_deleted")
redirect_to search_path
end
def check_username_availability
respond_to do |format|
format.json { render :json => Person.username_available?(params[:person][:username], @current_community.id) }
end
end
def check_email_availability_and_validity
email = params[:person][:email]
allowed_and_available = @current_community.email_allowed?(email) && Email.email_available?(email, @current_community.id)
respond_to do |format|
format.json { render json: allowed_and_available }
end
end
# this checks that email is not already in use for anyone (including current user)
def check_email_availability
email = params[:person] && params[:person][:email_attributes] && params[:person][:email_attributes][:address]
respond_to do |format|
format.json { render json: Email.email_available?(email, @current_community.id) }
end
end
def check_invitation_code
respond_to do |format|
format.json { render :json => Invitation.code_usable?(params[:invitation_code], @current_community) }
end
end
def show_closed?
params[:closed] && params[:closed].eql?("true")
end
private
# Create a new person by params and current community
def new_person(params, current_community)
person = Person.new
params[:person][:locale] = params[:locale] || APP_CONFIG.default_locale
params[:person][:test_group_number] = 1 + rand(4)
params[:person][:community_id] = current_community.id
email = Email.new(:person => person, :address => params[:person][:email].downcase, :send_notifications => true, community_id: current_community.id)
params["person"].delete(:email)
person = build_devise_resource_from_person(params[:person])
person.emails << email
person.inherit_settings_from(current_community)
if person.save!
sign_in(resource_name, resource)
end
person.set_default_preferences
[person, email]
end
end
| 38.714286 | 208 | 0.715184 |
f7ea0f71e6d14614be22de5cf15e63aa48279a18 | 4,437 | module IMS::LTI
# Mixin module for managing LTI Launch Data
#
# Launch data documentation:
# http://www.imsglobal.org/lti/v1p1pd/ltiIMGv1p1pd.html#_Toc309649684
module LaunchParams
# List of the standard launch parameters for an LTI launch
LAUNCH_DATA_PARAMETERS = %w{
accept_media_types
accept_multiple
accept_presentation_document_targets
accept_unsigned
auto_create
content_item_return_url
context_id
context_label
context_title
context_type
launch_presentation_css_url
launch_presentation_document_target
launch_presentation_height
launch_presentation_locale
launch_presentation_return_url
launch_presentation_width
lis_course_offering_sourcedid
lis_course_section_sourcedid
lis_outcome_service_url
lis_person_contact_email_primary
lis_person_name_family
lis_person_name_full
lis_person_name_given
lis_person_sourcedid
lis_result_sourcedid
lti_message_type
lti_version
oauth_callback
oauth_consumer_key
oauth_nonce
oauth_signature
oauth_signature_method
oauth_timestamp
oauth_version
resource_link_description
resource_link_id
resource_link_title
roles
role_scope_mentor
tool_consumer_info_product_family_code
tool_consumer_info_version
tool_consumer_instance_contact_email
tool_consumer_instance_description
tool_consumer_instance_guid
tool_consumer_instance_name
tool_consumer_instance_url
user_id
user_image
}
LAUNCH_DATA_PARAMETERS.each { |p| attr_accessor p }
# Hash of custom parameters, the keys will be prepended with "custom_" at launch
attr_accessor :custom_params
# Hash of extension parameters, the keys will be prepended with "ext_" at launch
attr_accessor :ext_params
# Hash of parameters to add to the launch. These keys will not be prepended
# with any value at launch
attr_accessor :non_spec_params
# Set the roles for the current launch
#
# Full list of roles can be found here:
# http://www.imsglobal.org/LTI/v1p1pd/ltiIMGv1p1pd.html#_Toc309649700
#
# LIS roles include:
# * Student
# * Faculty
# * Member
# * Learner
# * Instructor
# * Mentor
# * Staff
# * Alumni
# * ProspectiveStudent
# * Guest
# * Other
# * Administrator
# * Observer
# * None
#
# @param roles_list [String,Array] An Array or comma-separated String of roles
def roles=(roles_list)
if roles_list
if roles_list.is_a?(Array)
@roles = roles_list
else
@roles = roles_list.split(",").map(&:downcase)
end
else
@roles = nil
end
end
def set_custom_param(key, val)
@custom_params[key] = val
end
def get_custom_param(key)
@custom_params[key]
end
def set_non_spec_param(key, val)
@non_spec_params[key] = val
end
def get_non_spec_param(key)
@non_spec_params[key]
end
def set_ext_param(key, val)
@ext_params[key] = val
end
def get_ext_param(key)
@ext_params[key]
end
# Create a new Hash with all launch data. Custom/Extension keys will have the
# appropriate value prepended to the keys and the roles are set as a comma
# separated String
def to_params
params = launch_data_hash.merge(add_key_prefix(@custom_params, 'custom')).merge(add_key_prefix(@ext_params, 'ext')).merge(@non_spec_params)
params["roles"] = @roles.join(",") if @roles
params
end
# Populates the launch data from a Hash
#
# Only keys in LAUNCH_DATA_PARAMETERS and that start with 'custom_' or 'ext_'
# will be pulled from the provided Hash
def process_params(params)
params.each_pair do |key, val|
if LAUNCH_DATA_PARAMETERS.member?(key)
self.send("#{key}=", val)
elsif key =~ /\Acustom_(.+)\Z/
@custom_params[$1] = val
elsif key =~ /\Aext_(.+)\Z/
@ext_params[$1] = val
end
end
end
private
def launch_data_hash
LAUNCH_DATA_PARAMETERS.inject({}) { |h, k| h[k] = self.send(k) if self.send(k); h }
end
def add_key_prefix(hash, prefix)
hash.keys.inject({}) { |h, k| h["#{prefix}_#{k}"] = hash[k]; h }
end
end
end
| 26.568862 | 145 | 0.664638 |
2156934f1802623ccbf4e4a41101d9293b652c65 | 5,027 | require_relative '../spec_helper'
describe 'deploy instance_groups job', type: :integration do
with_reset_sandbox_before_each
it 're-evaluates job with new manifest job properties' do
manifest_hash = Bosh::Spec::NewDeployments.simple_manifest_with_instance_groups
manifest_hash['instance_groups'].first['jobs'].first['properties'] = { 'test_property' => 1 }
deploy_from_scratch(manifest_hash: manifest_hash, cloud_config_hash: Bosh::Spec::NewDeployments.simple_cloud_config)
foobar_instance = director.instance('foobar', '0')
template = foobar_instance.read_job_template('foobar', 'bin/foobar_ctl')
expect(template).to include('test_property=1')
manifest_hash['instance_groups'].first['jobs'].first['properties'] = { 'test_property' => 2 }
deploy_simple_manifest(manifest_hash: manifest_hash)
template = foobar_instance.read_job_template('foobar', 'bin/foobar_ctl')
expect(template).to include('test_property=2')
end
it 're-evaluates job with new dynamic network configuration' do
manifest_hash = Bosh::Spec::NewDeployments.simple_manifest_with_instance_groups
manifest_hash['instance_groups'].first['instances'] = 1
manifest_hash['instance_groups'].first['jobs'].first['properties'] = { 'network_name' => 'a' }
cloud_config_hash = Bosh::Spec::NewDeployments.simple_cloud_config
cloud_config_hash['networks'].first['type'] = 'dynamic'
cloud_config_hash['networks'].first['cloud_properties'] = {}
cloud_config_hash['networks'].first.delete('subnets')
current_sandbox.cpi.commands.make_create_vm_always_use_dynamic_ip('127.0.0.101')
deploy_from_scratch(cloud_config_hash: cloud_config_hash, manifest_hash: manifest_hash)
# VM deployed for the first time knows about correct dynamic IP
instance = director.instance('foobar', '0')
template = instance.read_job_template('foobar', 'bin/foobar_ctl')
expect(template).to include('a_ip=127.0.0.101')
expect(template).to include("spec.address=#{instance.id}.foobar.a.simple.bosh")
# Force VM recreation
cloud_config_hash['vm_types'].first['cloud_properties'] = { 'changed' => true }
upload_cloud_config(cloud_config_hash: cloud_config_hash)
current_sandbox.cpi.commands.make_create_vm_always_use_dynamic_ip('127.0.0.102')
deploy_simple_manifest(manifest_hash: manifest_hash)
# Recreated VM due to the resource pool change knows about correct dynamic IP
instance = director.instance('foobar', '0')
template = instance.read_job_template('foobar', 'bin/foobar_ctl')
expect(template).to include('a_ip=127.0.0.102')
expect(template).to include("spec.address=#{instance.id}.foobar.a.simple.bosh")
end
it 'does not redeploy if the order of properties get changed' do
manifest_hash = Bosh::Spec::NewDeployments.simple_manifest_with_instance_groups
manifest_hash['instance_groups'].first['jobs'].first['properties'] = {
'test_property' =>
{
'q2GB' => 'foo',
'q4GB' => 'foo',
'q8GB' => 'foo',
'q46GB' => 'foo',
'q82GB' => 'foo',
'q64GB' => 'foo',
'q428GB' => 'foo',
},
}
manifest_hash['instance_groups'].first['instances'] = 1
deploy_from_scratch(manifest_hash: manifest_hash, cloud_config_hash: Bosh::Spec::NewDeployments.simple_cloud_config)
expect(director.instances.count).to eq(1)
instance = director.instance('foobar', '0')
template = instance.read_job_template('foobar', 'bin/foobar_ctl')
expected_rendered_template = '"test_property={"q2GB"=>"foo", "q428GB"=>"foo", ' \
'"q46GB"=>"foo", "q4GB"=>"foo", "q64GB"=>"foo", "q82GB"=>"foo", "q8GB"=>"foo"}"'
expect(template).to include(expected_rendered_template)
output = deploy(manifest_hash: manifest_hash)
expect(output).to_not match(/Updating instance foobar/)
instance = director.instance('foobar', '0')
template = instance.read_job_template('foobar', 'bin/foobar_ctl')
expect(template).to include(expected_rendered_template)
end
context 'health monitor', hm: true do
with_reset_hm_before_each
it 'creates alerts to mark the start and end of an update deployment' do
manifest_hash = Bosh::Spec::NewDeployments.simple_manifest_with_instance_groups
manifest_hash['instance_groups'].first['instances'] = 1
deploy_from_scratch(manifest_hash: manifest_hash, cloud_config_hash: Bosh::Spec::NewDeployments.simple_cloud_config)
waiter.wait(60) do
expect(health_monitor.read_log).to match(/\[ALERT\] Alert @ .* Begin update deployment for 'simple'/)
end
waiter.wait(120) do
expect(health_monitor.read_log).to match(/\[ALERT\] Alert @ .* Finish update deployment for 'simple'/)
end
# delete this assertion on heartbeat output if it fails... This assertion adds ~60s to the suite. It's not worth it.
waiter.wait(120) do
expect(health_monitor.read_log).to match(/\[HEARTBEAT\] Heartbeat from \w.*\/\w.* \(agent_id=\w.*\)/)
end
end
end
end
| 44.883929 | 122 | 0.713348 |
794eb69ddaba9034762c484c0729d38db8181b8e | 1,106 | describe 'Gratan::Client#export' do
context 'when function exists' do
let(:grantfile) {
<<-RUBY
user "scott", "%" do
on "*.*" do
grant "USAGE"
end
on "FUNCTION #{TEST_DATABASE}.my_func" do
grant "EXECUTE"
end
end
RUBY
}
subject { client }
before do
mysql do |cli|
drop_database(cli)
create_database(cli)
create_function(cli, :my_func)
end
apply(subject) do
grantfile
end
end
it do
expect(subject.export.strip).to eq grantfile.strip
end
end
context 'when procedure exists' do
let(:grantfile) {
<<-RUBY
user "scott", "%" do
on "*.*" do
grant "USAGE"
end
on "PROCEDURE #{TEST_DATABASE}.my_prcd" do
grant "EXECUTE"
end
end
RUBY
}
subject { client }
before do
mysql do |cli|
drop_database(cli)
create_database(cli)
create_procedure(cli, :my_prcd)
end
apply(subject) do
grantfile
end
end
it do
expect(subject.export.strip).to eq grantfile.strip
end
end
end
| 15.8 | 56 | 0.571429 |
18f28f87f0f5f81fb369f3ea805f4ecb1139b43b | 2,908 | require 'spec_helper'
describe Spree::Admin::TaxonomiesController, type: :controller do
stub_authorization!
let(:store) { create(:store) }
let(:new_store) { create(:store) }
let!(:taxonomy_1) { create(:taxonomy, store: store) }
let!(:taxonomy_2) { create(:taxonomy, store: store) }
let!(:taxonomy_3) { create(:taxonomy) }
before do
allow_any_instance_of(described_class).to receive(:current_store).and_return(store)
end
describe '#index' do
it 'should assign only the store credits for user and current store' do
get :index
expect(assigns(:collection)).to include taxonomy_1
expect(assigns(:collection)).to include taxonomy_2
expect(assigns(:collection)).not_to include taxonomy_3
end
end
context '#new' do
it 'should create taxonomy' do
get :new
expect(response.status).to eq(200)
end
end
describe '#create' do
let(:request) { post :create, params: { taxonomy: { name: 'Shirts' } } }
it 'should create taxonomy for current store' do
expect{ request }.to change { store.taxonomies.count }.by(1)
expect(response).to be_redirect
end
context 'different store' do
subject(:create_request) { post(:create, params: {taxonomy: {name: 'Bags'}}) }
before do
allow_any_instance_of(described_class).to receive(:current_store).and_return(new_store)
end
it 'should not create taxonomy for store' do
expect{ subject }.not_to change { store.taxonomies.reload.count }
expect(response).to be_redirect
end
it 'should create taxonomy for new store' do
expect{ subject }.to change { new_store.taxonomies.reload.count }.by(1)
expect(response).to be_redirect
end
end
end
describe '#update' do
it 'should allow to update current store taxonomy' do
expect{ put(:update, params: { id: taxonomy_1.id, taxonomy: { name: 'Beverages' } }) }.to change{taxonomy_1.reload.name}.to('Beverages')
end
it 'should not allow to update not current store taxonomy' do
expect{ put(:update, params: { id: taxonomy_3.id, taxonomy: { name: 'Shoes' } }) }.not_to change{taxonomy_3.reload.name}
end
end
describe '#destroy' do
before { delete :destroy, params: { id: taxonomy.id } }
context 'when current store taxonomy' do
let(:taxonomy) { taxonomy_1 }
it 'should be able to destroy taxonomy' do
expect(assigns(:object)).to eq(taxonomy)
expect(response).to have_http_status(:found)
expect(flash[:success]).to eq("Taxonomy \"#{taxonomy.name}\" has been successfully removed!")
end
end
context 'when not current store taxonomy' do
let(:taxonomy) { taxonomy_3 }
it 'should be able to destroy taxonomy' do
expect(assigns(:object)).to be_nil
expect(flash[:error]).to eq("Taxonomy is not found")
end
end
end
end
| 31.608696 | 142 | 0.664374 |
edd75cfd0d8af69d60700600e2701d125514171e | 255 | # Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :mechanize_store_freight, :class => MechanizeStore::Freight do
value 1.5
service "MyString"
delivery_time 1
zipcode "MyString"
end
end
| 23.181818 | 72 | 0.745098 |
110019febace5cc202fc0ee8cd007ab97b537c1b | 3,731 | #
# lolcat (c)2011 moe@busyloop.net
#
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
# Version 2, December 2004
#
# Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
#
# Everyone is permitted to copy and distribute verbatim or modified
# copies of this license document, and changing it is allowed as long
# as the name is changed.
#
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
# 0. You just DO WHAT THE FUCK YOU WANT TO.
require "lolcat/version"
require "lolcat/lol"
require 'stringio'
require 'trollop'
module Lol
def self.halp!(text, opts={})
opts = {
:animate => false,
:duration => 12,
:os => 0,
:speed => 20,
:spread => 8.0,
:freq => 0.3
}.merge opts
begin
i = 20
o = rand(256)
text.split("\n").each do |line|
i -= 1
opts[:os] = o+i
Lol.println line, opts
end
puts "\n"
rescue Interrupt
end
exit 1
end
def self.cat!
p = Trollop::Parser.new do
version "lolcat #{Lolcat::VERSION} (c)2011 moe@busyloop.net"
banner <<HEADER
Usage: lolcat [OPTION]... [FILE]...
Concatenate FILE(s), or standard input, to standard output.
With no FILE, or when FILE is -, read standard input.
HEADER
banner ''
opt :spread, "Rainbow spread", :short => 'p', :default => 3.0
opt :freq, "Rainbow frequency", :short => 'F', :default => 0.1
opt :seed, "Rainbow seed, 0 = random", :short => 'S', :default => 0
opt :animate, "Enable psychedelics", :short => 'a', :default => false
opt :duration, "Animation duration", :short => 'd', :default => 12
opt :speed, "Animation speed", :short => 's', :default => 20.0
opt :force, "Force color even when stdout is not a tty", :short => 'f', :default => false
opt :version, "Print version and exit", :short => 'v'
opt :help, "Show this message", :short => 'h'
banner <<FOOTER
Examples:
lolcat f - g Output f's contents, then stdin, then g's contents.
lolcat Copy standard input to standard output.
fortune | lolcat Display a rainbow cookie.
Report lolcat bugs to <http://www.github.org/busyloop/lolcat/issues>
lolcat home page: <http://www.github.org/busyloop/lolcat/>
Report lolcat translation bugs to <http://speaklolcat.com/>
FOOTER
end
opts = Trollop::with_standard_exception_handling p do
begin
o = p.parse ARGV
rescue Trollop::HelpNeeded
buf = StringIO.new
p.educate buf
buf.rewind
halp! buf.read, {}
buf.close
end
o
end
p.die :spread, "must be > 0" if opts[:spread] < 0.1
p.die :duration, "must be > 0" if opts[:duration] < 0.1
p.die :speed, "must be > 0.1" if opts[:speed] < 0.1
opts[:os] = opts[:seed]
opts[:os] = rand(256) if opts[:os] == 0
begin
files = ARGV.empty? ? [:stdin] : ARGV[0..-1]
files.each do |file|
fd = ARGF if file == '-' or file == :stdin
begin
fd = File.open file unless fd == ARGF
if $stdout.tty? or opts[:force]
Lol.cat fd, opts
else
until fd.eof? do
$stdout.write(fd.read(8192))
end
end
rescue Errno::ENOENT
puts "lolcat: #{file}: No such file or directory"
exit 1
rescue Errno::EACCES
puts "lolcat: #{file}: Permission denied"
exit 1
rescue Errno::EISDIR
puts "lolcat: #{file}: Is a directory"
exit 1
rescue Errno::EPIPE
exit 1
end
end
rescue Interrupt
end
end
end
| 27.233577 | 95 | 0.573305 |
333d4858a5faff0299265a6272d022c710b19d3a | 1,118 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'socks_tunnel/version'
Gem::Specification.new do |spec|
spec.name = "socks_tunnel"
spec.version = SocksTunnel::VERSION
spec.authors = ["Weihu Chen"]
spec.email = ["cctiger36@gmail.com"]
spec.summary = %q{Establish secure tunnel via Socks 5.}
spec.description = %q{Establish secure tunnel via Socks 5. Dependents on EventMachine and ruby Fiber.}
spec.homepage = "https://github.com/cctiger36/socks_tunnel"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "bin"
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "eventmachine", "~> 1.2"
spec.add_dependency "thor", ">= 0.19", "< 0.21"
spec.add_development_dependency "bundler", "~> 1.16"
spec.add_development_dependency "rake", "~> 13.0"
spec.add_development_dependency "rspec", "~> 3.8"
end
| 38.551724 | 106 | 0.650268 |
33c86a3c6cc6eae9807a61810534f64a992673fd | 85 | class UserController < ApplicationController
def index
end
def show
end
end
| 10.625 | 44 | 0.752941 |
7ad0f92ce4ab026cf9f3238ea978f09113809074 | 3,940 | 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 = :local
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# 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 = "sportzhood_#{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
end
| 41.473684 | 102 | 0.758376 |
1da93910f418ad2c495712ac9c13b1d83022aaf0 | 23,492 | # Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
# stub: quick-admin 4.2.1 ruby lib
Gem::Specification.new do |s|
s.name = "quick-admin"
s.version = "4.2.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Ryan Wong"]
s.date = "2015-01-05"
s.description = "\n\n * bootstrap 3\n * fontawesome\n * haml\n * datagrid\n * responders\n * kaminari\n\n "
s.email = "lazing@gmail.com"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.mdown"
]
s.files = [
".document",
"Gemfile",
"LICENSE.txt",
"README.mdown",
"Rakefile",
"VERSION",
"app/assets/fonts/glyphicons-halflings-regular.eot",
"app/assets/fonts/glyphicons-halflings-regular.svg",
"app/assets/fonts/glyphicons-halflings-regular.ttf",
"app/assets/fonts/glyphicons-halflings-regular.woff",
"app/assets/images/.keep",
"app/assets/images/patterns/congruent_pentagon.png",
"app/assets/images/patterns/header-profile-skin-1.png",
"app/assets/images/patterns/header-profile-skin-2.png",
"app/assets/images/patterns/header-profile-skin-3.png",
"app/assets/images/patterns/header-profile.png",
"app/assets/images/patterns/otis_redding.png",
"app/assets/images/patterns/shattered.png",
"app/assets/images/patterns/triangular.png",
"app/assets/javascripts/quick-admin/base.js",
"app/assets/javascripts/quick-admin/datetimepicker.coffee",
"app/assets/stylesheets/quick-admin/base.scss",
"app/assets/stylesheets/quick-admin/datagrid-override.css.scss",
"app/assets/stylesheets/quick-admin/style.css.scss",
"app/controllers/quick_admin/base_controller.rb",
"app/helpers/quick_admin_helper.rb",
"app/views/kaminari/_first_page.html.haml",
"app/views/kaminari/_gap.html.haml",
"app/views/kaminari/_last_page.html.haml",
"app/views/kaminari/_next_page.html.haml",
"app/views/kaminari/_page.html.haml",
"app/views/kaminari/_paginator.html.haml",
"app/views/kaminari/_prev_page.html.haml",
"app/views/layouts/_menu.html.haml",
"app/views/layouts/application.html.haml",
"app/views/layouts/quick_admin/base.html.haml",
"app/views/quick_admin/_action_show.html.haml",
"app/views/quick_admin/_item.html.haml",
"app/views/quick_admin/base/edit.html.haml",
"app/views/quick_admin/base/index.html.haml",
"app/views/quick_admin/base/new.html.haml",
"app/views/quick_admin/base/show.html.haml",
"app/views/quick_grid/_form.html.erb",
"app/views/quick_grid/_head.html.haml",
"app/views/quick_grid/_order_for.html.haml",
"app/views/quick_grid/_row.html.haml",
"app/views/quick_grid/_table.html.haml",
"lib/assets/javascripts/.keep",
"lib/assets/javascripts/bootstrap-datetimepicker.js",
"lib/assets/javascripts/bootstrap-editable.js",
"lib/assets/javascripts/bootstrap-markdown.js",
"lib/assets/javascripts/inspinia.js",
"lib/assets/javascripts/lang/summernote-zh-CN.js",
"lib/assets/javascripts/locales/bootstrap-datetimepicker.zh-CN.js",
"lib/assets/javascripts/locales/bootstrap-datetimepicker.zh-TW.js",
"lib/assets/javascripts/markdown.js",
"lib/assets/javascripts/plugins/chartJs/Chart.min.js",
"lib/assets/javascripts/plugins/chosen/chosen.jquery.js",
"lib/assets/javascripts/plugins/dataTables/dataTables.bootstrap.js",
"lib/assets/javascripts/plugins/dataTables/jquery.dataTables.js",
"lib/assets/javascripts/plugins/datapicker/bootstrap-datepicker.js",
"lib/assets/javascripts/plugins/dropzone/dropzone.js",
"lib/assets/javascripts/plugins/easypiechart/easypiechart.js",
"lib/assets/javascripts/plugins/easypiechart/jquery.easypiechart.js",
"lib/assets/javascripts/plugins/fancybox/blank.gif",
"lib/assets/javascripts/plugins/fancybox/fancybox_loading.gif",
"lib/assets/javascripts/plugins/fancybox/fancybox_loading@2x.gif",
"lib/assets/javascripts/plugins/fancybox/fancybox_overlay.png",
"lib/assets/javascripts/plugins/fancybox/fancybox_sprite.png",
"lib/assets/javascripts/plugins/fancybox/fancybox_sprite@2x.png",
"lib/assets/javascripts/plugins/fancybox/helpers/fancybox_buttons.png",
"lib/assets/javascripts/plugins/fancybox/helpers/jquery.fancybox-buttons.css",
"lib/assets/javascripts/plugins/fancybox/helpers/jquery.fancybox-buttons.js",
"lib/assets/javascripts/plugins/fancybox/helpers/jquery.fancybox-media.js",
"lib/assets/javascripts/plugins/fancybox/helpers/jquery.fancybox-thumbs.css",
"lib/assets/javascripts/plugins/fancybox/helpers/jquery.fancybox-thumbs.js",
"lib/assets/javascripts/plugins/fancybox/jquery.fancybox.css",
"lib/assets/javascripts/plugins/fancybox/jquery.fancybox.js",
"lib/assets/javascripts/plugins/fancybox/jquery.fancybox.pack.js",
"lib/assets/javascripts/plugins/flot/curvedLines.js",
"lib/assets/javascripts/plugins/flot/excanvas.min.js",
"lib/assets/javascripts/plugins/flot/jquery.flot.js",
"lib/assets/javascripts/plugins/flot/jquery.flot.pie.js",
"lib/assets/javascripts/plugins/flot/jquery.flot.resize.js",
"lib/assets/javascripts/plugins/flot/jquery.flot.spline.js",
"lib/assets/javascripts/plugins/flot/jquery.flot.symbol.js",
"lib/assets/javascripts/plugins/flot/jquery.flot.tooltip.min.js",
"lib/assets/javascripts/plugins/fullcalendar/fullcalendar.min.js",
"lib/assets/javascripts/plugins/gritter/images/gritter-light.png",
"lib/assets/javascripts/plugins/gritter/images/gritter-long.png",
"lib/assets/javascripts/plugins/gritter/images/gritter.png",
"lib/assets/javascripts/plugins/gritter/images/ie-spacer.gif",
"lib/assets/javascripts/plugins/gritter/jquery.gritter.css",
"lib/assets/javascripts/plugins/gritter/jquery.gritter.min.js",
"lib/assets/javascripts/plugins/iCheck/icheck.min.js",
"lib/assets/javascripts/plugins/ionRangeSlider/ion.rangeSlider.min.js",
"lib/assets/javascripts/plugins/jasny/jasny-bootstrap.min.js",
"lib/assets/javascripts/plugins/jeditable/jquery.jeditable.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery-ui-i18n.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-af.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-ar-DZ.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-ar.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-az.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-be.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-bg.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-bs.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-ca.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-cs.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-cy-GB.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-da.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-de.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-el.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-en-AU.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-en-GB.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-en-NZ.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-eo.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-es.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-et.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-eu.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-fa.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-fi.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-fo.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-fr-CA.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-fr-CH.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-fr.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-gl.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-he.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-hi.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-hr.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-hu.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-hy.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-id.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-is.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-it.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-ja.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-ka.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-kk.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-km.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-ko.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-ky.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-lb.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-lt.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-lv.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-mk.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-ml.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-ms.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-nb.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-nl-BE.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-nl.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-nn.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-no.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-pl.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-pt-BR.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-pt.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-rm.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-ro.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-ru.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-sk.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-sl.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-sq.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-sr-SR.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-sr.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-sv.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-ta.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-th.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-tj.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-tr.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-uk.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-vi.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-zh-CN.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-zh-HK.min.js",
"lib/assets/javascripts/plugins/jquery-ui/i18n/jquery.ui.datepicker-zh-TW.min.js",
"lib/assets/javascripts/plugins/jquery-ui/images/animated-overlay.gif",
"lib/assets/javascripts/plugins/jquery-ui/images/ui-bg_flat_0_aaaaaa_40x100.png",
"lib/assets/javascripts/plugins/jquery-ui/images/ui-bg_flat_75_ffffff_40x100.png",
"lib/assets/javascripts/plugins/jquery-ui/images/ui-bg_glass_55_fbf9ee_1x400.png",
"lib/assets/javascripts/plugins/jquery-ui/images/ui-bg_glass_65_ffffff_1x400.png",
"lib/assets/javascripts/plugins/jquery-ui/images/ui-bg_glass_75_dadada_1x400.png",
"lib/assets/javascripts/plugins/jquery-ui/images/ui-bg_glass_75_e6e6e6_1x400.png",
"lib/assets/javascripts/plugins/jquery-ui/images/ui-bg_glass_95_fef1ec_1x400.png",
"lib/assets/javascripts/plugins/jquery-ui/images/ui-bg_highlight-soft_75_cccccc_1x100.png",
"lib/assets/javascripts/plugins/jquery-ui/images/ui-icons_222222_256x240.png",
"lib/assets/javascripts/plugins/jquery-ui/images/ui-icons_2e83ff_256x240.png",
"lib/assets/javascripts/plugins/jquery-ui/images/ui-icons_454545_256x240.png",
"lib/assets/javascripts/plugins/jquery-ui/images/ui-icons_888888_256x240.png",
"lib/assets/javascripts/plugins/jquery-ui/images/ui-icons_cd0a0a_256x240.png",
"lib/assets/javascripts/plugins/jquery-ui/jquery-ui.css",
"lib/assets/javascripts/plugins/jquery-ui/jquery-ui.js",
"lib/assets/javascripts/plugins/jquery-ui/jquery-ui.min.css",
"lib/assets/javascripts/plugins/jquery-ui/jquery-ui.min.js",
"lib/assets/javascripts/plugins/jsKnob/jquery.knob.js",
"lib/assets/javascripts/plugins/justified-gallery/README.md",
"lib/assets/javascripts/plugins/justified-gallery/jquery.justifiedgallery.css",
"lib/assets/javascripts/plugins/justified-gallery/jquery.justifiedgallery.js",
"lib/assets/javascripts/plugins/justified-gallery/jquery.justifiedgallery.min.css",
"lib/assets/javascripts/plugins/justified-gallery/jquery.justifiedgallery.min.js",
"lib/assets/javascripts/plugins/justified-gallery/loading.gif",
"lib/assets/javascripts/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js",
"lib/assets/javascripts/plugins/jvectormap/jquery-jvectormap-world-mill-en.js",
"lib/assets/javascripts/plugins/metisMenu/jquery.metisMenu.js",
"lib/assets/javascripts/plugins/morris/morris.js",
"lib/assets/javascripts/plugins/morris/raphael-2.1.0.min.js",
"lib/assets/javascripts/plugins/nouslider/jquery.nouislider.min.js",
"lib/assets/javascripts/plugins/pace/pace.min.js",
"lib/assets/javascripts/plugins/peity/jquery.peity.min.js",
"lib/assets/javascripts/plugins/rickshaw/rickshaw.min.js",
"lib/assets/javascripts/plugins/rickshaw/vendor/d3.v3.js",
"lib/assets/javascripts/plugins/slimscroll/jquery.slimscroll.js",
"lib/assets/javascripts/plugins/slimscroll/jquery.slimscroll.min.js",
"lib/assets/javascripts/plugins/sparkline/jquery.sparkline.min.js",
"lib/assets/javascripts/plugins/staps/jquery.steps.min.js",
"lib/assets/javascripts/plugins/summernote/summernote.min.js",
"lib/assets/javascripts/plugins/switchery/switchery.js",
"lib/assets/javascripts/plugins/validate/jquery.validate.min.js",
"lib/assets/javascripts/plugins/video/responsible-video.js",
"lib/assets/javascripts/summernote.js",
"lib/assets/javascripts/summernote.min.js",
"lib/assets/javascripts/to-markdown.js",
"lib/assets/stylesheets/.keep",
"lib/assets/stylesheets/bootstrap-datetimepicker.css",
"lib/assets/stylesheets/bootstrap-editable.css",
"lib/assets/stylesheets/bootstrap-markdown.min.css",
"lib/assets/stylesheets/framework/badgets_labels.sass",
"lib/assets/stylesheets/framework/base.sass",
"lib/assets/stylesheets/framework/buttons.sass",
"lib/assets/stylesheets/framework/custom.sass",
"lib/assets/stylesheets/framework/elements.sass",
"lib/assets/stylesheets/framework/media.sass",
"lib/assets/stylesheets/framework/mixins.sass",
"lib/assets/stylesheets/framework/navigation.sass",
"lib/assets/stylesheets/framework/pages.sass",
"lib/assets/stylesheets/framework/sidebar.sass",
"lib/assets/stylesheets/framework/skins.sass",
"lib/assets/stylesheets/framework/style.sass",
"lib/assets/stylesheets/framework/theme-config.sass",
"lib/assets/stylesheets/framework/typography.sass",
"lib/assets/stylesheets/framework/variables.sass",
"lib/assets/stylesheets/jqueryui-editable.css",
"lib/assets/stylesheets/plugins/chosen/chosen-sprite.png",
"lib/assets/stylesheets/plugins/chosen/chosen-sprite@2x.png",
"lib/assets/stylesheets/plugins/chosen/chosen.css",
"lib/assets/stylesheets/plugins/dataTables/dataTables.bootstrap.css",
"lib/assets/stylesheets/plugins/datapicker/datepicker3.css",
"lib/assets/stylesheets/plugins/dropzone/basic.css",
"lib/assets/stylesheets/plugins/dropzone/dropzone.css",
"lib/assets/stylesheets/plugins/fullcalendar/fullcalendar.css",
"lib/assets/stylesheets/plugins/fullcalendar/fullcalendar.print.css",
"lib/assets/stylesheets/plugins/iCheck/custom.css",
"lib/assets/stylesheets/plugins/iCheck/green.png",
"lib/assets/stylesheets/plugins/iCheck/green@2x.png",
"lib/assets/stylesheets/plugins/images/sort.png",
"lib/assets/stylesheets/plugins/images/sort_asc.png",
"lib/assets/stylesheets/plugins/images/sort_desc.png",
"lib/assets/stylesheets/plugins/images/sprite-skin-flat.png",
"lib/assets/stylesheets/plugins/images/sprite-skin-flat2.png",
"lib/assets/stylesheets/plugins/images/sprite-skin-nice.png",
"lib/assets/stylesheets/plugins/images/sprite-skin-simple.png",
"lib/assets/stylesheets/plugins/images/spritemap.png",
"lib/assets/stylesheets/plugins/images/spritemap@2x.png",
"lib/assets/stylesheets/plugins/ionRangeSlider/ion.rangeSlider.css",
"lib/assets/stylesheets/plugins/ionRangeSlider/ion.rangeSlider.skinFlat.css",
"lib/assets/stylesheets/plugins/ionRangeSlider/ion.rangeSlider.skinNice.css",
"lib/assets/stylesheets/plugins/ionRangeSlider/ion.rangeSlider.skinSimple.css",
"lib/assets/stylesheets/plugins/jasny/jasny-bootstrap.min.css",
"lib/assets/stylesheets/plugins/morris/morris-0.4.3.min.css",
"lib/assets/stylesheets/plugins/nouslider/jquery.nouislider.css",
"lib/assets/stylesheets/plugins/social-buttons/social-buttons.css",
"lib/assets/stylesheets/plugins/steps/jquery.steps.css",
"lib/assets/stylesheets/plugins/summernote/summernote-bs3.css",
"lib/assets/stylesheets/plugins/summernote/summernote.css",
"lib/assets/stylesheets/plugins/switchery/switchery.css",
"lib/assets/stylesheets/summernote-bs2.css",
"lib/assets/stylesheets/summernote-bs3.css",
"lib/assets/stylesheets/summernote.css",
"lib/quick-admin.rb",
"lib/quick_admin/datagrid.rb",
"lib/quick_admin/rails.rb",
"quick-admin.gemspec",
"spec/helpers/quick_admin_helper_spec.rb"
]
s.homepage = "http://github.com/lazing/quick-admin"
s.licenses = ["MIT"]
s.rubygems_version = "2.2.2"
s.summary = "easy to customize quick administrator backend framework"
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<rails>, ["~> 4.2"])
s.add_runtime_dependency(%q<haml>, [">= 0"])
s.add_runtime_dependency(%q<haml-rails>, [">= 0"])
s.add_runtime_dependency(%q<coffee-rails>, [">= 0"])
s.add_runtime_dependency(%q<meta-tags>, [">= 0"])
s.add_runtime_dependency(%q<simple_form>, ["~> 3.1.0"])
s.add_runtime_dependency(%q<kaminari>, [">= 0"])
s.add_runtime_dependency(%q<datagrid>, [">= 0"])
s.add_runtime_dependency(%q<responders>, ["~> 2.0"])
s.add_runtime_dependency(%q<nprogress-rails>, [">= 0"])
s.add_runtime_dependency(%q<sass-rails>, [">= 0"])
s.add_runtime_dependency(%q<bootstrap-sass>, [">= 0"])
s.add_runtime_dependency(%q<font-awesome-rails>, [">= 0"])
s.add_development_dependency(%q<shoulda>, [">= 0"])
s.add_development_dependency(%q<rdoc>, ["~> 3.12"])
s.add_development_dependency(%q<rspec-rails>, [">= 0"])
s.add_development_dependency(%q<rspec-activemodel-mocks>, [">= 0"])
s.add_development_dependency(%q<spring>, [">= 0"])
s.add_development_dependency(%q<spring-commands-rspec>, [">= 0"])
s.add_development_dependency(%q<guard-rspec>, [">= 0"])
s.add_development_dependency(%q<guard-haml>, [">= 0"])
s.add_development_dependency(%q<bundler>, ["~> 1.0"])
s.add_development_dependency(%q<jeweler>, ["~> 2.0.1"])
s.add_development_dependency(%q<simplecov>, [">= 0"])
else
s.add_dependency(%q<rails>, ["~> 4.2"])
s.add_dependency(%q<haml>, [">= 0"])
s.add_dependency(%q<haml-rails>, [">= 0"])
s.add_dependency(%q<coffee-rails>, [">= 0"])
s.add_dependency(%q<meta-tags>, [">= 0"])
s.add_dependency(%q<simple_form>, ["~> 3.1.0"])
s.add_dependency(%q<kaminari>, [">= 0"])
s.add_dependency(%q<datagrid>, [">= 0"])
s.add_dependency(%q<responders>, ["~> 2.0"])
s.add_dependency(%q<nprogress-rails>, [">= 0"])
s.add_dependency(%q<sass-rails>, [">= 0"])
s.add_dependency(%q<bootstrap-sass>, [">= 0"])
s.add_dependency(%q<font-awesome-rails>, [">= 0"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<rspec-rails>, [">= 0"])
s.add_dependency(%q<rspec-activemodel-mocks>, [">= 0"])
s.add_dependency(%q<spring>, [">= 0"])
s.add_dependency(%q<spring-commands-rspec>, [">= 0"])
s.add_dependency(%q<guard-rspec>, [">= 0"])
s.add_dependency(%q<guard-haml>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0"])
s.add_dependency(%q<jeweler>, ["~> 2.0.1"])
s.add_dependency(%q<simplecov>, [">= 0"])
end
else
s.add_dependency(%q<rails>, ["~> 4.2"])
s.add_dependency(%q<haml>, [">= 0"])
s.add_dependency(%q<haml-rails>, [">= 0"])
s.add_dependency(%q<coffee-rails>, [">= 0"])
s.add_dependency(%q<meta-tags>, [">= 0"])
s.add_dependency(%q<simple_form>, ["~> 3.1.0"])
s.add_dependency(%q<kaminari>, [">= 0"])
s.add_dependency(%q<datagrid>, [">= 0"])
s.add_dependency(%q<responders>, ["~> 2.0"])
s.add_dependency(%q<nprogress-rails>, [">= 0"])
s.add_dependency(%q<sass-rails>, [">= 0"])
s.add_dependency(%q<bootstrap-sass>, [">= 0"])
s.add_dependency(%q<font-awesome-rails>, [">= 0"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<rspec-rails>, [">= 0"])
s.add_dependency(%q<rspec-activemodel-mocks>, [">= 0"])
s.add_dependency(%q<spring>, [">= 0"])
s.add_dependency(%q<spring-commands-rspec>, [">= 0"])
s.add_dependency(%q<guard-rspec>, [">= 0"])
s.add_dependency(%q<guard-haml>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0"])
s.add_dependency(%q<jeweler>, ["~> 2.0.1"])
s.add_dependency(%q<simplecov>, [">= 0"])
end
end
| 60.390746 | 128 | 0.726332 |
edf45ac673dd538a47f1c06b780944db365b5bc6 | 2,314 | class Openni < Formula
homepage "http://www.openni.org/"
head "https://github.com/OpenNI/OpenNI.git"
stable do
url "https://github.com/OpenNI/OpenNI/archive/Stable-1.5.7.10.tar.gz"
sha256 "34b0bbf68633bb213dcb15408f979d5384bdceb04e151fa519e107a12e225852"
# Fix for Mavericks
patch do
url "https://github.com/OpenNI/OpenNI/pull/92.diff"
sha256 "d2bc9bd628cc463b4e7cdc9bf3abc3ba78d04e4d451d02f7f6cf7d0c4d032634"
end
end
devel do
url "https://github.com/OpenNI/OpenNI/archive/Unstable-1.5.8.5.tar.gz"
sha256 "766d3b9745e8d486ad2998e1437bb161188282cfc1553502386457d1438df42f"
# Fix for Mavericks
patch do
url "https://github.com/OpenNI/OpenNI/pull/95.diff"
sha256 "722fb0a6e6e99a5cc7c7e862ac802dfd3d03785c27af1d20d7f48314ff5154dd"
end
end
option :universal
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "libusb"
depends_on "doxygen" => :build
def install
ENV.universal_binary if build.universal?
# Fix build files
inreplace "Source/OpenNI/XnOpenNI.cpp", "/var/lib/ni/", "#{var}/lib/ni/"
inreplace "Platform/Linux/Build/Common/CommonJavaMakefile", "/usr/share/java", "#{share}/java"
# Build OpenNI
cd "Platform/Linux/CreateRedist"
chmod 0755, "RedistMaker"
system "./RedistMaker"
cd Dir.glob("../Redist/OpenNI-Bin-Dev-MacOSX-v*")[0]
bin.install Dir["Bin/ni*"]
lib.install Dir["Lib/*"]
(include+"ni").install Dir["Include/*"]
(share+"java").install Dir["Jar/*"]
(share+"openni/samples").install Dir["Samples/*"]
doc.install "Documentation"
# Create and install a pkg-config file
(lib/"pkgconfig/libopenni.pc").write <<-EOS.undent
prefix=#{prefix}
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir=${prefix}/include/ni
Name: OpenNI
Description: A general purpose driver for all OpenNI cameras.
Version: #{version}
Cflags: -I${includedir}
Libs: -L${libdir} -lOpenNI -lOpenNI.jni -lnimCodecs -lnimMockNodes -lnimRecorder
EOS
end
def post_install
mkpath "#{var}/lib/ni"
system "#{bin}/niReg", "#{lib}/libnimMockNodes.dylib"
system "#{bin}/niReg", "#{lib}/libnimCodecs.dylib"
system "#{bin}/niReg", "#{lib}/libnimRecorder.dylib"
end
end
| 29.666667 | 98 | 0.682368 |
e866cf337f946595b921421a7f80909c39866ea0 | 3,950 | require 'time'
require 'date'
class Time #:nodoc:
class << self
def mock_time
mocked_time_stack_item = Timecop.top_stack_item
mocked_time_stack_item.nil? ? nil : mocked_time_stack_item.time(self)
end
alias_method :now_without_mock_time, :now
def now_with_mock_time
mock_time || now_without_mock_time
end
alias_method :now, :now_with_mock_time
alias_method :new_without_mock_time, :new
def new_with_mock_time(*args)
args.size <= 0 ? now : new_without_mock_time(*args)
end
alias_method :new, :new_with_mock_time
end
end
class Date #:nodoc:
class << self
def mock_date
mocked_time_stack_item.nil? ? nil : mocked_time_stack_item.date(self)
end
alias_method :today_without_mock_date, :today
def today_with_mock_date
mock_date || today_without_mock_date
end
alias_method :today, :today_with_mock_date
alias_method :strptime_without_mock_date, :strptime
def strptime_with_mock_date(str = '-4712-01-01', fmt = '%F', start = Date::ITALY)
unless start == Date::ITALY
raise ArgumentError, "Timecop's #{self}::#{__method__} only " +
"supports Date::ITALY for the start argument."
end
d = Date._strptime(str, fmt) || Date.strptime_without_mock_date(str, fmt)
now = Time.now.to_date
year = d[:year] || now.year
mon = d[:mon] || now.mon
if d[:mday]
Date.new(year, mon, d[:mday])
elsif d[:wday]
Date.new(year, mon, now.mday) + (d[:wday] - now.wday)
elsif d[:yday]
Date.new(year).next_day(d[:yday] - 1)
elsif d[:cwyear] && d[:cweek]
if d[:cwday]
Date.commercial(d[:cwyear], d[:cweek], d[:cwday])
else
Date.commercial(d[:cwyear], d[:cweek])
end
elsif d[:seconds]
Time.at(d[:seconds]).to_date
else
Date.new(year, mon)
end
end
alias_method :strptime, :strptime_with_mock_date
def parse_with_mock_date(*args)
parsed_date = parse_without_mock_date(*args)
return parsed_date unless mocked_time_stack_item
date_hash = Date._parse(*args)
case
when date_hash[:year] && date_hash[:mon]
parsed_date
when date_hash[:mon] && date_hash[:mday]
Date.new(mocked_time_stack_item.year, date_hash[:mon], date_hash[:mday])
when date_hash[:wday]
closest_wday(date_hash[:wday])
else
parsed_date + mocked_time_stack_item.travel_offset_days
end
end
alias_method :parse_without_mock_date, :parse
alias_method :parse, :parse_with_mock_date
def mocked_time_stack_item
Timecop.top_stack_item
end
def closest_wday(wday)
today = Date.today
result = today - today.wday
result += 1 until wday == result.wday
result
end
end
end
class DateTime #:nodoc:
class << self
def mock_time
mocked_time_stack_item.nil? ? nil : mocked_time_stack_item.datetime(self)
end
def now_with_mock_time
mock_time || now_without_mock_time
end
alias_method :now_without_mock_time, :now
alias_method :now, :now_with_mock_time
def parse_with_mock_date(*args)
date_hash = Date._parse(*args)
parsed_date = parse_without_mock_date(*args)
return parsed_date unless mocked_time_stack_item
date_hash = DateTime._parse(*args)
case
when date_hash[:year] && date_hash[:mon]
parsed_date
when date_hash[:mon] && date_hash[:mday]
DateTime.new(mocked_time_stack_item.year, date_hash[:mon], date_hash[:mday])
when date_hash[:wday]
Date.closest_wday(date_hash[:wday]).to_datetime
else
parsed_date + mocked_time_stack_item.travel_offset_days
end
end
alias_method :parse_without_mock_date, :parse
alias_method :parse, :parse_with_mock_date
def mocked_time_stack_item
Timecop.top_stack_item
end
end
end
| 26.510067 | 85 | 0.662785 |
4ad9639a8df2e174d6d4b9af845dce967b581680 | 900 | require 'spec_helper'
describe OmniAuth::MLH do
subject do
OmniAuth::Strategies::MLH.new(nil, @options || {})
end
it_should_behave_like 'an oauth2 strategy'
describe '#client' do
it 'has correct MyMLH site' do
expect(subject.client.site).to eq('https://my.mlh.io')
end
it 'has correct authorize url' do
expect(subject.client.options[:authorize_url]).to eq('/oauth/authorize')
end
it 'has correct token url' do
expect(subject.client.options[:token_url]).to eq('/oauth/token')
end
it 'runs the setup block if passed one' do
counter = ''
@options = { :setup => Proc.new { |env| counter = 'ok' } }
subject.setup_phase
expect(counter).to eq("ok")
end
end
describe '#callback_path' do
it "has the correct callback path" do
expect(subject.callback_path).to eq('/auth/mlh/callback')
end
end
end
| 24.324324 | 78 | 0.646667 |
1801e95e6dece3fd4566be945ae4472b1f3cc525 | 2,157 | require 'ddtrace/contrib/support/spec_helper'
require 'redis'
require 'ddtrace'
RSpec.describe 'Redis configuration resolver' do
let(:resolver) { Datadog::Contrib::Redis::Configuration::Resolver.new }
context 'when :default magic keyword' do
it { expect(resolver.resolve(:default)).to eq(:default) }
end
context 'when unix socket provided' do
let(:options) { { url: 'unix://path/to/file' } }
it do
expect(resolver.resolve(options)).to eq(url: 'unix://path/to/file')
end
end
context 'when redis connexion string provided' do
let(:options) { { url: 'redis://127.0.0.1:6379/0' } }
it do
expect(resolver.resolve(options)).to eq(host: '127.0.0.1',
port: 6379,
db: 0,
scheme: 'redis')
end
end
context 'when host, port, db and scheme provided' do
let(:options) do
{
host: '127.0.0.1',
port: 6379,
db: 0,
scheme: 'redis'
}
end
it do
expect(resolver.resolve(options)).to eq(host: '127.0.0.1',
port: 6379,
db: 0,
scheme: 'redis')
end
end
context 'when host, port and db provided' do
let(:options) do
{
host: '127.0.0.1',
port: 6379,
db: 0
}
end
it do
expect(resolver.resolve(options)).to eq(host: '127.0.0.1',
port: 6379,
db: 0,
scheme: 'redis')
end
end
context 'when host and portprovided' do
let(:options) do
{
host: '127.0.0.1',
port: 6379
}
end
it do
expect(resolver.resolve(options)).to eq(host: '127.0.0.1',
port: 6379,
db: 0,
scheme: 'redis')
end
end
end
| 25.987952 | 73 | 0.437645 |
d5d5548ff1810258f761829bea5e927d27acd822 | 1,577 | module UcbRails::LdapPerson
class TestFinder
PersonNotFound = Class.new(StandardError)
def find_by_uid(uid)
uid.presence and find_by_attributes(:uid => uid.to_s).first
end
def find_by_uid!(uid)
find_by_uid(uid) || raise(PersonNotFound, "uid=#{uid.inspect}")
end
def find_by_first_last(first_name, last_name, options={})
find_by_attributes(:first_name => first_name, :last_name => last_name)
end
def find_by_attributes(attributes)
self.class.entries.select { |entry| entry_matches_attributes(entry, attributes) }
end
def entry_matches_attributes(entry, attributes)
attributes.keys.all? do |key|
value = attributes[key].to_s.downcase
value.blank? || entry.send(key).downcase.include?(value)
end
end
def self.entries
[
new_entry("1", 'art', "Art", "Andrews", "art@example.com", "999-999-0001", "Dept 1"),
new_entry("2", 'beth', "Beth", "Brown", "beth@example.com", "999-999-0002", "Dept 2"),
new_entry("61065", 'runner', "Steven", "Hansen", "runner@berkeley.edu", "999-999-9998", "EAS"),
new_entry("191501", 'stevedowney', "Steve", "Downey", "sldowney@berkeley.edu", "999-999-9999", "EAS"),
]
end
def self.new_entry(uid, calnet_id, fn, ln, email, phone, depts)
::UcbRails::LdapPerson::Entry.new(
:uid => uid,
:calnet_id => calnet_id,
:first_name => fn,
:last_name => ln,
:email => email,
:phone => phone,
:departments => depts
)
end
end
end | 31.54 | 110 | 0.615726 |
bb146f143a7158ac39e13084b642c3610cb3d861 | 1,053 | module Sources
module Datapoints
class Error < StandardError; end
class NotFoundError < Error; end
class Base
def available?
true
end
def supports_target_browsing?
false
end
def supports_functions?
false
end
def custom_fields
[]
end
def default_fields
[
{ name: "targets", title: "Targets", mandatory: true }
]
end
def get(options = {})
end
protected
def targetsArray(targets)
targets.split(";").map { |t| t.strip }
end
@@cache = {}
def cached_get(key)
return yield if Rails.env.test?
time = Time.now.to_i
if entry = @@cache[key]
if entry[:time] > 5.minutes.ago.to_i
Rails.logger.info("Sources::Datapoints - CACHE HIT for #{key}")
return entry[:value]
end
end
value = yield
@@cache[key] = { :time => time, :value => value }
value
end
end
end
end | 17.847458 | 75 | 0.51567 |
1869f9b594680548c356e46b0b02fcc1039ac3c8 | 1,717 | module Roby
module Interface
# Representation of a subcommand on {Interface} on the shell side
class SubcommandClient
# @return [ShellClient,ShellSubcommand] the parent shell /
# subcommand
attr_reader :parent
# @return [
# @return [String] the subcommand name
attr_reader :name
# @return [String] the subcommand description
attr_reader :description
# @return [Hash<String,Command>] the set of commands on this subcommand
attr_reader :commands
def initialize(parent, name, description, commands)
@parent, @name, @description, @commands =
parent, name, description, commands
end
def call(path, m, *args)
parent.call([name] + path, m, *args)
end
def path
parent.path + [name]
end
def async_call(path, m, *args, &block)
parent.async_call([name] + path, m, *args, &block)
end
def find_subcommand_by_name(m)
@commands[m.to_s]
end
def has_command?(m)
@commands.has_key?(m.to_s)
end
def method_missing(m, *args, &block)
if (sub = find_subcommand_by_name(m))
SubcommandClient.new(self, m, sub.description, sub.commands)
elsif (match = /^async_(.*)$/.match(m.to_s))
async_call([], match[1].to_sym, *args, &block)
else
call([], m, *args)
end
end
end
end
end
| 32.396226 | 83 | 0.499126 |
e8b551e5608f6e69f0452974a9cc4773c410f4ea | 198 | module Mazi::Model
class Notification < Sequel::Model
def enable
self.enabled = true
self.save
end
def disable
self.enabled = false
self.save
end
end
end | 15.230769 | 36 | 0.611111 |
03e18543a17ca54fe9833194264a72ceca0a2923 | 5,723 | # Copyright (c) 2018-2019 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: MIT
# DO NOT MODIFY. THIS CODE IS GENERATED. CHANGES WILL BE OVERWRITTEN.
# vcenter - VMware vCenter Server provides a centralized platform for managing your VMware vSphere environments
require 'date'
module VSphereAutomation
module VCenter
class VcenterVchaClusterWitnessSpec
attr_accessor :placement
attr_accessor :ha_ip
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'placement' => :'placement',
:'ha_ip' => :'ha_ip'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'placement' => :'VcenterVchaPlacementSpec',
:'ha_ip' => :'VcenterVchaIpSpec'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.has_key?(:'placement')
self.placement = attributes[:'placement']
end
if attributes.has_key?(:'ha_ip')
self.ha_ip = attributes[:'ha_ip']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
if @ha_ip.nil?
invalid_properties.push('invalid value for "ha_ip", ha_ip cannot be nil.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if @ha_ip.nil?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
placement == o.placement &&
ha_ip == o.ha_ip
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[placement, ha_ip].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN, :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = VSphereAutomation::VCenter.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
end
| 29.050761 | 111 | 0.61943 |
4a996411e2e9cb2cbaaa4ffa357377aa3210bbad | 1,834 | # frozen_string_literal: true
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "gapic/common"
require "gapic/config"
require "gapic/config/method"
require "google/ads/google_ads/version"
require "google/ads/google_ads/v5/services/campaign_criterion_simulation_service/credentials"
require "google/ads/google_ads/v5/services/campaign_criterion_simulation_service/paths"
require "google/ads/google_ads/v5/services/campaign_criterion_simulation_service/client"
module Google
module Ads
module GoogleAds
module V5
module Services
##
# Service to fetch campaign criterion simulations.
#
# To load this service and instantiate a client:
#
# require "google/ads/google_ads/v5/services/campaign_criterion_simulation_service"
# client = ::Google::Ads::GoogleAds::V5::Services::CampaignCriterionSimulationService::Client.new
#
module CampaignCriterionSimulationService
end
end
end
end
end
end
helper_path = ::File.join __dir__, "campaign_criterion_simulation_service", "helpers.rb"
require "google/ads/google_ads/v5/services/campaign_criterion_simulation_service/helpers" if ::File.file? helper_path
| 35.269231 | 117 | 0.741003 |
28c05e284a02883212608df2e9bcd1b6949e4ccf | 2,588 | require 'test_helper'
require 'messente/omnimessage'
require 'messente/sending_error'
class OmnimessageTest < ActiveSupport::TestCase
def setup
super
@recipient = '+37250060070'
@text = 'Your text sms'
end
def test_initialization_requires_recipent_text_and_channel
instance = Messente::Omnimessage.new(@recipient, @text)
assert_equal(@recipient, instance.recipient)
assert_equal(@text, instance.text)
end
def test_server_url_is_a_constant
assert_equal(URI('https://api.messente.com/v1/omnimessage'), Messente::Omnimessage::BASE_URL)
end
def test_username_and_password_are_constants
assert_equal('messente_user', Messente::Omnimessage::USERNAME)
assert_equal('messente_password', Messente::Omnimessage::PASSWORD)
assert_equal('sms', Messente::Omnimessage::CHANNEL)
end
def test_request_is_an_http_post_request
instance = Messente::Omnimessage.new(@recipient, @text)
assert(instance.request.is_a?(Net::HTTP::Post))
end
def test_body_is_a_json_object
instance = Messente::Omnimessage.new(@recipient, @text)
expected_body = { to: @recipient, messages: [channel: 'sms', text: @text]}.to_json
assert_equal(expected_body, instance.body)
end
def test_send_message_raises_an_error_when_answer_is_not_201
instance = Messente::Omnimessage.new(@recipient, @text)
body = {
errors: [{
code:"103",
detail: "Unauthorized",
source: nil,
title:"Unauthorized"
}]
}
response = Minitest::Mock.new
response.expect(:code, '401')
response.expect(:body, body.to_json)
http = Minitest::Mock.new
http.expect(:request, nil, [instance.request])
Net::HTTP.stub(:start, response, http) do
assert_raises(Messente::SendingError) do
instance.send_message
end
end
end
def test_send_message_returns_code_and_response_when_answer_is_201
instance = Messente::Omnimessage.new(@recipient, @text)
body = {
messages: [{
channel: 'sms',
message_id: '02a632d6-9c7c-436e-8b9c-ea3ef636724c',
sender: '+37255000002'}],
omnimessage_id: '75cbf2b6-74e8-4c75-8093-f1041587cd04',
to: '+37255000001'
}
response = Minitest::Mock.new
response.expect(:code, '201')
response.expect(:body, body.to_json)
http = Minitest::Mock.new
http.expect(:request, nil, [instance.request])
Net::HTTP.stub(:start, response, http) do
code, return_body = instance.send_message
assert_equal(code, '201')
assert_equal(body, return_body)
end
end
end
| 27.531915 | 97 | 0.697836 |
ab264607745ea8584657dd1ff2bd7425480b923e | 230 | cask "sync" do
version :latest
sha256 :no_check
url "https://www.sync.com/download/apple/Sync.dmg"
name "Sync"
desc "Store, share and access files from anywhere"
homepage "https://www.sync.com/"
app "Sync.app"
end
| 19.166667 | 52 | 0.691304 |
2193d4b911c47dd1c854d25bd7f1485fc9957956 | 351 | Puppet::Type.type(:database).provide :linux do
desc 'An example provider on Linux.'
confine kernel: 'Linux'
confine osfamily: 'RedHat'
defaultfor :kernel => 'Linux'
defaultfor :osfamily => 'RedHat', :operatingsystemmajrelease => '7'
has_feature :implements_some_feature
has_feature :some_other_feature
commands foo: '/usr/bin/foo'
end
| 31.909091 | 69 | 0.740741 |
26471d6bf5ad891a152a8777691ab94cac623d16 | 3,439 | module VCloud
# Handles creating and managing a session in vCloud Director.
class Client < BaseVCloudEntity
tag 'Session'
has_links
attribute :type, String
attribute :href, String
attribute :user, String
attribute :org, String
LOGIN = 'login'
SESSION = 'sessions'
LOGOUT_SESSION = 'session'
LOGOUT_HTTP_RESPONSE = 204
TOKEN = 'x_vcloud_authorization'.to_sym
attr_reader :api_version, :url, :token
attr_accessor :verify_ssl
# Create a new client
#
# @param [String] url API endpoint URL
# @param [VCloud::Constants::Version] api_version API version
def initialize(url, api_version, opts={})
@links=[]
@url = url.strip
@api_version = api_version
@token = {}
@logged_in = false
@verify_ssl = opts[:verify_ssl].nil? ? true : opts[:verify_ssl]
end
# Create a new session and retrieves the session token
#
# @param [String] username Username to log in with
# @param [String] password Password to log in with
# @return [Boolean] True if a session token has been generated
def login(username, password)
return true if @logged_in
url = @api_version > VCloud::Constants::Version::V0_9 ? @url + SESSION : @url + LOGIN
response = post(url, nil, nil, self, :user => username, :password => password)
parse_xml(response)
@token = { TOKEN => response.headers[TOKEN] }
@logged_in = true
return true
end
# Returns a hash of of all Org refs keyed by the Org name
#
# @return [Hash{String => VCloud::Reference}] Reference to all Orgs the user has access to, keyed by Org name
def get_org_references_by_name()
Hash[get_org_references.collect{ |i| [i.name, i] }]
end
# Returns an OrgList that contains all of the Orgs the user has access to
#
# @return [VCloud::OrgList] OrgList that contains all of the Orgs the user has access to
def get_org_references()
OrgList.from_reference(get_orglist_link, self).org_references
end
# Retrieves an Org, assuming the user has access to it
#
# @param [String] name Org name
# @return [VCloud::Org] Org object
def get_org_from_name(name)
orgs = get_org_references_by_name
ref = orgs[name] or return nil
org = Org.from_reference(ref, self)
return org
end
# Returns the Link object to retrieve an OrgList
#
# @return [VCloud::Link] Link for the OrgList
def get_orglist_link
@orglist ||= @links.select {|l| l.type == VCloud::Constants::ContentType::ORG_LIST}.first
end
# Determins if the user is logged in
#
# @return [Boolean] True if the user is logged in, otherwise false
def logged_in?
@logged_in
end
# Destroy the current session
#
# @return [Boolean] True if the session was destroyed, false if it could not be destroyed or a session does not exist
def logout
return false if not logged_in?
url = @api_version > VCloud::Constants::Version::V0_9 ? @url + LOGOUT_SESSION : @url + LOGIN
begin
delete(url, nil, nil, self)
rescue => error
if error.instance_of? VCloud::VCloudError
raise error
else
return false
end
end
@token = nil
@logged_in = false
return true
end
end
end | 29.393162 | 121 | 0.633324 |
edba738930eafb0fd259e1fa74da4fc053c3064f | 1,296 | require 'test_helper'
class UsersEditTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
end
test "unsuccessful edit" do
log_in_as(@user)
get edit_user_path(@user)
assert_template 'users/edit'
patch user_path(@user), params: { user: { name: "",
email: "foo@invalid",
password: "foo",
password_confirmation: "bar" } }
assert_template 'users/edit'
assert_select "div.alert", text: "The form contains 4 errors."
end
test "successful edit with friendly forwarding" do
get edit_user_path(@user)
log_in_as(@user)
assert_redirected_to edit_user_url(@user)
name = "Foo Bar"
email = "foo@bar.com"
patch user_path(@user), params: { user: { name: name,
email: email,
password: "",
password_confirmation: "" } }
assert_not flash.empty?
assert_redirected_to @user
@user.reload
assert_equal name, @user.name
assert_equal email, @user.email
log_in_as(@user)
assert_redirected_to user_url(@user)
end
end
| 30.857143 | 78 | 0.536265 |
3833eed74a54d6ff5cc04a2b4a0231def7a03be6 | 1,021 | #
# Symfony defaults
#
set :symfony_env, "prod"
# symfony-standard edition top-level directories
set :bin_path, "bin"
set :config_path, "config"
set :var_path, "var"
set :web_path, "public"
# Use closures for directories nested under the top level dirs, so that
# any changes to web/app etc do not require these to be changed also
set :log_path, -> { fetch(:var_path) + "/log" }
set :cache_path, -> { fetch(:var_path) + "/cache" }
# console
set :symfony_console_path, -> { fetch(:bin_path) + "/console" }
set :symfony_console_flags, "--no-debug"
# assets
set :assets_install_path, fetch(:web_path)
set :assets_install_flags, '--symlink'
#
# Capistrano defaults
#
set :linked_files, -> { [".env"] }
set :linked_dirs, -> { [fetch(:log_path)] }
#
# Configure capistrano/file-permissions defaults
#
set :file_permissions_paths, -> { [fetch(:var_path)] }
# Method used to set permissions (:chmod, :acl, or :chown)
set :permission_method, false
# Role filtering
set :symfony_roles, :all
set :symfony_deploy_roles, :all | 25.525 | 71 | 0.711068 |
e9a18d51659a29ba2828200ee7782316f7ae5f78 | 328 | # frozen_string_literal: true
module Canary
module Types
module Scalars
class DateTime < Canary::Types::Scalars::Base
def self.coerce_input(value, _ctx)
Time.zone.parse(value)
end
def self.coerce_result(value, _ctx)
value.iso8601
end
end
end
end
end
| 18.222222 | 51 | 0.612805 |
b91dcb0567afda2a978dac21cda3149995251195 | 15 | require 'gosu'
| 7.5 | 14 | 0.733333 |