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
|
---|---|---|---|---|---|
bb247574a4dcdb32c6873be12a33289f2ace48e1 | 441 | require 'spec_helper'
describe Quota do
it_behaves_like 'a resource'
let(:json) do
{
:uuid => '11111111-2222-3333-4444-555555555555',
:internal_id => 1,
:quota_limit => 2,
:request_type => 'request type',
:project_internal_id => 3,
:project_uuid => '22222222-3333-4444-5555-666666666666',
:project_name => 'project name'
}
end
end
| 24.5 | 69 | 0.548753 |
1c311fea0fb654c13e8d3a052bff94fe621a9fb4 | 1,471 | # Copyright (C) 2014-2019 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Mongo
module ChangeStreams
class Operation
# The operation name.
#
# @return [ String ] name The operation name.
#
# @since 2.6.0
attr_reader :name
# Instantiate the operation.
#
# @return [ Hash ] spec The operation spec.
#
# @since 2.6.0
def initialize(spec)
@spec = spec
@name = spec['name']
end
def execute(db1, db2)
db = case @spec['database']
when db1.name
db1
when db2.name
db2
end
send(Utils.underscore(@spec['name']) ,db[@spec['collection']])
end
private
def insert_one(coll)
coll.insert_one(document)
end
def arguments
@spec['arguments']
end
def document
arguments['document']
end
end
end
end | 23.725806 | 74 | 0.603671 |
79853079a798c1532a1004860500ab981cc66d80 | 794 | # frozen_string_literal: true
module Types
module Vulnerability
class ExternalIssueLinkType < BaseObject
graphql_name 'VulnerabilityExternalIssueLink'
description 'Represents an external issue link of a vulnerability'
authorize :read_security_resource
field :id, GlobalIDType[::Vulnerabilities::ExternalIssueLink], null: false,
description: 'GraphQL ID of the external issue link.'
field :link_type, ::Types::Vulnerability::ExternalIssueLinkTypeEnum, null: false,
description: 'Type of the external issue link.'
field :external_issue, ::Types::ExternalIssueType, null: true,
description: 'The external issue attached to the issue link.',
resolver: Resolvers::ExternalIssueResolver
end
end
end
| 34.521739 | 87 | 0.717884 |
610430dfaecec4ddf86cc35e9cc64530447f41d7 | 670 | class DocsController < ApplicationController
before_action :find_doc, only: [:show, :edit, :update, :destroy]
def index
@docs = Doc.where(user_id: current_user)
end
def show
end
def new
@doc = current_user.docs.build
end
def create
@doc = current_user.docs.build(doc_params)
if @doc.save
redirect_to @doc
else
render 'new'
end
end
def edit
end
def update
if @doc.update(doc_params)
redirect_to @doc
else
render 'edit'
end
end
def destroy
@doc.destroy
redirect_to docs_path
end
private
def find_doc
@doc = Doc.find(params[:id])
end
def doc_params
params.require(:doc).permit(:title, :content)
end
end
| 12.884615 | 65 | 0.69403 |
e92b4f608a96c2e55ce1b940d24696ffc95d9401 | 188 | require 'test_helper'
class DashboardControllerTest < ActionDispatch::IntegrationTest
test "should get welcome" do
get dashboard_welcome_url
assert_response :success
end
end
| 18.8 | 63 | 0.792553 |
9187ff6cc4667ce1374cd2a63fbbc4dd51975e2c | 421 | class Show < ActiveRecord::Base
has_and_belongs_to_many :fans
has_many :memories
belongs_to :year
def date_slug
self[:date].split(" ")[1].split("/").join("-")
end
def self.find_by_slug(slug)
self.all.find {|f| f.date_slug == slug}
end
def self.in_year_of(year)
self.all.select {|s| s[:date].split(" ")[1].split("/").last.to_i == year.value}
end
end | 22.157895 | 87 | 0.584323 |
5d85f1e5c21f21d963f468d04754ac8a907c5ca3 | 1,851 | require 'spec_helper'
describe 'cinder::api' do
let :req_params do
{:keystone_password => 'foo'}
end
let :facts do
{:osfamily => 'Debian'}
end
describe 'with only required params' do
let :params do
req_params
end
it 'should configure cinder api correctly' do
should contain_cinder_config('DEFAULT/auth_strategy').with(
:value => 'keystone'
)
should contain_cinder_config('DEFAULT/bind_host').with(
:value => '0.0.0.0'
)
should contain_cinder_api_paste_ini('filter:authtoken/service_protocol').with(
:value => 'http'
)
should contain_cinder_api_paste_ini('filter:authtoken/service_host').with(
:value => 'localhost'
)
should contain_cinder_api_paste_ini('filter:authtoken/service_port').with(
:value => '5000'
)
should contain_cinder_api_paste_ini('filter:authtoken/auth_protocol').with(
:value => 'http'
)
should contain_cinder_api_paste_ini('filter:authtoken/auth_host').with(
:value => 'localhost'
)
should contain_cinder_api_paste_ini('filter:authtoken/auth_port').with(
:value => '35357'
)
should contain_cinder_api_paste_ini('filter:authtoken/admin_tenant_name').with(
:value => 'services'
)
should contain_cinder_api_paste_ini('filter:authtoken/admin_user').with(
:value => 'cinder'
)
should contain_cinder_api_paste_ini('filter:authtoken/admin_password').with(
:value => 'foo'
)
end
end
describe 'with only required params' do
let :params do
req_params.merge({'bind_host' => '192.168.1.3'})
end
it 'should configure cinder api correctly' do
should contain_cinder_config('DEFAULT/bind_host').with(
:value => '192.168.1.3'
)
end
end
end
| 28.921875 | 85 | 0.643436 |
7af0f51376ac894d1d4ae4301f4ae583b9868b74 | 2,119 | # frozen_string_literal: true
module ActiveInteractor
module Context
# Find or create {Base context} classes for a given {ActiveInteractor::Base interactor}
#
# @api private
# @author Aaron Allen <hello@aaronmallen>
# @since 1.0.0
module Loader
# ActiveInteractor base classes
# @return [Array<Const>]
BASE_CLASSES = [ActiveInteractor::Base, ActiveInteractor::Organizer::Base].freeze
# The {ActiveInteractor::Context::Base} class
# @return [Const]
BASE_CONTEXT = ActiveInteractor::Context::Base
# Create a {Base context} class for a given {ActiveInteractor::Base interactor}
#
# @param context_class_name [Symbol, String] the class name of the
# {Base context} class to create
# @param interactor_class [Const] an {ActiveInteractor::Base interactor} class
# @return [Const] a class that inherits from {Base}
def self.create(context_class_name, interactor_class)
interactor_class.const_set(context_class_name.to_s.classify, Class.new(BASE_CONTEXT))
end
# Find or create a {Base context} class for a given {ActiveInteractor::Base interactor}. If a class exists
# following the pattern of `InteractorNameContext` or `InteractorName::Context` then that class will be returned
# otherwise a new class will be created with the pattern `InteractorName::Context`.
#
# @param interactor_class [Const] an {ActiveInteractor::Base interactor} class
# @return [Const] a class that inherits from {Base}
def self.find_or_create(interactor_class)
return BASE_CONTEXT if BASE_CLASSES.include?(interactor_class)
klass = possible_classes(interactor_class).first
klass || create('Context', interactor_class)
end
def self.possible_classes(interactor_class)
["#{interactor_class.name}::Context", "#{interactor_class.name}Context"]
.map(&:safe_constantize)
.compact
.reject { |klass| klass&.name&.include?('ActiveInteractor') }
end
private_class_method :possible_classes
end
end
end
| 41.54902 | 118 | 0.693723 |
1c0bc50a9500cf3b1bc42e1b87cf4d23ab5f8a20 | 597 |
Pod::Spec.new do |s|
s.name = 'RxFSPagerView'
s.version = '0.2.1'
s.summary = 'A short description of RxFSPagerView.'
s.homepage = 'https://github.com/behrad-kzm/RxFSPagerView/'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Pircate' => '[email protected]' }
s.source = { :git => 'https://github.com/behrad-kzm/RxFSPagerView.git', :tag => s.version.to_s }
s.swift_version = '5.2'
s.ios.deployment_target = '10.0'
s.source_files = 'RxFSPagerView/Classes/**/*'
s.dependency 'RxCocoa'
end
| 39.8 | 108 | 0.574539 |
7a5196eccbb68218f9b2cbddc65fe0ec4bba8471 | 796 | # frozen_string_literal: true
class CreateSpreeWalletPaymentSources < ActiveRecord::Migration[4.2]
def change
return if table_exists?(:spree_wallet_payment_sources)
create_table :spree_wallet_payment_sources do |t|
t.references(
:user,
foreign_key: { to_table: Spree.user_class.table_name },
index: true,
null: false,
)
t.references :payment_source, polymorphic: true, null: false
t.boolean :default, default: false, null: false
t.timestamps null: false, precision: 6
end
add_index(
:spree_wallet_payment_sources,
[:user_id, :payment_source_id, :payment_source_type],
unique: true,
name: 'index_spree_wallet_payment_sources_on_source_and_user',
)
end
end
| 28.428571 | 69 | 0.668342 |
f871ec174954e913bfe408c755f9f0a5ba9eb2e7 | 666 | require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module ActioncableTest
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
| 33.3 | 82 | 0.767267 |
f75961f24df2c73d56e05c466f6d4964272b4012 | 328 | module MoneyS3
module Parsers
class SeznamFirem
include ParserCore::BaseParser
def firma
array_of_at(Firma, ['Firma'])
end
def to_h
hash = {}
hash[:attributes] = attributes
hash[:firma] = firma.map(&:to_h) if has? 'Firma'
hash
end
end
end
end | 16.4 | 56 | 0.557927 |
b9f64d060d6e87610042a6592b5cc01b663305a8 | 1,538 | Pod::Spec.new do |s|
s.name = "ReactiveObjCBridge"
s.version = "6.0.0"
s.summary = "Bridge between ReactiveObjC and ReactiveSwift"
s.description = <<-DESC
After the announcement of Swift, ReactiveCocoa was rewritten in Swift. This framework creates a bridge between those Swift and Objective-C APIs (now known as ReactiveSwift and ReactiveObjC respectively).
Because the APIs are based on fundamentally different designs, the conversion is not always one-to-one; however, every attempt has been made to faithfully translate the concepts between the two APIs (and languages).
DESC
s.homepage = "https://github.com/ReactiveCocoa/ReactiveObjCBridge"
s.license = { :type => "MIT", :file => "LICENSE.md" }
s.author = "ReactiveCocoa"
s.osx.deployment_target = "10.9"
s.ios.deployment_target = "8.0"
s.tvos.deployment_target = "9.0"
s.watchos.deployment_target = "2.0"
s.source = { :git => "https://github.com/ReactiveCocoa/ReactiveObjCBridge.git", :tag => "#{s.version}" }
s.source_files = "ReactiveObjCBridge/*.{swift,h,m}"
s.private_header_files = 'ReactiveObjCBridge/RACScheduler+SwiftSupport.h'
s.module_map = 'ReactiveObjCBridge/module.modulemap'
s.dependency 'ReactiveObjC', '~> 3.1'
s.dependency 'ReactiveSwift', '~> 6.1'
s.pod_target_xcconfig = { "OTHER_SWIFT_FLAGS[config=Release]" => "$(inherited) -suppress-warnings" }
s.cocoapods_version = ">= 1.6.0"
s.swift_versions = ["5.0", "5.1"]
end
| 48.0625 | 234 | 0.680104 |
f7dea616bb3600b6ebf5c35b6eb52f4728807eb0 | 188 | # frozen_string_literal: true
$LOAD_PATH.unshift File.expand_path('../lib', __dir__)
require 'simplecov'
SimpleCov.start 'test_frameworks'
require 'adam6050'
require 'minitest/autorun'
| 18.8 | 54 | 0.787234 |
f7c0a23e504731828b251bce37068e889c1d1298 | 34,009 | # 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.
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module SecuritycenterV1
class Asset
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class AssetDiscoveryConfig
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class AuditConfig
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class AuditLogConfig
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Binding
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Cve
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Cvssv3
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Empty
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Expr
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Finding
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Folder
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GetIamPolicyRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GetPolicyOptions
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSecuritycenterV1NotificationMessage
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSecuritycenterV1Resource
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSecuritycenterV1RunAssetDiscoveryResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSecuritycenterV1beta1RunAssetDiscoveryResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSecuritycenterV1p1beta1Finding
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSecuritycenterV1p1beta1Folder
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSecuritycenterV1p1beta1NotificationMessage
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSecuritycenterV1p1beta1Resource
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSecuritycenterV1p1beta1RunAssetDiscoveryResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GoogleCloudSecuritycenterV1p1beta1SecurityMarks
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GroupAssetsRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GroupAssetsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GroupFindingsRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GroupFindingsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GroupResult
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class IamPolicy
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Indicator
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListAssetsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListAssetsResult
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListFindingsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListFindingsResult
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListNotificationConfigsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListOperationsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListSourcesResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class NotificationConfig
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Operation
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class OrganizationSettings
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Policy
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Reference
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Resource
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class RunAssetDiscoveryRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class SecurityCenterProperties
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class SecurityMarks
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class SetFindingStateRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class SetIamPolicyRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Source
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Status
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class StreamingConfig
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class TestIamPermissionsRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class TestIamPermissionsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Vulnerability
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Asset
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :canonical_name, as: 'canonicalName'
property :create_time, as: 'createTime'
property :iam_policy, as: 'iamPolicy', class: Google::Apis::SecuritycenterV1::IamPolicy, decorator: Google::Apis::SecuritycenterV1::IamPolicy::Representation
property :name, as: 'name'
hash :resource_properties, as: 'resourceProperties'
property :security_center_properties, as: 'securityCenterProperties', class: Google::Apis::SecuritycenterV1::SecurityCenterProperties, decorator: Google::Apis::SecuritycenterV1::SecurityCenterProperties::Representation
property :security_marks, as: 'securityMarks', class: Google::Apis::SecuritycenterV1::SecurityMarks, decorator: Google::Apis::SecuritycenterV1::SecurityMarks::Representation
property :update_time, as: 'updateTime'
end
end
class AssetDiscoveryConfig
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :folder_ids, as: 'folderIds'
property :inclusion_mode, as: 'inclusionMode'
collection :project_ids, as: 'projectIds'
end
end
class AuditConfig
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :audit_log_configs, as: 'auditLogConfigs', class: Google::Apis::SecuritycenterV1::AuditLogConfig, decorator: Google::Apis::SecuritycenterV1::AuditLogConfig::Representation
property :service, as: 'service'
end
end
class AuditLogConfig
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :exempted_members, as: 'exemptedMembers'
property :log_type, as: 'logType'
end
end
class Binding
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :condition, as: 'condition', class: Google::Apis::SecuritycenterV1::Expr, decorator: Google::Apis::SecuritycenterV1::Expr::Representation
collection :members, as: 'members'
property :role, as: 'role'
end
end
class Cve
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :cvssv3, as: 'cvssv3', class: Google::Apis::SecuritycenterV1::Cvssv3, decorator: Google::Apis::SecuritycenterV1::Cvssv3::Representation
property :id, as: 'id'
collection :references, as: 'references', class: Google::Apis::SecuritycenterV1::Reference, decorator: Google::Apis::SecuritycenterV1::Reference::Representation
end
end
class Cvssv3
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :attack_complexity, as: 'attackComplexity'
property :attack_vector, as: 'attackVector'
property :availability_impact, as: 'availabilityImpact'
property :base_score, as: 'baseScore'
property :confidentiality_impact, as: 'confidentialityImpact'
property :integrity_impact, as: 'integrityImpact'
property :privileges_required, as: 'privilegesRequired'
property :scope, as: 'scope'
property :user_interaction, as: 'userInteraction'
end
end
class Empty
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class Expr
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :description, as: 'description'
property :expression, as: 'expression'
property :location, as: 'location'
property :title, as: 'title'
end
end
class Finding
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :canonical_name, as: 'canonicalName'
property :category, as: 'category'
property :create_time, as: 'createTime'
property :event_time, as: 'eventTime'
property :external_uri, as: 'externalUri'
property :finding_class, as: 'findingClass'
property :indicator, as: 'indicator', class: Google::Apis::SecuritycenterV1::Indicator, decorator: Google::Apis::SecuritycenterV1::Indicator::Representation
property :name, as: 'name'
property :parent, as: 'parent'
property :resource_name, as: 'resourceName'
property :security_marks, as: 'securityMarks', class: Google::Apis::SecuritycenterV1::SecurityMarks, decorator: Google::Apis::SecuritycenterV1::SecurityMarks::Representation
property :severity, as: 'severity'
hash :source_properties, as: 'sourceProperties'
property :state, as: 'state'
property :vulnerability, as: 'vulnerability', class: Google::Apis::SecuritycenterV1::Vulnerability, decorator: Google::Apis::SecuritycenterV1::Vulnerability::Representation
end
end
class Folder
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :resource_folder, as: 'resourceFolder'
property :resource_folder_display_name, as: 'resourceFolderDisplayName'
end
end
class GetIamPolicyRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :options, as: 'options', class: Google::Apis::SecuritycenterV1::GetPolicyOptions, decorator: Google::Apis::SecuritycenterV1::GetPolicyOptions::Representation
end
end
class GetPolicyOptions
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :requested_policy_version, as: 'requestedPolicyVersion'
end
end
class GoogleCloudSecuritycenterV1NotificationMessage
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :finding, as: 'finding', class: Google::Apis::SecuritycenterV1::Finding, decorator: Google::Apis::SecuritycenterV1::Finding::Representation
property :notification_config_name, as: 'notificationConfigName'
property :resource, as: 'resource', class: Google::Apis::SecuritycenterV1::GoogleCloudSecuritycenterV1Resource, decorator: Google::Apis::SecuritycenterV1::GoogleCloudSecuritycenterV1Resource::Representation
end
end
class GoogleCloudSecuritycenterV1Resource
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :display_name, as: 'displayName'
collection :folders, as: 'folders', class: Google::Apis::SecuritycenterV1::Folder, decorator: Google::Apis::SecuritycenterV1::Folder::Representation
property :name, as: 'name'
property :parent, as: 'parent'
property :parent_display_name, as: 'parentDisplayName'
property :project, as: 'project'
property :project_display_name, as: 'projectDisplayName'
property :type, as: 'type'
end
end
class GoogleCloudSecuritycenterV1RunAssetDiscoveryResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :duration, as: 'duration'
property :state, as: 'state'
end
end
class GoogleCloudSecuritycenterV1beta1RunAssetDiscoveryResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :duration, as: 'duration'
property :state, as: 'state'
end
end
class GoogleCloudSecuritycenterV1p1beta1Finding
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :canonical_name, as: 'canonicalName'
property :category, as: 'category'
property :create_time, as: 'createTime'
property :event_time, as: 'eventTime'
property :external_uri, as: 'externalUri'
property :name, as: 'name'
property :parent, as: 'parent'
property :resource_name, as: 'resourceName'
property :security_marks, as: 'securityMarks', class: Google::Apis::SecuritycenterV1::GoogleCloudSecuritycenterV1p1beta1SecurityMarks, decorator: Google::Apis::SecuritycenterV1::GoogleCloudSecuritycenterV1p1beta1SecurityMarks::Representation
property :severity, as: 'severity'
hash :source_properties, as: 'sourceProperties'
property :state, as: 'state'
end
end
class GoogleCloudSecuritycenterV1p1beta1Folder
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :resource_folder, as: 'resourceFolder'
property :resource_folder_display_name, as: 'resourceFolderDisplayName'
end
end
class GoogleCloudSecuritycenterV1p1beta1NotificationMessage
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :finding, as: 'finding', class: Google::Apis::SecuritycenterV1::GoogleCloudSecuritycenterV1p1beta1Finding, decorator: Google::Apis::SecuritycenterV1::GoogleCloudSecuritycenterV1p1beta1Finding::Representation
property :notification_config_name, as: 'notificationConfigName'
property :resource, as: 'resource', class: Google::Apis::SecuritycenterV1::GoogleCloudSecuritycenterV1p1beta1Resource, decorator: Google::Apis::SecuritycenterV1::GoogleCloudSecuritycenterV1p1beta1Resource::Representation
end
end
class GoogleCloudSecuritycenterV1p1beta1Resource
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :folders, as: 'folders', class: Google::Apis::SecuritycenterV1::GoogleCloudSecuritycenterV1p1beta1Folder, decorator: Google::Apis::SecuritycenterV1::GoogleCloudSecuritycenterV1p1beta1Folder::Representation
property :name, as: 'name'
property :parent, as: 'parent'
property :parent_display_name, as: 'parentDisplayName'
property :project, as: 'project'
property :project_display_name, as: 'projectDisplayName'
end
end
class GoogleCloudSecuritycenterV1p1beta1RunAssetDiscoveryResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :duration, as: 'duration'
property :state, as: 'state'
end
end
class GoogleCloudSecuritycenterV1p1beta1SecurityMarks
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :canonical_name, as: 'canonicalName'
hash :marks, as: 'marks'
property :name, as: 'name'
end
end
class GroupAssetsRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :compare_duration, as: 'compareDuration'
property :filter, as: 'filter'
property :group_by, as: 'groupBy'
property :page_size, as: 'pageSize'
property :page_token, as: 'pageToken'
property :read_time, as: 'readTime'
end
end
class GroupAssetsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :group_by_results, as: 'groupByResults', class: Google::Apis::SecuritycenterV1::GroupResult, decorator: Google::Apis::SecuritycenterV1::GroupResult::Representation
property :next_page_token, as: 'nextPageToken'
property :read_time, as: 'readTime'
property :total_size, as: 'totalSize'
end
end
class GroupFindingsRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :compare_duration, as: 'compareDuration'
property :filter, as: 'filter'
property :group_by, as: 'groupBy'
property :page_size, as: 'pageSize'
property :page_token, as: 'pageToken'
property :read_time, as: 'readTime'
end
end
class GroupFindingsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :group_by_results, as: 'groupByResults', class: Google::Apis::SecuritycenterV1::GroupResult, decorator: Google::Apis::SecuritycenterV1::GroupResult::Representation
property :next_page_token, as: 'nextPageToken'
property :read_time, as: 'readTime'
property :total_size, as: 'totalSize'
end
end
class GroupResult
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :count, :numeric_string => true, as: 'count'
hash :properties, as: 'properties'
end
end
class IamPolicy
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :policy_blob, as: 'policyBlob'
end
end
class Indicator
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :domains, as: 'domains'
collection :ip_addresses, as: 'ipAddresses'
end
end
class ListAssetsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :list_assets_results, as: 'listAssetsResults', class: Google::Apis::SecuritycenterV1::ListAssetsResult, decorator: Google::Apis::SecuritycenterV1::ListAssetsResult::Representation
property :next_page_token, as: 'nextPageToken'
property :read_time, as: 'readTime'
property :total_size, as: 'totalSize'
end
end
class ListAssetsResult
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :asset, as: 'asset', class: Google::Apis::SecuritycenterV1::Asset, decorator: Google::Apis::SecuritycenterV1::Asset::Representation
property :state_change, as: 'stateChange'
end
end
class ListFindingsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :list_findings_results, as: 'listFindingsResults', class: Google::Apis::SecuritycenterV1::ListFindingsResult, decorator: Google::Apis::SecuritycenterV1::ListFindingsResult::Representation
property :next_page_token, as: 'nextPageToken'
property :read_time, as: 'readTime'
property :total_size, as: 'totalSize'
end
end
class ListFindingsResult
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :finding, as: 'finding', class: Google::Apis::SecuritycenterV1::Finding, decorator: Google::Apis::SecuritycenterV1::Finding::Representation
property :resource, as: 'resource', class: Google::Apis::SecuritycenterV1::Resource, decorator: Google::Apis::SecuritycenterV1::Resource::Representation
property :state_change, as: 'stateChange'
end
end
class ListNotificationConfigsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :next_page_token, as: 'nextPageToken'
collection :notification_configs, as: 'notificationConfigs', class: Google::Apis::SecuritycenterV1::NotificationConfig, decorator: Google::Apis::SecuritycenterV1::NotificationConfig::Representation
end
end
class ListOperationsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :next_page_token, as: 'nextPageToken'
collection :operations, as: 'operations', class: Google::Apis::SecuritycenterV1::Operation, decorator: Google::Apis::SecuritycenterV1::Operation::Representation
end
end
class ListSourcesResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :next_page_token, as: 'nextPageToken'
collection :sources, as: 'sources', class: Google::Apis::SecuritycenterV1::Source, decorator: Google::Apis::SecuritycenterV1::Source::Representation
end
end
class NotificationConfig
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :description, as: 'description'
property :name, as: 'name'
property :pubsub_topic, as: 'pubsubTopic'
property :service_account, as: 'serviceAccount'
property :streaming_config, as: 'streamingConfig', class: Google::Apis::SecuritycenterV1::StreamingConfig, decorator: Google::Apis::SecuritycenterV1::StreamingConfig::Representation
end
end
class Operation
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :done, as: 'done'
property :error, as: 'error', class: Google::Apis::SecuritycenterV1::Status, decorator: Google::Apis::SecuritycenterV1::Status::Representation
hash :metadata, as: 'metadata'
property :name, as: 'name'
hash :response, as: 'response'
end
end
class OrganizationSettings
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :asset_discovery_config, as: 'assetDiscoveryConfig', class: Google::Apis::SecuritycenterV1::AssetDiscoveryConfig, decorator: Google::Apis::SecuritycenterV1::AssetDiscoveryConfig::Representation
property :enable_asset_discovery, as: 'enableAssetDiscovery'
property :name, as: 'name'
end
end
class Policy
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :audit_configs, as: 'auditConfigs', class: Google::Apis::SecuritycenterV1::AuditConfig, decorator: Google::Apis::SecuritycenterV1::AuditConfig::Representation
collection :bindings, as: 'bindings', class: Google::Apis::SecuritycenterV1::Binding, decorator: Google::Apis::SecuritycenterV1::Binding::Representation
property :etag, :base64 => true, as: 'etag'
property :version, as: 'version'
end
end
class Reference
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :source, as: 'source'
property :uri, as: 'uri'
end
end
class Resource
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :display_name, as: 'displayName'
collection :folders, as: 'folders', class: Google::Apis::SecuritycenterV1::Folder, decorator: Google::Apis::SecuritycenterV1::Folder::Representation
property :name, as: 'name'
property :parent_display_name, as: 'parentDisplayName'
property :parent_name, as: 'parentName'
property :project_display_name, as: 'projectDisplayName'
property :project_name, as: 'projectName'
property :type, as: 'type'
end
end
class RunAssetDiscoveryRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
end
end
class SecurityCenterProperties
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :folders, as: 'folders', class: Google::Apis::SecuritycenterV1::Folder, decorator: Google::Apis::SecuritycenterV1::Folder::Representation
property :resource_display_name, as: 'resourceDisplayName'
property :resource_name, as: 'resourceName'
collection :resource_owners, as: 'resourceOwners'
property :resource_parent, as: 'resourceParent'
property :resource_parent_display_name, as: 'resourceParentDisplayName'
property :resource_project, as: 'resourceProject'
property :resource_project_display_name, as: 'resourceProjectDisplayName'
property :resource_type, as: 'resourceType'
end
end
class SecurityMarks
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :canonical_name, as: 'canonicalName'
hash :marks, as: 'marks'
property :name, as: 'name'
end
end
class SetFindingStateRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :start_time, as: 'startTime'
property :state, as: 'state'
end
end
class SetIamPolicyRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :policy, as: 'policy', class: Google::Apis::SecuritycenterV1::Policy, decorator: Google::Apis::SecuritycenterV1::Policy::Representation
property :update_mask, as: 'updateMask'
end
end
class Source
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :canonical_name, as: 'canonicalName'
property :description, as: 'description'
property :display_name, as: 'displayName'
property :name, as: 'name'
end
end
class Status
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :code, as: 'code'
collection :details, as: 'details'
property :message, as: 'message'
end
end
class StreamingConfig
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :filter, as: 'filter'
end
end
class TestIamPermissionsRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :permissions, as: 'permissions'
end
end
class TestIamPermissionsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :permissions, as: 'permissions'
end
end
class Vulnerability
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :cve, as: 'cve', class: Google::Apis::SecuritycenterV1::Cve, decorator: Google::Apis::SecuritycenterV1::Cve::Representation
end
end
end
end
end
| 37.537528 | 251 | 0.650798 |
9137b64452282845ba42f574763bd1b58e4b1c08 | 8,381 | require File.join(File.dirname(File.expand_path(__FILE__)), "spec_helper")
Sequel.extension :pg_array, :pg_array_ops, :pg_json, :pg_json_ops
describe "Sequel::Postgres::JSONOp" do
before do
@db = Sequel.connect('mock://postgres', :quote_identifiers=>false)
@j = Sequel.pg_json_op(:j)
@jb = Sequel.pg_jsonb_op(:j)
@l = proc{|o| @db.literal(o)}
end
it "should have #[] get the element" do
@l[@j[1]].should == "(j -> 1)"
@l[@j['a']].should == "(j -> 'a')"
end
it "should have #[] accept an array" do
@l[@j[%w'a b']].should == "(j #> ARRAY['a','b'])"
@l[@j[Sequel.pg_array(%w'a b')]].should == "(j #> ARRAY['a','b'])"
@l[@j[Sequel.pg_array(:a)]].should == "(j #> a)"
end
it "should have #[] return a JSONOp" do
@l[@j[1][2]].should == "((j -> 1) -> 2)"
@l[@j[%w'a b'][2]].should == "((j #> ARRAY['a','b']) -> 2)"
end
it "should have #get be an alias to #[]" do
@l[@j.get(1)].should == "(j -> 1)"
@l[@j.get(%w'a b')].should == "(j #> ARRAY['a','b'])"
end
it "should have #get_text get the element as text" do
@l[@j.get_text(1)].should == "(j ->> 1)"
@l[@j.get_text('a')].should == "(j ->> 'a')"
end
it "should have #get_text accept an array" do
@l[@j.get_text(%w'a b')].should == "(j #>> ARRAY['a','b'])"
@l[@j.get_text(Sequel.pg_array(%w'a b'))].should == "(j #>> ARRAY['a','b'])"
@l[@j.get_text(Sequel.pg_array(:a))].should == "(j #>> a)"
end
it "should have #get_text return an SQL::StringExpression" do
@l[@j.get_text(1) + 'a'].should == "((j ->> 1) || 'a')"
@l[@j.get_text(%w'a b') + 'a'].should == "((j #>> ARRAY['a','b']) || 'a')"
end
it "should have #array_length use the json_array_length function" do
@l[@j.array_length].should == "json_array_length(j)"
@l[@jb.array_length].should == "jsonb_array_length(j)"
end
it "should have #array_length return a numeric expression" do
@l[@j.array_length & 1].should == "(json_array_length(j) & 1)"
@l[@jb.array_length & 1].should == "(jsonb_array_length(j) & 1)"
end
it "should have #each use the json_each function" do
@l[@j.each].should == "json_each(j)"
@l[@jb.each].should == "jsonb_each(j)"
end
it "should have #each_text use the json_each_text function" do
@l[@j.each_text].should == "json_each_text(j)"
@l[@jb.each_text].should == "jsonb_each_text(j)"
end
it "should have #extract use the json_extract_path function" do
@l[@j.extract('a')].should == "json_extract_path(j, 'a')"
@l[@j.extract('a', 'b')].should == "json_extract_path(j, 'a', 'b')"
@l[@jb.extract('a')].should == "jsonb_extract_path(j, 'a')"
@l[@jb.extract('a', 'b')].should == "jsonb_extract_path(j, 'a', 'b')"
end
it "should have #extract return a JSONOp" do
@l[@j.extract('a')[1]].should == "(json_extract_path(j, 'a') -> 1)"
@l[@jb.extract('a')[1]].should == "(jsonb_extract_path(j, 'a') -> 1)"
end
it "should have #extract_text use the json_extract_path_text function" do
@l[@j.extract_text('a')].should == "json_extract_path_text(j, 'a')"
@l[@j.extract_text('a', 'b')].should == "json_extract_path_text(j, 'a', 'b')"
@l[@jb.extract_text('a')].should == "jsonb_extract_path_text(j, 'a')"
@l[@jb.extract_text('a', 'b')].should == "jsonb_extract_path_text(j, 'a', 'b')"
end
it "should have #extract_text return an SQL::StringExpression" do
@l[@j.extract_text('a') + 'a'].should == "(json_extract_path_text(j, 'a') || 'a')"
@l[@jb.extract_text('a') + 'a'].should == "(jsonb_extract_path_text(j, 'a') || 'a')"
end
it "should have #keys use the json_object_keys function" do
@l[@j.keys].should == "json_object_keys(j)"
@l[@jb.keys].should == "jsonb_object_keys(j)"
end
it "should have #array_elements use the json_array_elements function" do
@l[@j.array_elements].should == "json_array_elements(j)"
@l[@jb.array_elements].should == "jsonb_array_elements(j)"
end
it "should have #array_elements use the json_array_elements_text function" do
@l[@j.array_elements_text].should == "json_array_elements_text(j)"
@l[@jb.array_elements_text].should == "jsonb_array_elements_text(j)"
end
it "should have #typeof use the json_typeof function" do
@l[@j.typeof].should == "json_typeof(j)"
@l[@jb.typeof].should == "jsonb_typeof(j)"
end
it "should have #to_record use the json_to_record function" do
@l[@j.to_record].should == "json_to_record(j)"
@l[@jb.to_record].should == "jsonb_to_record(j)"
end
it "should have #to_recordset use the json_to_recordsetfunction" do
@l[@j.to_recordset].should == "json_to_recordset(j)"
@l[@jb.to_recordset].should == "jsonb_to_recordset(j)"
end
it "should have #populate use the json_populate_record function" do
@l[@j.populate(:a)].should == "json_populate_record(a, j)"
@l[@jb.populate(:a)].should == "jsonb_populate_record(a, j)"
end
it "should have #populate_set use the json_populate_record function" do
@l[@j.populate_set(:a)].should == "json_populate_recordset(a, j)"
@l[@jb.populate_set(:a)].should == "jsonb_populate_recordset(a, j)"
end
it "#contain_all should use the ?& operator" do
@l[@jb.contain_all(:h1)].should == "(j ?& h1)"
end
it "#contain_all handle arrays" do
@l[@jb.contain_all(%w'h1')].should == "(j ?& ARRAY['h1'])"
end
it "#contain_any should use the ?| operator" do
@l[@jb.contain_any(:h1)].should == "(j ?| h1)"
end
it "#contain_any should handle arrays" do
@l[@jb.contain_any(%w'h1')].should == "(j ?| ARRAY['h1'])"
end
it "#contains should use the @> operator" do
@l[@jb.contains(:h1)].should == "(j @> h1)"
end
it "#contains should handle hashes" do
@l[@jb.contains('a'=>'b')].should == "(j @> '{\"a\":\"b\"}'::jsonb)"
end
it "#contains should handle arrays" do
@l[@jb.contains([1, 2])].should == "(j @> '[1,2]'::jsonb)"
end
it "#contained_by should use the <@ operator" do
@l[@jb.contained_by(:h1)].should == "(j <@ h1)"
end
it "#contained_by should handle hashes" do
@l[@jb.contained_by('a'=>'b')].should == "(j <@ '{\"a\":\"b\"}'::jsonb)"
end
it "#contained_by should handle arrays" do
@l[@jb.contained_by([1, 2])].should == "(j <@ '[1,2]'::jsonb)"
end
it "#has_key? and aliases should use the ? operator" do
@l[@jb.has_key?('a')].should == "(j ? 'a')"
@l[@jb.include?('a')].should == "(j ? 'a')"
end
it "#pg_json should return self" do
@j.pg_json.should equal(@j)
@jb.pg_jsonb.should equal(@jb)
end
it "Sequel.pg_json_op should return arg for JSONOp" do
Sequel.pg_json_op(@j).should equal(@j)
Sequel.pg_jsonb_op(@jb).should equal(@jb)
end
it "should be able to turn expressions into json ops using pg_json" do
@db.literal(Sequel.qualify(:b, :a).pg_json[1]).should == "(b.a -> 1)"
@db.literal(Sequel.function(:a, :b).pg_json[1]).should == "(a(b) -> 1)"
@db.literal(Sequel.qualify(:b, :a).pg_jsonb[1]).should == "(b.a -> 1)"
@db.literal(Sequel.function(:a, :b).pg_jsonb[1]).should == "(a(b) -> 1)"
end
it "should be able to turn literal strings into json ops using pg_json" do
@db.literal(Sequel.lit('a').pg_json[1]).should == "(a -> 1)"
@db.literal(Sequel.lit('a').pg_jsonb[1]).should == "(a -> 1)"
end
it "should be able to turn symbols into json ops using Sequel.pg_json_op" do
@db.literal(Sequel.pg_json_op(:a)[1]).should == "(a -> 1)"
@db.literal(Sequel.pg_jsonb_op(:a)[1]).should == "(a -> 1)"
end
it "should be able to turn symbols into json ops using Sequel.pg_json" do
@db.literal(Sequel.pg_json(:a)[1]).should == "(a -> 1)"
@db.literal(Sequel.pg_jsonb(:a)[1]).should == "(a -> 1)"
end
it "should allow transforming JSONArray instances into ArrayOp instances" do
@db.literal(Sequel.pg_json([1,2]).op[1]).should == "('[1,2]'::json -> 1)"
end
it "should allow transforming JSONHash instances into ArrayOp instances" do
@db.literal(Sequel.pg_json('a'=>1).op['a']).should == "('{\"a\":1}'::json -> 'a')"
end
it "should allow transforming JSONBArray instances into ArrayOp instances" do
@db.literal(Sequel.pg_jsonb([1,2]).op[1]).should == "('[1,2]'::jsonb -> 1)"
end
it "should allow transforming JSONBHash instances into ArrayOp instances" do
@db.literal(Sequel.pg_jsonb('a'=>1).op['a']).should == "('{\"a\":1}'::jsonb -> 'a')"
end
end
| 36.920705 | 88 | 0.611025 |
1c4a96d5717f21a6dd4706951f714ef43e390225 | 4,814 | # frozen_string_literal: true
# This file was generated by the `rails generate rspec:install` command.
# Conventionally, all specs live under a `spec` directory, which RSpec
# adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
#
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
# config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
# config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
# config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
# if config.files_to_run.one?
# # Use the documentation formatter for detailed output,
# # unless a formatter has already been configured
# # (e.g. via a command-line flag).
# config.default_formatter = "doc"
# end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
# config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
# config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
# Kernel.srand config.seed
end
| 48.626263 | 92 | 0.739094 |
1a23706fbfd4b2dc39317678c8afcd55318b59eb | 1,345 | require 'ostruct'
require_relative '../lib/ruby_hid.rb'
class Cursor < OpenStruct
def draw
puts `clear`
out = "+#{'-'*max_x}+\n"
max_y.times do |row|
out << '|'
max_x.times do |column|
if y.to_i == row and x.to_i == column
out << '#'
else
out << ' '
end
end
out << "|\n"
end
out << "+#{'-'*max_x}+\n"
puts out
end
end
@cursor = Cursor.new(
:speed => 2,
:x => 5.0, :x_speed => 0.0,
:y => 5.0, :y_speed => 0.0,
:max_x => 40, :max_y => 15
)
axis = RubyHid::Axis.find_by_name(:left_y)
axis.add_event(
lambda do |value|
@cursor.y_speed = ((value.to_f / 255.0) - 0.5) * @cursor.speed
end
)
axis = RubyHid::Axis.find_by_name(:left_x)
axis.add_event(
lambda do |value|
@cursor.x_speed = ((value.to_f / 255.0) - 0.5) * @cursor.speed
end
)
device = RubyHid::Device.new(RubyHid::Device.list[0])
device.start_watching
loop do
if (@cursor.x >= 0 and @cursor.x_speed < 0) or
(@cursor.x <= (@cursor.max_x - 1) and @cursor.x_speed > 0)
@cursor.x += @cursor.x_speed
end
if (@cursor.y >= 0 and @cursor.y_speed < 0) or
(@cursor.y <= (@cursor.max_y - 1) and @cursor.y_speed > 0)
@cursor.y += @cursor.y_speed
end
@cursor.draw
puts "x: #{@cursor.x.to_i.to_s.ljust(4)} - y: #{@cursor.y.to_i}"
sleep 0.1
end | 20.692308 | 66 | 0.561338 |
794224b06226caf130e847694ac1742ca2327f40 | 1,053 | json.cache! ['item', p] do
json.(p, :id, :application_id, :parent_id, :sku, :name, :full_name, :permalink, :full_permalink, :description, :short_description, :active, :weight, :price, :cost_price, :tax_rate_id, :created_at, :updated_at, :featured, :in_the_box, :stock_control, :default, :default_image, :final_price)
json.display_price number_to_currency p.final_price
json.option_values p.option_values do |ov|
json.(ov, :id, :application_id, :option_type, :value)
end
json.images p.attachments do |i|
json.(i, :application_id, :created_at, :file_name, :file_size, :file_type, :id, :parent_id, :parent_type, :role, :token, :updated_at)
json.(i.file, :url)
json.file i.file.as_json[:file]
end
json.product_categories p.product_categories do |pc|
json.cache! ['item', pc], expires_in: 60.minutes do
json.partial! 'shoppe/api/product_categories/item', p: pc
end
end
json.errors @errors
end
json.cache! ['item-discounts', p], expires_in: 1.hour do
json.children_discounts p.children_discounts
json.discounts p.active_discounts
end | 47.863636 | 290 | 0.74264 |
7a31536263364be4c9bd6aff75ffa14f1a5accf7 | 2,411 | class Broot < Formula
desc "New way to see and navigate directory trees"
homepage "https://dystroy.org/broot/"
url "https://github.com/Canop/broot/archive/v1.6.1.tar.gz"
sha256 "5f97d876aa554be4c67bfd161ef762425f6083da583775c13cc75bf9882f1085"
license "MIT"
head "https://github.com/Canop/broot.git"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "c92f48f3b8e4e9d7c81389263c6be05ce6976129e3582173580b2f7ea37e9758"
sha256 cellar: :any_skip_relocation, big_sur: "b26055e7a5ba7759e05d5964c7f1cafb3d57d5e2d4ee695c77dc7e764a087f36"
sha256 cellar: :any_skip_relocation, catalina: "15189da6c77fff1a516b46771b2c54400a7e570e22dc9abd853e5c9a47c443fd"
sha256 cellar: :any_skip_relocation, mojave: "e54a687ab10f4a4cec43ee6ef7b63a0273a1b38e12b92744d91c98e756e8fc3a"
sha256 cellar: :any_skip_relocation, x86_64_linux: "8992846a3f6dcb12f69c31bd5d0f6f8f80664fb17f299aad56e979ff79f1cabf" # linuxbrew-core
end
depends_on "rust" => :build
uses_from_macos "zlib"
def install
system "cargo", "install", *std_cargo_args
# Replace man page "#version" and "#date" based on logic in release.sh
inreplace "man/page" do |s|
s.gsub! "#version", version
s.gsub! "#date", time.strftime("%Y/%m/%d")
end
man1.install "man/page" => "broot.1"
# Completion scripts are generated in the crate's build directory,
# which includes a fingerprint hash. Try to locate it first
out_dir = Dir["target/release/build/broot-*/out"].first
bash_completion.install "#{out_dir}/broot.bash"
bash_completion.install "#{out_dir}/br.bash"
fish_completion.install "#{out_dir}/broot.fish"
fish_completion.install "#{out_dir}/br.fish"
zsh_completion.install "#{out_dir}/_broot"
zsh_completion.install "#{out_dir}/_br"
end
test do
on_linux do
return if ENV["HOMEBREW_GITHUB_ACTIONS"]
end
assert_match "A tree explorer and a customizable launcher", shell_output("#{bin}/broot --help 2>&1")
require "pty"
require "io/console"
PTY.spawn(bin/"broot", "--cmd", ":pt", "--color", "no", "--out", testpath/"output.txt", err: :out) do |r, w, pid|
r.winsize = [20, 80] # broot dependency termimad requires width > 2
w.write "n\r"
assert_match "New Configuration file written in", r.read
Process.wait(pid)
end
assert_equal 0, $CHILD_STATUS.exitstatus
end
end
| 40.183333 | 139 | 0.720033 |
01931c59d99bfe640a5710f287acfefc544c0bc8 | 165 | class AddStackToClaim < ActiveRecord::Migration[4.2]
def change
change_table(:claims) do |t|
t.string :stack, array: true, default: []
end
end
end
| 20.625 | 52 | 0.666667 |
18f7c3c9b17809dfee941e5ea3076193e923c6dd | 6,565 | # frozen_string_literal: true
module Alchemy
# This helpers are useful to render elements from pages.
#
# The most important helper for frontend developers is the {#render_elements} helper.
#
module ElementsHelper
include Alchemy::UrlHelper
include Alchemy::ElementsBlockHelper
# Renders elements from given page
#
# == Examples:
#
# === Render only certain elements:
#
# <header>
# <%= render_elements only: ['header', 'claim'] %>
# </header>
# <section id="content">
# <%= render_elements except: ['header', 'claim'] %>
# </section>
#
# === Render elements from global page:
#
# <footer>
# <%= render_elements from_page: 'footer' %>
# </footer>
#
# === Custom elements finder:
#
# Having a custom element finder class:
#
# class MyCustomNewsArchive
# def elements(page:)
# news_page.elements.named('news').order(created_at: :desc)
# end
#
# private
#
# def news_page
# Alchemy::Page.where(page_layout: 'news-archive')
# end
# end
#
# In your view:
#
# <div class="news-archive">
# <%= render_elements finder: MyCustomNewsArchive.new %>
# </div>
#
# @option options [Alchemy::Page|String] :from_page (@page)
# The page the elements are rendered from. You can pass a page_layout String or a {Alchemy::Page} object.
# @option options [Array<String>|String] :only
# A list of element names only to be rendered.
# @option options [Array<String>|String] :except
# A list of element names not to be rendered.
# @option options [Number] :count
# The amount of elements to be rendered (begins with first element found)
# @option options [Number] :offset
# The offset to begin loading elements from
# @option options [Boolean] :random (false)
# Randomize the output of elements
# @option options [Boolean] :reverse (false)
# Reverse the rendering order
# @option options [String] :separator
# A string that will be used to join the element partials.
# @option options [Class] :finder (Alchemy::ElementsFinder)
# A class instance that will return elements that get rendered.
# Use this for your custom element loading logic in views.
#
def render_elements(options = {})
options = {
from_page: @page,
render_format: "html",
}.update(options)
finder = options[:finder] || Alchemy::ElementsFinder.new(options)
elements = finder.elements(page: options[:from_page])
buff = []
elements.each_with_index do |element, i|
buff << render_element(element, options, i + 1)
end
buff.join(options[:separator]).html_safe
end
# This helper renders a {Alchemy::Element} view partial.
#
# A element view partial is the html snippet presented to the website visitor.
#
# The partial is located in <tt>app/views/alchemy/elements</tt>.
#
# == View partial naming
#
# The partial has to be named after the name of the element as defined in the <tt>elements.yml</tt> file.
#
# === Example
#
# Given a headline element
#
# # elements.yml
# - name: headline
# contents:
# - name: text
# type: EssenceText
#
# Then your element view partial has to be named like:
#
# app/views/alchemy/elements/_headline.html.{erb|haml|slim}
#
# === Element partials generator
#
# You can use this handy generator to let Alchemy generate the partials for you:
#
# $ rails generate alchemy:elements --skip
#
# == Usage
#
# <%= render_element(Alchemy::Element.available.named(:headline).first) %>
#
# @param [Alchemy::Element] element
# The element you want to render the view for
# @param [Hash] options
# Additional options
# @param [Number] counter
# a counter
#
# @note If the view partial is not found
# <tt>alchemy/elements/_view_not_found.html.erb</tt> gets rendered.
#
def render_element(element, options = {}, counter = 1)
if element.nil?
warning("Element is nil")
render "alchemy/elements/view_not_found", {name: "nil"}
return
end
element.store_page(@page)
render element, {
element: element,
counter: counter,
options: options,
}.merge(options.delete(:locals) || {})
rescue ActionView::MissingTemplate => e
warning(%(
Element view partial not found for #{element.name}.\n
#{e}
))
render "alchemy/elements/view_not_found", name: element.name
end
# Returns a string for the id attribute of a html element for the given element
def element_dom_id(element)
return "" if element.nil?
"#{element.name}_#{element.id}".html_safe
end
# Renders the HTML tag attributes required for preview mode.
def element_preview_code(element)
tag_builder.tag_options(element_preview_code_attributes(element))
end
# Returns a hash containing the HTML tag attributes required for preview mode.
def element_preview_code_attributes(element)
return {} unless element.present? && @preview_mode && element.page == @page
{ "data-alchemy-element" => element.id }
end
# Returns the element's tags information as a string. Parameters and options
# are equivalent to {#element_tags_attributes}.
#
# @see #element_tags_attributes
#
# @return [String]
# HTML tag attributes containing the element's tag information.
#
def element_tags(element, options = {})
tag_builder.tag_options(element_tags_attributes(element, options))
end
# Returns the element's tags information as an attribute hash.
#
# @param [Alchemy::Element] element The {Alchemy::Element} you want to render the tags from.
#
# @option options [Proc] :formatter
# ('lambda { |tags| tags.join(' ') }')
# Lambda converting array of tags to a string.
#
# @return [Hash]
# HTML tag attributes containing the element's tag information.
#
def element_tags_attributes(element, options = {})
options = {
formatter: lambda { |tags| tags.join(" ") },
}.merge(options)
return {} if !element.taggable? || element.tag_list.blank?
{ "data-element-tags" => options[:formatter].call(element.tag_list) }
end
end
end
| 31.5625 | 111 | 0.624676 |
6ac4978c6c19e8386a09b337aac2b9df2bcc71d0 | 1,282 | =begin
#Tatum API
## Authentication <!-- ReDoc-Inject: <security-definitions> -->
OpenAPI spec version: 3.9.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 3.0.31
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for Tatum::LtcTransactionAddressKMSFromAddress
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'LtcTransactionAddressKMSFromAddress' do
before do
# run before each test
@instance = Tatum::LtcTransactionAddressKMSFromAddress.new
end
after do
# run after each test
end
describe 'test an instance of LtcTransactionAddressKMSFromAddress' do
it 'should create an instance of LtcTransactionAddressKMSFromAddress' do
expect(@instance).to be_instance_of(Tatum::LtcTransactionAddressKMSFromAddress)
end
end
describe 'test attribute "address"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "signature_id"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 27.276596 | 102 | 0.75195 |
7a601edd33c57907e8e7bbb043b5d206fdbaefc4 | 1,153 | cask 'v2rayx' do
# note: "2" is not a version number, but an intrinsic part of the product name
version '0.7.8'
sha256 'b7be7a26626bf65c7f5ce2801b52a56f7cd3cbb63c1b9db83cc5bf50cb2dd09c'
url "https://github.com/Cenmrev/V2RayX/releases/download/v#{version}/V2RayX.dmg"
appcast 'https://github.com/Cenmrev/V2RayX/releases.atom',
checkpoint: '75a333b75a20cb9ada9d23b923466899e432d9c43d137ea5df0238693ad92cf1'
name 'V2RayX'
homepage 'https://github.com/Cenmrev/V2RayX'
app 'V2RayX.app'
uninstall_preflight do
set_ownership '/Library/Application Support/V2RayX'
end
uninstall delete: '/Library/Application Support/V2RayX',
launchctl: 'v2rayproject.v2rayx.v2ray-core',
script: {
executable: '/Library/Application Support/V2RayX/v2rayx_sysconf',
args: ['off'],
sudo: true,
},
signal: ['TERM', 'cenmrev.V2RayX']
zap delete: [
'~/Library/Application Support/V2RayX',
'~/Library/Preferences/cenmrev.V2RayX.plist',
]
end
| 36.03125 | 90 | 0.622723 |
61b2d6f6c545bb2f404b0a97991217acad6052dc | 686 | require 'rails/generators/active_record/model/model_generator'
module MobileWorkflow
module Generators
class ModelGenerator < ActiveRecord::Generators::ModelGenerator
source_root File.join(File.dirname(ActiveRecord::Generators::ModelGenerator.instance_method(:create_migration_file).source_location.first), "templates")
class_option :doorkeeper_oauth, type: :boolean, default: false
def create_model_file
template File.join(File.dirname(__FILE__), "templates", "model.rb.erb"), File.join('app/models', class_path, "#{file_name}.rb")
end
private
def doorkeeper_oauth?
options[:doorkeeper_oauth]
end
end
end
end
| 29.826087 | 158 | 0.734694 |
4a6a55e395958bfef866570355afad9612fa582f | 1,572 | require 'spec_helper'
describe Immutable::SortedSet do
describe '#take' do
[
[[], 10, []],
[['A'], 10, ['A']],
[%w[A B C], 0, []],
[%w[A B C], 2, %w[A B]],
].each do |values, number, expected|
context "#{number} from #{values.inspect}" do
let(:sorted_set) { SS[*values] }
it 'preserves the original' do
sorted_set.take(number)
sorted_set.should eql(SS[*values])
end
it "returns #{expected.inspect}" do
sorted_set.take(number).should eql(SS[*expected])
end
end
end
context 'when argument is at least size of receiver' do
let(:sorted_set) { SS[6, 7, 8, 9] }
it 'returns self' do
sorted_set.take(sorted_set.size).should be(sorted_set)
sorted_set.take(sorted_set.size + 1).should be(sorted_set)
end
end
context 'when the set has a custom order' do
let(:sorted_set) { SS.new([1, 2, 3], &:-@)}
it 'maintains the custom order' do
sorted_set.take(1).to_a.should == [3]
sorted_set.take(2).to_a.should == [3, 2]
sorted_set.take(3).to_a.should == [3, 2, 1]
end
it 'keeps the comparator even when set is cleared' do
s = sorted_set.take(0)
s.add(4).add(5).add(6).to_a.should == [6, 5, 4]
end
end
context 'when called on a subclass' do
it 'should return an instance of the subclass' do
subclass = Class.new(Immutable::SortedSet)
subclass.new([1,2,3]).take(1).class.should be(subclass)
end
end
end
end
| 28.581818 | 66 | 0.568702 |
796f4c0171ff20b1645e9394d3098ac5455f7439 | 5,197 | module ActiveRecordSurvey
class Answer
module Chained
module ClassMethods
def self.extended(base)
end
end
module InstanceMethods
# Gets index relative to other chained answers
def sibling_index
if node_map = self.survey.node_maps.select { |i|
i.node == self
}.first
return node_map.ancestors_until_node_not_ancestor_of(::ActiveRecordSurvey::Node::Answer).length-1
end
return 0
end
# Chain nodes are different
# They must also see if this answer linked to subsequent answers, and re-build the link
def remove_answer(question_node)
self.survey = question_node.survey
# The node from answer from the parent question
self.survey.node_maps.reverse.select { |i|
i.node == self && !i.marked_for_destruction?
}.each { |answer_node_map|
answer_node_map.children.each { |child|
answer_node_map.parent.children << child
}
answer_node_map.send((answer_node_map.new_record?)? :destroy : :mark_for_destruction )
}
end
# Chain nodes are different - they must find the final answer node added and add to it
# They must also see if the final answer node then points somewhere else - and fix the links on that
def build_answer(question_node)
self.survey = question_node.survey
question_node_maps = self.survey.node_maps.select { |i|
i.node == question_node && !i.marked_for_destruction?
}
answer_node_maps = self.survey.node_maps.select { |i|
i.node == self && i.parent.nil? && !i.marked_for_destruction?
}.collect { |i|
i.survey = self.survey
i
}
# No node_maps exist yet from this question
if question_node_maps.length === 0
# Build our first node-map
question_node_maps << self.survey.node_maps.build(:node => question_node, :survey => self.survey)
end
last_answer_in_chain = (question_node.answers.last || question_node)
# Each instance of this question needs the answer hung from it
self.survey.node_maps.select { |i|
i.node == last_answer_in_chain && !i.marked_for_destruction?
}.each_with_index { |node_map, index|
if answer_node_maps[index]
new_node_map = answer_node_maps[index]
else
new_node_map = self.survey.node_maps.build(:node => self, :survey => self.survey)
end
# Hack - should fix this - why does self.survey.node_maps still think... yea somethigns not referenced right
#curr_children = self.survey.node_maps.select { |j|
# node_map.children.include?(j) && j != new_node_map
#}
node_map.children << new_node_map
#curr_children.each { |c|
# new_node_map.children << c
#}
}
true
end
# Moves answer down relative to other answers by swapping parent and children
def move_up
# Ensure each parent node to this node (the goal here is to hit a question node) is valid
!self.survey.node_maps.select { |i|
i.node == self
}.collect { |node_map|
# Parent must be an answer - cannot move into the position of a Question!
if !node_map.parent.nil? && node_map.parent.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer)
# I know this looks overly complicated, but we need to always work with the survey.node_maps - never children/parent of the relation
parent_node = self.survey.node_maps.select { |j|
node_map.parent == j
}.first
parent_parent = self.survey.node_maps.select { |j|
node_map.parent.parent == j
}.first
node_map.parent = parent_parent
parent_parent.children << node_map
self.survey.node_maps.select { |j|
node_map.children.include?(j)
}.each { |c|
c.parent = parent_node
parent_node.children << c
}
parent_node.parent = node_map
node_map.children << parent_node
end
}
end
# Moves answer down relative to other answers by swapping parent and children
def move_down
# Ensure each parent node to this node (the goal here is to hit a question node) is valid
!self.survey.node_maps.select { |i|
i.node == self
}.collect { |node_map|
# Must have children to move lower!
# And the children are also answers!
if node_map.children.length > 0 && !node_map.children.select { |j| j.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer) }.empty?
# I know this looks overly complicated, but we need to always work with the survey.node_maps - never children/parent of the relation
parent_node = self.survey.node_maps.select { |j|
node_map.parent == j
}.first
children = self.survey.node_maps.select { |j|
node_map.children.include?(j)
}
children_children = self.survey.node_maps.select { |j|
children.collect { |k| k.children }.flatten.include?(j)
}
children.each { |c|
parent_node.children << c
}
children.each { |c|
c.children << node_map
}
children_children.each { |i|
node_map.children << i
}
end
}
end
end
end
end
end | 32.279503 | 149 | 0.653646 |
edccda38bd400b2ce3d93f1e3de5c6af790dc828 | 1,581 | require 'test_helper'
##
# User Login test
class UserLoginTest < ActionDispatch::IntegrationTest
fixtures :users
test 'login and view default group' do
get '/login'
assert_response :success
post_via_redirect(
'/login',
user: { email: users(:jim).email, password: 'testing123' }
)
assert_nil flash[:alert]
assert_equal 'Signed in successfully.', flash[:notice]
assert_equal '/groups', path
end
test 'login and view group landing page' do
get '/login'
assert_response :success
post_via_redirect(
'/login',
user: { email: users(:sarah).email, password: 'testing123' }
)
assert_nil flash[:alert]
assert_equal 'Signed in successfully.', flash[:notice]
assert_equal '/groups', path
end
test 'login and be denied entry' do
get '/login'
assert_response :success
post_via_redirect(
'/login',
user: { email: users(:peter).email, password: 'testing123' }
)
assert_equal 'Your account is not activated yet.', flash[:alert]
assert_equal '/login', path
end
test 'login and then logout' do
get '/login'
assert_response :success
post_via_redirect(
'/login',
user: { email: users(:jim).email, password: 'testing123' }
)
assert_nil flash[:alert]
assert_equal 'Signed in successfully.', flash[:notice]
assert_equal '/groups', path
delete '/logout'
assert_equal 'Signed out successfully.', flash[:notice]
assert_equal '/logout', path
get '/groups/1'
assert_equal '/unauthenticated', path
end
end
| 23.954545 | 68 | 0.656546 |
f7cab09bdd2cdae202928ae87cfc3069fba638a2 | 2,769 |
#
# spec'ing slipdf.js
#
# Tue Nov 21 17:26:37 JST 2017
#
require 'pp'
require 'yaml'
require 'io/console'
#require 'execjs'
require 'ferrum'
module Helpers
#def run(s)
# $driver ||=
# begin
# d = Selenium::WebDriver.for :phantomjs
# #d = Selenium::WebDriver.for :chrome
# d.navigate.to('file://' + File.absolute_path('spec/test.html'))
# #d.execute_script('window._src = document.body.innerHTML;');
# d
# end
# r = $driver.execute_script(s)
# r = r.strip if r.is_a?(String)
# r = r.gsub(/\n( *)/, "\n") if r.is_a?(String)
# r
#end
#
#def js(s)
# ExecJS
# .compile(
# File.read('spec/jaabro-1.1.0.min.js') +
# File.read('src/slipdf.js') +
# File.read('spec/helpers.js'))
# .exec(s)
#end
#
def js(s)
$sources ||=
begin
%w[ spec/jaabro-1.4.0.com.js src/slipdf.js spec/helpers.js ]
.collect { |path| File.read(path) }
.join(';')
end
$browser ||=
begin
Ferrum::Browser.new(js_errors: true)
end
s = "JSON.stringify((function() { #{$sources}; #{s}; })())"
j = $browser.evaluate(s)
JSON.parse(j)
end
def print_tree(n, indent=0)
tc = "[0;90m" # tree color
sc0 = "[1;33m[4m" # string color 0
sc1 = "[0;33m" # string color 1
c1 = "[0;32m" # result 1 color
rc = "[0;0m" # reset color
rdc = "[1;31m" # red color
nc = "[0;97m" # name color
if indent == 0
n['input']['string']
.split("\n")
.each { |l| puts "#{tc} │#{sc1}#{l}#{rc}" }
end
o, l = n['offset'], n['length']
s = n['input']['string'][o..-1]
res = n['result']
r = res.to_s; r = "#{c1}#{r}#{tc}" if res == 1
mw = IO.console.winsize[1] rescue 80
na = n['name']; na = na ? "#{nc}#{na}#{tc}" : '(null)'
ind = (0..indent)
.inject('') { |ss, i|
ss +
case i % 3
when 0 then '│ '
when 1 then '· '
else '· '; end }
sio =
StringIO.new
sio <<
ind << tc << na << ' ' << r << ' ' << n['parter'] << "(#{o}, #{l})"
if res != 1
#sc0 = "[1;90m";
sc1 = "[0;90m"
end
mw = mw - sio.length - 3 - 10; mw = 0 if mw < 0
s = s[0, mw]
if l < mw
s.insert(l, sc1)
elsif l > mw
s = s + sc1 + '...'
end
s = s.gsub(/\n/, '\n')
sio <<
' >' << sc0 << s << tc << '<'
puts sio.string
n['children'].each { |c| print_tree(c, indent + 1) }
if indent == 0
il = n['input']['string'].length
tl = n['length']; tl = "#{rdc}#{tl}#{rc}" if tl != il
puts "├─ input length: #{il}"
puts "└─ tree length: #{tl}"
end
end
end
RSpec.configure { |c| c.include(Helpers) }
| 21.465116 | 73 | 0.464789 |
f8391a88cde38f2210f5ef289afbb7d33281845f | 4,393 | #
# Author:: Derek Groh (<[email protected]>)
# Copyright:: 2018, Derek Groh
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require "chef/resource"
require "chef/mixin/powershell_out"
class Chef
class Resource
class WindowsWorkgroup < Chef::Resource
resource_name :windows_workgroup
provides :windows_workgroup
include Chef::Mixin::PowershellOut
description "Use the windows_workgroup resource to join or change the workgroup of a Windows host."
introduced "14.5"
property :workgroup_name, String,
description: "The name of the workgroup for the computer.",
validation_message: "The 'workgroup_name' property must not contain spaces.",
regex: /^\S*$/, # no spaces
name_property: true
property :user, String,
description: "The local administrator user to use to change the workgroup.",
desired_state: false
property :password, String,
description: "The password for the local administrator user.",
desired_state: false
property :reboot, Symbol,
equal_to: [:immediate, :delayed, :never, :request_reboot, :reboot_now],
validation_message: "The reboot property accepts :immediate (reboot as soon as the resource completes), :delayed (reboot once the Chef run completes), and :never (Don't reboot)",
description: "Controls the system reboot behavior post workgroup joining. Reboot immediately, after the Chef run completes, or never. Note that a reboot is necessary for changes to take effect.",
default: :immediate, desired_state: false
# define this again so we can default it to true. Otherwise failures print the password
property :sensitive, [TrueClass, FalseClass],
default: true, desired_state: false
action :join do
description "Update the workgroup."
unless workgroup_member?
cmd = ""
cmd << "$pswd = ConvertTo-SecureString \'#{new_resource.password}\' -AsPlainText -Force;" if new_resource.password
cmd << "$credential = New-Object System.Management.Automation.PSCredential (\"#{new_resource.user}\",$pswd);" if new_resource.password
cmd << "Add-Computer -WorkgroupName #{new_resource.workgroup_name}"
cmd << " -Credential $credential" if new_resource.password
cmd << " -Force"
converge_by("join workstation workgroup #{new_resource.workgroup_name}") do
ps_run = powershell_out(cmd)
raise "Failed to join the workgroup #{new_resource.workgroup_name}: #{ps_run.stderr}}" if ps_run.error?
unless new_resource.reboot == :never
reboot "Reboot to join workgroup #{new_resource.workgroup_name}" do
action clarify_reboot(new_resource.reboot)
reason "Reboot to join workgroup #{new_resource.workgroup_name}"
end
end
end
end
end
action_class do
# This resource historically took `:immediate` and `:delayed` as arguments to the reboot property but then
# tried to shove that straight to the `reboot` resource which objected strenuously
def clarify_reboot(reboot_action)
case reboot_action
when :immediate
:reboot_now
when :delayed
:request_reboot
else
reboot_action
end
end
def workgroup_member?
node_workgroup = powershell_out!("(Get-WmiObject -Class Win32_ComputerSystem).Workgroup")
raise "Failed to determine if system already a member of workgroup #{new_resource.workgroup_name}" if node_workgroup.error?
node_workgroup.stdout.downcase.strip == new_resource.workgroup_name.downcase
end
end
end
end
end
| 42.240385 | 210 | 0.665377 |
ed088fd046400625aa9a45318b18cf437df08f77 | 11,816 | require_relative '../template'
require_relative '../scripts'
class Formatron
module CloudFormation
module Resources
# Generates CloudFormation template EC2 resources
# rubocop:disable Metrics/ModuleLength
module EC2
BLOCK_DEVICE_MAPPINGS = :BlockDeviceMappings
def self.vpc(cidr:)
{
Type: 'AWS::EC2::VPC',
Properties: {
CidrBlock: cidr,
EnableDnsSupport: true,
EnableDnsHostnames: true,
InstanceTenancy: 'default'
}
}
end
def self.internet_gateway
{
Type: 'AWS::EC2::InternetGateway'
}
end
def self.vpc_gateway_attachment(vpc:, gateway:)
{
Type: 'AWS::EC2::VPCGatewayAttachment',
Properties: {
InternetGatewayId: Template.ref(gateway),
VpcId: Template.ref(vpc)
}
}
end
def self.route_table(vpc:)
{
Type: 'AWS::EC2::RouteTable',
Properties: {
VpcId: Template.ref(vpc)
}
}
end
# rubocop:disable Metrics/MethodLength
def self.route(
route_table:,
instance: nil,
internet_gateway: nil,
vpc_gateway_attachment: nil
)
properties = {
RouteTableId: Template.ref(route_table),
DestinationCidrBlock: '0.0.0.0/0'
}
properties[:GatewayId] =
Template.ref internet_gateway unless internet_gateway.nil?
properties[:InstanceId] =
Template.ref instance unless instance.nil?
route = {
Type: 'AWS::EC2::Route',
Properties: properties
}
route[:DependsOn] =
vpc_gateway_attachment unless vpc_gateway_attachment.nil?
route
end
# rubocop:enable Metrics/MethodLength
# rubocop:disable Metrics/MethodLength
def self.subnet(
vpc:,
cidr:,
availability_zone:,
map_public_ip_on_launch:
)
{
Type: 'AWS::EC2::Subnet',
Properties: {
VpcId: Template.ref(vpc),
CidrBlock: cidr,
MapPublicIpOnLaunch: map_public_ip_on_launch,
AvailabilityZone: Template.join(
Template.ref('AWS::Region'),
availability_zone
)
}
}
end
# rubocop:enable Metrics/MethodLength
def self.subnet_route_table_association(route_table:, subnet:)
{
Type: 'AWS::EC2::SubnetRouteTableAssociation',
Properties: {
RouteTableId: Template.ref(route_table),
SubnetId: Template.ref(subnet)
}
}
end
def self.network_acl(vpc:)
{
Type: 'AWS::EC2::NetworkAcl',
Properties: {
VpcId: Template.ref(vpc)
}
}
end
def self.subnet_network_acl_association(subnet:, network_acl:)
{
Type: 'AWS::EC2::SubnetNetworkAclAssociation',
Properties: {
SubnetId: Template.ref(subnet),
NetworkAclId: Template.ref(network_acl)
}
}
end
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/ParameterLists
def self.network_acl_entry(
network_acl:,
cidr:,
egress:,
protocol:,
action:,
icmp_code: nil,
icmp_type: nil,
start_port: nil,
end_port: nil,
number:
)
resource = {
Type: 'AWS::EC2::NetworkAclEntry',
Properties: {
NetworkAclId: Template.ref(network_acl),
CidrBlock: cidr,
Egress: egress,
Protocol: protocol,
RuleAction: action,
RuleNumber: number
}
}
resource[:Properties][:Icmp] = {
Code: icmp_code,
Type: icmp_type
} unless icmp_code.nil?
resource[:Properties][:PortRange] = {
From: start_port,
To: end_port
} unless start_port.nil?
resource
end
# rubocop:enable Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength
# rubocop:disable Metrics/MethodLength
def self.security_group(
group_description:,
vpc:,
egress:,
ingress:
)
{
Type: 'AWS::EC2::SecurityGroup',
Properties: {
GroupDescription: group_description,
VpcId: Template.ref(vpc),
SecurityGroupEgress: egress.collect do |rule|
{
CidrIp: rule[:cidr],
IpProtocol: rule[:protocol],
FromPort: rule[:from_port],
ToPort: rule[:to_port]
}
end,
SecurityGroupIngress: ingress.collect do |rule|
{
CidrIp: rule[:cidr],
IpProtocol: rule[:protocol],
FromPort: rule[:from_port],
ToPort: rule[:to_port]
}
end
}
}
end
# rubocop:enable Metrics/MethodLength
# rubocop:disable Metrics/MethodLength
def self.security_group_egress(
security_group:,
cidr:,
protocol:,
from_port:,
to_port:
)
{
Type: 'AWS::EC2::SecurityGroupEgress',
Properties: {
GroupId: Template.ref(security_group),
CidrIp: cidr,
IpProtocol: protocol,
FromPort: from_port,
ToPort: to_port
}
}
end
# rubocop:enable Metrics/MethodLength
# rubocop:disable Metrics/MethodLength
def self.security_group_ingress(
security_group:,
cidr:,
protocol:,
from_port:,
to_port:
)
{
Type: 'AWS::EC2::SecurityGroupIngress',
Properties: {
GroupId: Template.ref(security_group),
CidrIp: cidr,
IpProtocol: protocol,
FromPort: from_port,
ToPort: to_port
}
}
end
# rubocop:enable Metrics/MethodLength
def self.block_device_mapping(device:, size:, type:, iops:)
mapping = {
DeviceName: device,
Ebs: {
VolumeSize: size
}
}
mapping[:Ebs][:VolumeType] = type unless type.nil?
mapping[:Ebs][:Iops] = iops unless iops.nil?
mapping
end
def self.volume(size:, type:, iops:, availability_zone:)
volume = {
Type: 'AWS::EC2::Volume',
Properties: {
AvailabilityZone: availability_zone,
Size: size
}
}
volume[:Properties][:VolumeType] = type unless type.nil?
volume[:Properties][:Iops] = iops unless iops.nil?
volume
end
def self.volume_attachment(device:, instance:, volume:)
{
Type: 'AWS::EC2::VolumeAttachment',
Properties: {
Device: device,
InstanceId: Template.ref(instance),
VolumeId: Template.ref(volume)
}
}
end
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/ParameterLists
# rubocop:disable Metrics/AbcSize
def self.instance(
instance_profile:,
availability_zone:,
instance_type:,
key_name:,
administrator_name:,
administrator_password:,
subnet:,
name:,
wait_condition_handle:,
security_group:,
logical_id:,
source_dest_check:,
os:,
ami:
)
ami = Template.find_in_map(
Template::REGION_MAP,
Template.ref('AWS::Region'),
os
) if ami.nil?
if os.eql? 'windows'
user_data = Template.base_64(
Template.join(
# rubocop:disable Metrics/LineLength
"<powershell>\n",
"try\n",
"{\n",
Scripts.windows_administrator(
name: administrator_name,
password: administrator_password
),
'winrm quickconfig -q', "\n",
"winrm set winrm/config/winrs '@{MaxMemoryPerShellMB=\"1024\"}'", "\n",
"winrm set winrm/config '@{MaxTimeoutms=\"1800000\"}'", "\n",
"winrm set winrm/config/service '@{AllowUnencrypted=\"true\"}'", "\n",
"winrm set winrm/config/service/auth '@{Basic=\"true\"}'", "\n",
'netsh advfirewall firewall add rule name="WinRM 5985" protocol=TCP dir=in localport=5985 action=allow', "\n",
'netsh advfirewall firewall add rule name="WinRM 5986" protocol=TCP dir=in localport=5986 action=allow', "\n",
'Stop-Service winrm', "\n",
'Set-Service winrm -startuptype "automatic"', "\n",
'Start-Service winrm', "\n",
'cfn-init.exe -v -s ', Template.ref('AWS::StackName'),
" -r #{logical_id}",
' --region ', Template.ref('AWS::Region'), "\n",
"}\n",
"catch\n",
"{\n",
'cfn-signal.exe -e 1 ',
Template.base_64(Template.ref(wait_condition_handle)), "\n",
"}\n",
'</powershell>'
# rubocop:enable Metrics/LineLength
)
)
else
user_data = Template.base_64(
Template.join(
# rubocop:disable Metrics/LineLength
"#!/bin/bash -v\n",
"apt-get -y update\n",
"apt-get -y install python-setuptools\n",
"easy_install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz\n",
"export PATH=$PATH:/opt/aws/bin\n",
'cfn-init --region ', Template.ref('AWS::Region'),
' -v -s ', Template.ref('AWS::StackName'), " -r #{logical_id}\n",
"cfn-signal -e $? -r 'Formatron instance configuration complete' '", Template.ref(wait_condition_handle), "'\n"
# rubocop:enable Metrics/LineLength
)
)
end
{
Type: 'AWS::EC2::Instance',
Properties: {
IamInstanceProfile: Template.ref(instance_profile),
AvailabilityZone: Template.join(
Template.ref('AWS::Region'),
availability_zone
),
ImageId: ami,
SourceDestCheck: source_dest_check,
InstanceType: instance_type,
KeyName: key_name,
SubnetId: Template.ref(subnet),
SecurityGroupIds: [Template.ref(security_group)],
Tags: [{
Key: 'Name',
Value: name
}],
UserData: user_data
}
}
end
# rubocop:enable Metrics/ParameterLists
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/AbcSize
end
# rubocop:enable Metrics/ModuleLength
end
end
end
| 31.259259 | 127 | 0.491029 |
e90602a88e02ab106a13382df366f58ab69216e2 | 1,401 | # frozen_string_literal: true
require_relative 'boot'
require 'rails'
# Pick the frameworks you want:
require 'active_model/railtie'
# require "active_job/railtie"
require 'active_record/railtie'
# require "active_storage/engine"
require 'action_controller/railtie'
# require "action_mailer/railtie"
# require "action_mailbox/engine"
# require "action_text/engine"
require 'action_view/railtie'
# require "action_cable/engine"
# require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module ParkingLot
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.1
# Configuration for the application, engines, and railties goes here.
#
# These settings can be overridden in specific environments using the files
# in config/environments, which are processed later.
#
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
# Only loads a smaller set of middleware suitable for API only apps.
# Middleware like session, flash, cookies can be added back manually.
# Skip views, helpers and assets when generating a new resource.
config.api_only = true
end
end
| 32.581395 | 79 | 0.756602 |
bb29d0f7719c3d7ec5dc0b39e94f08f87cba9ee6 | 2,832 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::ApiManagement::Mgmt::V2018_01_01
module Models
#
# Paged OpenIdProviders list representation.
#
class OpenIdConnectProviderCollection
include MsRestAzure
include MsRest::JSONable
# @return [Array<OpenidConnectProviderContract>] Page values.
attr_accessor :value
# @return [String] Next page link if any.
attr_accessor :next_link
# return [Proc] with next page method call.
attr_accessor :next_method
#
# Gets the rest of the items for the request, enabling auto-pagination.
#
# @return [Array<OpenidConnectProviderContract>] operation results.
#
def get_all_items
items = @value
page = self
while page.next_link != nil && !page.next_link.strip.empty? do
page = page.get_next_page
items.concat(page.value)
end
items
end
#
# Gets the next page of results.
#
# @return [OpenIdConnectProviderCollection] with next page content.
#
def get_next_page
response = @next_method.call(@next_link).value! unless @next_method.nil?
unless response.nil?
@next_link = response.body.next_link
@value = response.body.value
self
end
end
#
# Mapper for OpenIdConnectProviderCollection class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'OpenIdConnectProviderCollection',
type: {
name: 'Composite',
class_name: 'OpenIdConnectProviderCollection',
model_properties: {
value: {
client_side_validation: true,
required: false,
serialized_name: 'value',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'OpenidConnectProviderContractElementType',
type: {
name: 'Composite',
class_name: 'OpenidConnectProviderContract'
}
}
}
},
next_link: {
client_side_validation: true,
required: false,
serialized_name: 'nextLink',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 28.897959 | 82 | 0.541667 |
ff60aadd88dbbb3349d0798d059f36244a9593d3 | 5,133 | #!/opt/puppetlabs/puppet/bin/ruby
require 'json'
require 'puppet'
def custom_domains_list_by_endpoint(*args)
header_params = {}
argstring = args[0].delete('\\')
arg_hash = JSON.parse(argstring)
# Remove task name from arguments - should contain all necessary parameters for URI
arg_hash.delete('_task')
operation_verb = 'Get'
query_params, body_params, path_params = format_params(arg_hash)
uri_string = "https://management.azure.com//subscriptions/%{subscription_id}/resourceGroups/%{resource_group_name}/providers/Microsoft.Cdn/profiles/%{profile_name}/endpoints/%{endpoint_name}/customDomains" % path_params
unless query_params.empty?
uri_string = uri_string + '?' + to_query(query_params)
end
header_params['Content-Type'] = 'application/json' # first of #{parent_consumes}
return nil unless authenticate(header_params) == true
uri = URI(uri_string)
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
if operation_verb == 'Get'
req = Net::HTTP::Get.new(uri)
elsif operation_verb == 'Put'
req = Net::HTTP::Put.new(uri)
elsif operation_verb == 'Delete'
req = Net::HTTP::Delete.new(uri)
end
header_params.each { |x, v| req[x] = v } unless header_params.empty?
unless body_params.empty?
req.body=body_params.to_json
end
Puppet.debug("URI is (#{operation_verb}) #{uri} headers are #{header_params}")
response = http.request req # Net::HTTPResponse object
Puppet.debug("Called (#{operation_verb}) endpoint at #{uri}")
Puppet.debug("response code is #{response.code} and body is #{response.body}")
response
end
end
def to_query(hash)
if hash
return_value = hash.map { |x, v| "#{x}=#{v}" }.reduce { |x, v| "#{x}&#{v}" }
if !return_value.nil?
return return_value
end
end
return ''
end
def op_param(name, inquery, paramalias, namesnake)
operation_param = { :name => name, :location => inquery, :paramalias => paramalias, :namesnake => namesnake }
return operation_param
end
def format_params(key_values)
query_params = {}
body_params = {}
path_params = {}
key_values.each do |key,value|
if value.include? '{'
key_values[key]=JSON.parse(value.gsub("\'","\""))
end
end
op_params = [
op_param('api-version', 'query', 'api_version', 'api_version'),
op_param('code', 'body', 'code', 'code'),
op_param('endpointName', 'path', 'endpoint_name', 'endpoint_name'),
op_param('message', 'body', 'message', 'message'),
op_param('profileName', 'path', 'profile_name', 'profile_name'),
op_param('resourceGroupName', 'path', 'resource_group_name', 'resource_group_name'),
op_param('subscriptionId', 'path', 'subscription_id', 'subscription_id'),
]
op_params.each do |i|
location = i[:location]
name = i[:name]
paramalias = i[:paramalias]
name_snake = i[:namesnake]
if location == 'query'
query_params[name] = key_values[name_snake] unless key_values[name_snake].nil?
query_params[name] = ENV["azure__#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil?
elsif location == 'body'
body_params[name] = key_values[name_snake] unless key_values[name_snake].nil?
body_params[name] = ENV["azure_#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil?
else
path_params[name_snake.to_sym] = key_values[name_snake] unless key_values[name_snake].nil?
path_params[name_snake.to_sym] = ENV["azure__#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil?
end
end
return query_params,body_params,path_params
end
def fetch_oauth2_token
Puppet.debug('Getting oauth2 token')
@client_id = ENV['azure_client_id']
@client_secret = ENV['azure_client_secret']
@tenant_id = ENV['azure_tenant_id']
uri = URI("https://login.microsoftonline.com/#{@tenant_id}/oauth2/token")
response = Net::HTTP.post_form(uri,
'grant_type' => 'client_credentials',
'client_id' => @client_id,
'client_secret' => @client_secret,
'resource' => 'https://management.azure.com/')
Puppet.debug("get oauth2 token response code is #{response.code} and body is #{response.body}")
success = response.is_a? Net::HTTPSuccess
if success
return JSON[response.body]["access_token"]
else
raise Puppet::Error, "Unable to get oauth2 token - response is #{response} and body is #{response.body}"
end
end
def authenticate(header_params)
token = fetch_oauth2_token
if token
header_params['Authorization'] = "Bearer #{token}"
return true
else
return false
end
end
def task
# Get operation parameters from an input JSON
params = STDIN.read
result = custom_domains_list_by_endpoint(params)
if result.is_a? Net::HTTPSuccess
puts result.body
else
raise result.body
end
rescue StandardError => e
result = {}
result[:_error] = {
msg: e.message,
kind: 'puppetlabs-azure_arm/error',
details: { class: e.class.to_s },
}
puts result
exit 1
end
task | 32.694268 | 221 | 0.66803 |
03a737d66a4236ba72d0a45ea3664ea3668cf290 | 953 | class EMem < Formula
# cite Khiste_2015: "https://doi.org/10.1093/bioinformatics/btu687"
desc "Efficiently compute MEMs between large genomes"
homepage "https://www.csd.uwo.ca/~ilie/E-MEM/"
url "https://github.com/lucian-ilie/E-MEM/archive/v1.0.1.tar.gz"
sha256 "70a5a1e8b4e190d117b8629fff3493a4762708c8c0fe9eae84da918136ceafea"
license "GPL-3.0-or-later"
revision 1
bottle do
root_url "https://ghcr.io/v2/brewsci/bio"
sha256 cellar: :any_skip_relocation, catalina: "ff057c192242eb21d9392b1e616eaa579b301b90c608a49ce3a90e6d65015f79"
sha256 cellar: :any_skip_relocation, x86_64_linux: "badf5104b21d2f5d99031c6b65af178071b022d11c187f76b6ad2fe684b660bc"
end
depends_on "boost" => :build
on_macos do
depends_on "libomp"
end
def install
bin.mkpath
system "make", "BIN_DIR=#{bin}"
pkgshare.install "example"
end
test do
assert_match "Usage", shell_output("#{bin}/e-mem --help")
end
end
| 29.78125 | 121 | 0.741868 |
bf8c30b0b1fc35c1e61451b1d981292d700e3b62 | 145 | class AddKindToSettings < ActiveRecord::Migration[5.2]
def change
add_column :settings, :kind, :integer, default: 0, null: false
end
end
| 24.166667 | 66 | 0.731034 |
ff2837d80b33bbef999d4e6121aaae9d745800a0 | 684 | require 'faraday_middleware'
Dir[File.expand_path('../../faraday/*.rb', __FILE__)].each{|f| require f}
module LendingClub
# @private
module Connection
private
def connection
options = {
:headers => {
'Accept' => "application/#{format}; charset=utf-8",
'User-Agent' => user_agent,
'Authorization' => access_token
},
:url => endpoint,
}
Faraday::Connection.new(options) do |connection|
connection.request format
connection.response format
connection.adapter Faraday.default_adapter
connection.use FaradayMiddleware::RaiseHttpException
end
end
end
end
| 22.8 | 73 | 0.615497 |
f8ab97f4de7b42284e9843f9c1f257302632b3a7 | 3,064 | class QwtQt4 < Formula
desc "Qt Widgets for Technical Applications (qt4 version)"
homepage "http://qwt.sourceforge.net/"
url "https://downloads.sourceforge.net/project/qwt/qwt/6.1.3/qwt-6.1.3.tar.bz2"
sha256 "f3ecd34e72a9a2b08422fb6c8e909ca76f4ce5fa77acad7a2883b701f4309733"
revision 1
option "with-qwtmathml", "Build the qwtmathml library"
option "without-plugin", "Skip building the Qt Designer plugin"
depends_on "cartr/qt4/qt@4"
# Update designer plugin linking back to qwt framework/lib after install
# See: https://sourceforge.net/p/qwt/patches/45/
patch :DATA
def install
inreplace "qwtconfig.pri" do |s|
s.gsub! /^\s*QWT_INSTALL_PREFIX\s*=(.*)$/, "QWT_INSTALL_PREFIX=#{prefix}"
s.sub! /\+(=\s*QwtDesigner)/, "-\\1" if build.without? "plugin"
# Install Qt plugin in `lib/qt4/plugins/designer`, not `plugins/designer`.
s.sub! %r{(= \$\$\{QWT_INSTALL_PREFIX\})/(plugins/designer)$},
"\\1/lib/qt4/\\2"
end
args = ["-config", "release", "-spec"]
# On Mavericks we want to target libc++, this requires a unsupported/macx-clang-libc++ flag
if ENV.compiler == :clang && MacOS.version >= :mavericks
args << "unsupported/macx-clang-libc++"
else
args << "macx-g++"
end
if build.with? "qwtmathml"
args << "QWT_CONFIG+=QwtMathML"
prefix.install "textengines/mathml/qtmmlwidget-license"
end
system "qmake", *args
system "make"
system "make", "install"
end
def caveats
s = ""
if build.with? "qwtmathml"
s += <<~EOS
The qwtmathml library contains code of the MML Widget from the Qt solutions package.
Beside the Qwt license you also have to take care of its license:
#{opt_prefix}/qtmmlwidget-license
EOS
end
s
end
test do
(testpath/"test.cpp").write <<~EOS
#include <qwt_plot_curve.h>
int main() {
QwtPlotCurve *curve1 = new QwtPlotCurve("Curve 1");
return (curve1 == NULL);
}
EOS
system ENV.cxx, "test.cpp", "-o", "out",
"-framework", "qwt", "-framework", "QtCore",
"-F#{lib}", "-F#{Formula["cartr/qt4/qt@4"].opt_lib}",
"-I#{lib}/qwt.framework/Headers",
"-I#{Formula["cartr/qt4/qt@4"].opt_lib}/QtCore.framework/Headers",
"-I#{Formula["cartr/qt4/qt@4"].opt_lib}/QtGui.framework/Headers"
system "./out"
end
end
__END__
diff --git a/designer/designer.pro b/designer/designer.pro
index c269e9d..c2e07ae 100644
--- a/designer/designer.pro
+++ b/designer/designer.pro
@@ -126,6 +126,16 @@ contains(QWT_CONFIG, QwtDesigner) {
target.path = $${QWT_INSTALL_PLUGINS}
INSTALLS += target
+
+ macx {
+ contains(QWT_CONFIG, QwtFramework) {
+ QWT_LIB = qwt.framework/Versions/$${QWT_VER_MAJ}/qwt
+ }
+ else {
+ QWT_LIB = libqwt.$${QWT_VER_MAJ}.dylib
+ }
+ QMAKE_POST_LINK = install_name_tool -change $${QWT_LIB} $${QWT_INSTALL_LIBS}/$${QWT_LIB} $(DESTDIR)$(TARGET)
+ }
}
else {
TEMPLATE = subdirs # do nothing | 31.265306 | 117 | 0.629569 |
380430a13415fad5b69a2423f4bd13bdad471232 | 279 | class Specinfra::Helper::DetectOs::Esxi < Specinfra::Helper::DetectOs
def detect
if run_command('vmware -v').success?
line = run_command('vmware -v').stdout
if line =~ /VMware ESXi (.*)/
{ :family => 'esxi', :release => $1 }
end
end
end
end
| 25.363636 | 69 | 0.591398 |
1aa7c626047c64ac53ff67ffa3511175dca8b9d5 | 206 | PROJECT_ROOT_PATH = File.dirname(File.dirname(File.dirname(__FILE__)))
require 'middleman-core'
require 'middleman-core/step_definitions'
require File.join(PROJECT_ROOT_PATH, 'lib', 'middleman-github_api')
| 41.2 | 70 | 0.815534 |
080259579b1ea6a2ed0eee564e7205a4873679cb | 1,368 | class SimpleObfs < Formula
desc "Simple obfusacting plugin of shadowsocks-libev"
homepage "https://github.com/shadowsocks/simple-obfs"
url "https://github.com/shadowsocks/simple-obfs.git",
:tag => "v0.0.5",
:revision => "a9c43588e4cb038e6ac02f050e4cab81f8228dff"
revision 1
bottle do
cellar :any
sha256 "64ac7bb71b3dd0a0d087d7f981c53516abfb294f709d84cb969b192456310c51" => :catalina
sha256 "7d00695065a2e780f6a93d98d3d2a96ebe4c02fe48e52e30cea4fefe353100e8" => :mojave
sha256 "08024887dc9fba3f56425181dd34dba1ecf185dad688b85d20a7b70ec07afbae" => :high_sierra
sha256 "831de4a180d61c801397ead63a0130d8d2eb102afb526ef81bcecb2f9d1d029b" => :sierra
sha256 "eccfcd8d4016297999d730fd185624b42e903f7dfac43bd6227c337c2b3aafea" => :el_capitan
end
depends_on "asciidoc" => :build
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "xmlto" => :build
depends_on "libev"
def install
ENV["XML_CATALOG_FILES"] = etc/"xml/catalog"
system "./autogen.sh"
system "./configure", "--prefix=#{prefix}",
"--disable-dependency-tracking",
"--enable-applecc"
system "make"
system "make", "install"
end
test do
assert_match "simple-obfs", shell_output("#{bin}/obfs-local -h 2>&1")
end
end
| 35.076923 | 93 | 0.70614 |
081d1be93190520116064c02e4a870856b0a81f4 | 4,235 | #
# Cookbook Name:: yum
# Provider:: repository
#
# Copyright 2010, Tippr Inc.
# Copyright 2011, Opscode, Inc..
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# note that deletion does not remove GPG keys, either from the repo or
# /etc/pki/rpm-gpg; this is a design decision.
def whyrun_supported?
true
end
action :add do
unless ::File.exists?("/etc/yum.repos.d/#{new_resource.repo_name}.repo")
Chef::Log.info "Adding #{new_resource.repo_name} repository to /etc/yum.repos.d/#{new_resource.repo_name}.repo"
repo_config
end
end
action :create do
Chef::Log.info "Adding and updating #{new_resource.repo_name} repository in /etc/yum.repos.d/#{new_resource.repo_name}.repo"
repo_config
end
action :remove do
if ::File.exists?("/etc/yum.repos.d/#{new_resource.repo_name}.repo")
Chef::Log.info "Removing #{new_resource.repo_name} repository from /etc/yum.repos.d/"
file "/etc/yum.repos.d/#{new_resource.repo_name}.repo" do
action :delete
end
new_resource.updated_by_last_action(true)
end
end
action :update do
repos ||= {}
# If the repo is already enabled/disabled as per the resource, we don't want to converge the template resource.
if ::File.exists?("/etc/yum.repos.d/#{new_resource.repo_name}.repo")
::File.open("/etc/yum.repos.d/#{new_resource.repo_name}.repo") do |file|
repo_name ||= nil
file.each_line do |line|
case line
when /^\[(\S+)\]/
repo_name = $1
repos[repo_name] ||= {}
when /^(\S+?)=(.*)$/
param, value = $1, $2
repos[repo_name][param] = value
else
end
end
end
else
Chef::Log.error "Repo /etc/yum.repos.d/#{new_resource.repo_name}.repo does not exist, you must create it first"
end
if repos[new_resource.repo_name]['enabled'].to_i != new_resource.enabled
Chef::Log.info "Updating #{new_resource.repo_name} repository in /etc/yum.repos.d/#{new_resource.repo_name}.repo (setting enabled=#{new_resource.enabled})"
repo_config
else
Chef::Log.debug "Repository /etc/yum.repos.d/#{new_resource.repo_name}.repo is already set to enabled=#{new_resource.enabled}, skipping"
end
end
private
def repo_config
#import the gpg key. If it needs to be downloaded or imported from a cookbook
#that can be done in the calling recipe
if new_resource.key then
yum_key new_resource.key
end
#get the metadata
execute "yum-makecache" do
command "yum -q makecache"
action :nothing
end
#reload internal Chef yum cache
ruby_block "reload-internal-yum-cache" do
block do
Chef::Provider::Package::Yum::YumCache.instance.reload
end
action :nothing
end
#write out the file
template "/etc/yum.repos.d/#{new_resource.repo_name}.repo" do
cookbook "yum"
source "repo.erb"
mode "0644"
variables({
:repo_name => new_resource.repo_name,
:description => new_resource.description,
:url => new_resource.url,
:mirrorlist => new_resource.mirrorlist,
:key => new_resource.key,
:enabled => new_resource.enabled,
:type => new_resource.type,
:failovermethod => new_resource.failovermethod,
:bootstrapurl => new_resource.bootstrapurl,
:includepkgs => new_resource.includepkgs,
:exclude => new_resource.exclude,
:priority => new_resource.priority,
:metadata_expire => new_resource.metadata_expire
})
if new_resource.make_cache
notifies :run, "execute[yum-makecache]", :immediately
notifies :create, "ruby_block[reload-internal-yum-cache]", :immediately
end
end
end
| 33.88 | 159 | 0.670366 |
ab146fc862ad642dc601525e6f5896527b589a90 | 289 | class TeammateReviewQuestionnaire < Questionnaire
after_initialize :post_initialization
def post_initialization
self.display_type = 'Teammate Review'
end
def symbol
"teammate".to_sym
end
def get_assessments_for(participant)
participant.teammate_reviews
end
end
| 19.266667 | 49 | 0.785467 |
3818746a9b7837545a0187e8b14552a963162a54 | 5,303 | require 'spec_helper'
describe GroupsSerializer do
let(:raceteam) { threadable.organizations.find_by_slug!('raceteam') }
let(:electronics) { raceteam.groups.find_by_email_address_tag!('electronics') }
let(:fundraising) { raceteam.groups.find_by_email_address_tag!('fundraising') }
before{ sign_in_as '[email protected]' }
context 'when given a single record' do
let(:payload){ electronics }
let(:expected_key){ :group }
it do
is_expected.to eq(
id: electronics.id,
slug: "electronics",
name: "Electronics",
email_address_tag: "electronics",
subject_tag: "RaceTeam+Electronics",
alias_email_address: '',
webhook_url: '',
color: "#964bf8",
auto_join: false,
non_member_posting: "allow_replies",
description: 'Soldering and wires and stuff!',
google_sync: false,
primary: false,
private: false,
email_address: electronics.email_address,
task_email_address: electronics.task_email_address,
formatted_email_address: electronics.formatted_email_address,
formatted_task_email_address: electronics.formatted_task_email_address,
internal_email_address: electronics.internal_email_address,
internal_task_email_address: electronics.internal_task_email_address,
conversations_count: electronics.conversations.count,
members_count: electronics.members.count,
organization_slug: electronics.organization.slug,
current_user_is_a_member: false,
current_user_is_a_limited_member: false,
can_set_google_sync: true,
can_change_settings: true,
can_create_members: true,
can_delete_members: true,
)
end
end
context 'when given a collection of records' do
let(:payload){ [electronics, fundraising] }
let(:expected_key){ :groups }
it do
is_expected.to eq [
{
id: electronics.id,
slug: "electronics",
name: "Electronics",
email_address_tag: "electronics",
subject_tag: "RaceTeam+Electronics",
alias_email_address: '',
webhook_url: '',
color: "#964bf8",
auto_join: false,
non_member_posting: "allow_replies",
description: 'Soldering and wires and stuff!',
google_sync: false,
primary: false,
private: false,
email_address: electronics.email_address,
task_email_address: electronics.task_email_address,
formatted_email_address: electronics.formatted_email_address,
formatted_task_email_address: electronics.formatted_task_email_address,
internal_email_address: electronics.internal_email_address,
internal_task_email_address: electronics.internal_task_email_address,
conversations_count: electronics.conversations.count,
members_count: electronics.members.count,
organization_slug: electronics.organization.slug,
current_user_is_a_member: false,
current_user_is_a_limited_member: false,
can_set_google_sync: true,
can_change_settings: true,
can_create_members: true,
can_delete_members: true,
},{
id: fundraising.id,
slug: "fundraising",
name: "Fundraising",
email_address_tag: "fundraising",
subject_tag: "RaceTeam+Fundraising",
alias_email_address: '',
webhook_url: '',
color: "#5a9de1",
auto_join: false,
non_member_posting: "allow_replies",
description: 'Cache Monet',
google_sync: false,
primary: false,
private: false,
email_address: fundraising.email_address,
task_email_address: fundraising.task_email_address,
formatted_email_address: fundraising.formatted_email_address,
formatted_task_email_address: fundraising.formatted_task_email_address,
internal_email_address: fundraising.internal_email_address,
internal_task_email_address: fundraising.internal_task_email_address,
conversations_count: fundraising.conversations.count,
members_count: fundraising.members.count,
organization_slug: fundraising.organization.slug,
current_user_is_a_member: true,
current_user_is_a_limited_member: false,
can_set_google_sync: true,
can_change_settings: true,
can_create_members: true,
can_delete_members: true,
},
]
end
end
end
| 39.87218 | 81 | 0.583066 |
4a13997e412831019fc175b4d89275201a0dbc8c | 3,640 | # frozen_string_literal: true
class ProductForCart
include TextHelpers::Translation
attr_accessor :error_message
attr_accessor :error_path
def initialize(product)
@product = product
end
def purchasable_by?(acting_user, session_user)
raise NUCore::PermissionDenied unless product.is_accessible_to_user?(session_user)
checks(acting_user, session_user).all? do |check|
result = check.call
[error_path, error_message].all?(&:blank?) && result != false
end
end
protected
def translation_scope
"models.#{self.class.name.underscore}"
end
private
attr_accessor :product
def checks(acting_user, session_user)
[
check_that_user_is_present(acting_user),
check_that_product_is_available_for_purchase,
check_that_product_has_price_policies,
check_that_product_can_be_used(acting_user, session_user),
check_that_product_has_price_groups_accessible_to_user(acting_user),
check_that_user_has_accounts_for_product(acting_user),
check_that_session_user_can_order_on_behalf_of_assumed_user(acting_user, session_user),
]
end
def check_that_user_is_present(user)
-> { user.present? }
end
def check_that_product_is_available_for_purchase
-> { @error_message = text(".not_available", i18n_params) unless product.available_for_purchase? }
end
def check_that_product_has_price_policies
proc do
price_policies = product.is_a?(Bundle) ? product.products.flat_map(&:price_policies) : product.price_policies
@error_message = text(".pricing_not_available", i18n_params) if price_policies.none?
end
end
def check_that_product_can_be_used(acting_user, session_user)
proc do
if !product.can_be_used_by?(acting_user) && !(session_user.present? && session_user.can_override_restrictions?(product))
if SettingsHelper.feature_on?(:training_requests)
if TrainingRequest.submitted?(session_user, product)
@error_message = text("models.product_for_cart.already_requested_access", i18n_params)
@error_path = url_helpers.facility_path(product.facility)
else
@error_path = url_helpers.new_facility_product_training_request_path(product.facility, product)
end
else
@error_message = html(".requires_approval", i18n_params)
end
end
end
end
def check_that_product_has_price_groups_accessible_to_user(user)
proc do
price_group_ids = (user.price_groups + user.account_price_groups).flatten.uniq.map(&:id)
@error_message = text(".no_price_groups", i18n_params) unless product.can_purchase?(price_group_ids)
end
end
def check_that_user_has_accounts_for_product(user)
-> { @error_message = text(".no_accounts", i18n_params) if user.accounts_for_product(product).none? }
end
def check_that_session_user_can_order_on_behalf_of_assumed_user(acting_user, session_user)
proc do
if acting_as?(acting_user, session_user) && !session_user.operator_of?(product.facility)
@error_message = text(".not_authorized_to_order_on_behalf", i18n_params)
end
end
end
def i18n_params
product_type = product.class.model_name.human.downcase
{
email: product.email,
facility: product.facility,
product_name: product.name,
product_type: product_type,
product_type_plural: product_type.pluralize,
}
end
def url_helpers
Rails.application.routes.url_helpers
end
def acting_as?(acting_user, session_user)
return false if session_user.nil?
acting_user.object_id != session_user.object_id
end
end
| 31.111111 | 126 | 0.744231 |
08681c0341a70e9c0175092ec34f8aabe335972a | 5,385 | # frozen_string_literal: true
require('spec_helper')
describe ProfilesController, :request_store do
let(:user) { create(:user) }
describe 'POST update' do
it 'does not update password' do
sign_in(user)
expect do
post :update,
params: { user: { password: 'hello12345', password_confirmation: 'hello12345' } }
end.not_to change { user.reload.encrypted_password }
expect(response.status).to eq(302)
end
end
describe 'PUT update' do
it 'allows an email update from a user without an external email address' do
sign_in(user)
put :update,
params: { user: { email: "[email protected]", name: "John" } }
user.reload
expect(response.status).to eq(302)
expect(user.unconfirmed_email).to eq('[email protected]')
end
it "allows an email update without confirmation if existing verified email" do
user = create(:user)
create(:email, :confirmed, user: user, email: '[email protected]')
sign_in(user)
put :update,
params: { user: { email: "[email protected]", name: "John" } }
user.reload
expect(response.status).to eq(302)
expect(user.unconfirmed_email).to eq nil
end
it 'ignores an email update from a user with an external email address' do
stub_omniauth_setting(sync_profile_from_provider: ['ldap'])
stub_omniauth_setting(sync_profile_attributes: true)
ldap_user = create(:omniauth_user)
ldap_user.create_user_synced_attributes_metadata(provider: 'ldap', name_synced: true, email_synced: true)
sign_in(ldap_user)
put :update,
params: { user: { email: "[email protected]", name: "John" } }
ldap_user.reload
expect(response.status).to eq(302)
expect(ldap_user.unconfirmed_email).not_to eq('[email protected]')
end
it 'ignores an email and name update but allows a location update from a user with external email and name, but not external location' do
stub_omniauth_setting(sync_profile_from_provider: ['ldap'])
stub_omniauth_setting(sync_profile_attributes: true)
ldap_user = create(:omniauth_user, name: 'Alex')
ldap_user.create_user_synced_attributes_metadata(provider: 'ldap', name_synced: true, email_synced: true, location_synced: false)
sign_in(ldap_user)
put :update,
params: { user: { email: "[email protected]", name: "John", location: "City, Country" } }
ldap_user.reload
expect(response.status).to eq(302)
expect(ldap_user.unconfirmed_email).not_to eq('[email protected]')
expect(ldap_user.name).not_to eq('John')
expect(ldap_user.location).to eq('City, Country')
end
it 'allows setting a user status' do
sign_in(user)
put :update, params: { user: { status: { message: 'Working hard!' } } }
expect(user.reload.status.message).to eq('Working hard!')
expect(response).to have_gitlab_http_status(302)
end
end
describe 'PUT update_username' do
let(:namespace) { user.namespace }
let(:gitlab_shell) { Gitlab::Shell.new }
let(:new_username) { generate(:username) }
it 'allows username change' do
sign_in(user)
put :update_username,
params: { user: { username: new_username } }
user.reload
expect(response.status).to eq(302)
expect(user.username).to eq(new_username)
end
it 'updates a username using JSON request' do
sign_in(user)
put :update_username,
params: {
user: { username: new_username }
},
format: :json
expect(response.status).to eq(200)
expect(json_response['message']).to eq('Username successfully changed')
end
it 'renders an error message when the username was not updated' do
sign_in(user)
put :update_username,
params: {
user: { username: 'invalid username.git' }
},
format: :json
expect(response.status).to eq(422)
expect(json_response['message']).to match(/Username change failed/)
end
it 'raises a correct error when the username is missing' do
sign_in(user)
expect { put :update_username, params: { user: { gandalf: 'you shall not pass' } } }
.to raise_error(ActionController::ParameterMissing)
end
context 'with legacy storage' do
it 'moves dependent projects to new namespace' do
project = create(:project_empty_repo, :legacy_storage, namespace: namespace)
sign_in(user)
put :update_username,
params: { user: { username: new_username } }
user.reload
expect(response.status).to eq(302)
expect(gitlab_shell.exists?(project.repository_storage, "#{new_username}/#{project.path}.git")).to be_truthy
end
end
context 'with hashed storage' do
it 'keeps repository location unchanged on disk' do
project = create(:project_empty_repo, namespace: namespace)
before_disk_path = project.disk_path
sign_in(user)
put :update_username,
params: { user: { username: new_username } }
user.reload
expect(response.status).to eq(302)
expect(gitlab_shell.exists?(project.repository_storage, "#{project.disk_path}.git")).to be_truthy
expect(before_disk_path).to eq(project.disk_path)
end
end
end
end
| 29.916667 | 141 | 0.653296 |
6a55b6c3fc8bc3bb92cc31da4c40fb1458af9388 | 290 | =begin
author : Jagepard <[email protected]>
license https://mit-license.org/ MIT
=end
class Iterator
def initialize(bucket)
@bucket = bucket
end
def iterate_items
@bucket.each { |item|
puts item.name + ' ' + item.price.to_s + ' ' + item.description
}
end
end
| 17.058824 | 69 | 0.651724 |
ab836934a5172d0885fff2552afd1a861a4e139b | 2,390 | class CfrDecompiler < Formula
desc "Yet Another Java Decompiler"
homepage "https://www.benf.org/other/cfr/"
url "https://github.com/leibnitz27/cfr.git",
:tag => "0.150",
:revision => "1361cd7fa74f25f30a6bbf72c825d83647d2cdaf"
head "https://github.com/leibnitz27/cfr.git"
bottle do
cellar :any_skip_relocation
sha256 "05d1bff6093077a4f9789606c7b8d77d26f66f341aa491a9412da3e85669c932" => :catalina
sha256 "0235b4a3204736079b3790db8de5bb02f99162318bff390aea45168f2bd1ea48" => :mojave
sha256 "c6866f8e6b6c8e849936d2b5a45c3827dda9acacfe49ca2e831041e633617ac5" => :high_sierra
end
depends_on "maven" => :build
depends_on "openjdk"
def install
# Homebrew's OpenJDK no longer accepts Java 6 source, so:
inreplace "pom.xml", "<javaVersion>1.6</javaVersion>", "<javaVersion>1.7</javaVersion>"
inreplace "cfr.iml", 'LANGUAGE_LEVEL="JDK_1_6"', 'LANGUAGE_LEVEL="JDK_1_7"'
# build
ENV["JAVA_HOME"] = Formula["openjdk"].opt_prefix
system Formula["maven"].bin/"mvn", "package"
cd "target" do
# switch on jar names
if build.head?
lib_jar = Dir["cfr-*-SNAPSHOT.jar"]
doc_jar = Dir["cfr-*-SNAPSHOT-javadoc.jar"]
odie "Unexpected number of artifacts!" unless (lib_jar.length == 1) && (doc_jar.length == 1)
lib_jar = lib_jar[0]
doc_jar = doc_jar[0]
else
lib_jar = "cfr-#{version}.jar"
doc_jar = "cfr-#{version}-javadoc.jar"
end
# install library and binary
libexec.install lib_jar
(bin/"cfr-decompiler").write <<~EOS
#!/bin/bash
export JAVA_HOME="${JAVA_HOME:-#{Formula["openjdk"].opt_prefix}}"
exec "${JAVA_HOME}/bin/java" -jar "#{libexec/lib_jar}" "$@"
EOS
# install library docs
doc.install doc_jar
mkdir doc/"javadoc"
cd doc/"javadoc" do
system Formula["openjdk"].bin/"jar", "-xf", doc/doc_jar
rm_rf "META-INF"
end
end
end
test do
fixture = <<~EOS
class T {
T() {
}
public static void main(String[] arrstring) {
System.out.println("Hello brew!");
}
}
EOS
(testpath/"T.java").write fixture
system Formula["openjdk"].bin/"javac", "T.java"
output = pipe_output("#{bin}/cfr-decompiler --comments false T.class")
assert_match fixture, output
end
end
| 31.447368 | 100 | 0.633473 |
7ac91c10c377cbb28874f13b7d54c4062d6a4f7f | 3,392 | require 'rails_helper'
describe Address do
subject { build(:address) }
it { is_expected.to be_valid }
it { is_expected.to belong_to(:location).optional.touch(true) }
it { is_expected.to validate_presence_of(:address_1).with_message("can't be blank for Address") }
it { is_expected.to validate_presence_of(:city).with_message("can't be blank for Address") }
it do
expect(subject).to validate_presence_of(:state_province).
with_message(t('errors.messages.invalid_state_province'))
end
it do
expect(subject).to validate_presence_of(:postal_code).with_message("can't be blank for Address")
end
it { is_expected.to validate_presence_of(:country).with_message("can't be blank for Address") }
it do
expect(subject).to validate_length_of(:country).
is_at_least(2).
is_at_most(2).
with_short_message('is too short (minimum is 2 characters)').
with_long_message('is too long (maximum is 2 characters)')
end
it { is_expected.to allow_value('90210-1234', '22045').for(:postal_code) }
it do
expect(subject).not_to allow_value('asdf').for(:postal_code).
with_message('asdf is not a valid ZIP code')
end
it { is_expected.not_to allow_value('1234').for(:postal_code) }
it { is_expected.not_to allow_value('123456').for(:postal_code) }
it { is_expected.not_to allow_value('12346-689').for(:postal_code) }
it { is_expected.not_to allow_value('90210-90210').for(:postal_code) }
it { is_expected.not_to allow_value('90 210').for(:postal_code) }
describe 'auto_strip_attributes' do
it 'strips extra whitespace before validation' do
address = build(:address_with_extra_whitespace)
address.valid?
expect(address.address_1).to eq('8875 La Honda Road')
expect(address.city).to eq('La Honda')
expect(address.state_province).to eq('CA')
expect(address.postal_code).to eq('94020')
expect(address.country).to eq('US')
end
end
describe 'callbacks' do
before { @loc = create(:location) }
it 'calls reset_location_coordinates after destroy' do
expect(@loc.address).to receive(:reset_location_coordinates)
@loc.address.destroy
end
end
describe 'state_province validations' do
context 'when country is US' do
it 'validates length is 2 characters' do
address = build(:address, country: 'US', state_province: 'California')
address.save
expect(address.errors[:state_province].first).
to eq t('errors.messages.invalid_state_province')
end
end
context 'when country is CA' do
it 'validates length is 2 characters' do
address = build(:address, country: 'CA', state_province: 'Ontario')
address.save
expect(address.errors[:state_province].first).
to eq t('errors.messages.invalid_state_province')
end
end
context 'when country is not CA or US' do
it 'does not validate length' do
address = build(:address, country: 'UK', state_province: 'Kent')
address.save
expect(address.errors[:state_province]).to be_empty
end
end
context 'when country is not CA or US' do
it 'does not validate presence' do
address = build(:address, country: 'ES', state_province: '')
address.save
expect(address.errors[:state_province]).to be_empty
end
end
end
end
| 32 | 100 | 0.685436 |
114ed456b7e11fdbf8c0344fff9ce0d7f7dd4361 | 378 | module Textris
module Delay
module Sidekiq
module Missing
def sidekiq_missing(*args)
raise(LoadError, "Sidekiq is required to delay sending messages")
end
alias_method :delay, :sidekiq_missing
alias_method :delay_for, :sidekiq_missing
alias_method :delay_until, :sidekiq_missing
end
end
end
end
| 23.625 | 75 | 0.650794 |
6219b9f85d061bf4d4ba88051ffaabb0049f9721 | 1,754 | require 'stringio'
module Aws
module Query
class ParamList
include Enumerable
# @api private
def initialize
@params = {}
end
# @param [String] param_name
# @param [String, nil] param_value
# @return [Param]
def set(param_name, param_value = nil)
param = Param.new(param_name, param_value)
@params[param.name] = param
param
end
alias []= set
# @return [Param, nil]
def [](param_name)
@params[param_name.to_s]
end
# @param [String] param_name
# @return [Param, nil]
def delete(param_name)
@params.delete(param_name)
end
# @return [Enumerable]
def each(&block)
to_a.each(&block)
end
# @return [Boolean]
def empty?
@params.empty?
end
# @return [Array<Param>] Returns an array of sorted {Param} objects.
def to_a
@params.values.sort
end
# @return [String]
def to_s
to_a.map(&:to_s).join('&')
end
# @return [#read, #rewind, #size]
def to_io
IoWrapper.new(self)
end
# @api private
class IoWrapper
# @param [ParamList] param_list
def initialize(param_list)
@param_list = param_list
@io = StringIO.new(param_list.to_s)
end
# @return [ParamList]
attr_reader :param_list
# @return [Integer]
def size
@io.size
end
# @return [void]
def rewind
@io.rewind
end
# @return [String, nil]
def read(bytes = nil, output_buffer = nil)
@io.read(bytes, output_buffer)
end
end
end
end
end
| 19.065217 | 74 | 0.526796 |
03d3f31bfd1ba0dc70abe648019f929ceda8913f | 23,025 | # ------------------------------------------------------------------------------------
# <copyright company="Aspose" file="jpeg_save_options_data.rb">
# Copyright (c) 2021 Aspose.Words for Cloud
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# </summary>
# ------------------------------------------------------------------------------------
require 'date'
module AsposeWordsCloud
# Container class for jpeg save options.
class JpegSaveOptionsData
# Gets or sets a boolean value indicating whether to allow embedding fonts with PostScript outlines when embedding TrueType fonts in a document upon it is saved. The default value is false..
attr_accessor :allow_embedding_post_script_fonts
# Gets or sets CustomTimeZoneInfo.
attr_accessor :custom_time_zone_info_data
# Gets or sets the value determining how 3D effects are rendered.
attr_accessor :dml3_d_effects_rendering_mode
# Gets or sets the value determining how DrawingML effects are rendered.
# { Simplified | None | Fine }.
attr_accessor :dml_effects_rendering_mode
# Gets or sets the option that controls how DrawingML shapes are rendered.
attr_accessor :dml_rendering_mode
# Gets or sets the name of destination file.
attr_accessor :file_name
# Gets or sets value determining which document formats are allowed to be mapped by Aspose.Words.Markup.StructuredDocumentTag.XmlMapping.
# By default only Aspose.Words.LoadFormat.FlatOpc document format is allowed to be mapped.
attr_accessor :flat_opc_xml_mapping_only
# Gets or sets the value determining how ink (InkML) objects are rendered.
attr_accessor :iml_rendering_mode
# Gets or sets the format of save.
attr_accessor :save_format
# Gets or sets a value determining whether the Aspose.Words.Properties.BuiltInDocumentProperties.CreatedTime property is updated before saving.
# Default value is false.
attr_accessor :update_created_time_property
# Gets or sets a value indicating whether fields should be updated before saving the document to a fixed page format. The default value is true.
attr_accessor :update_fields
# Gets or sets a value indicating whether the Aspose.Words.Properties.BuiltInDocumentProperties.LastPrinted property is updated before saving.
attr_accessor :update_last_printed_property
# Gets or sets a value indicating whether the Aspose.Words.Properties.BuiltInDocumentProperties.LastSavedTime property is updated before saving.
attr_accessor :update_last_saved_time_property
# Gets or sets a value indicating whether content of StructuredDocumentTag is updated before saving.
attr_accessor :update_sdt_content
# Gets or sets a value indicating whether to zip output or not.
# The default value is false.
attr_accessor :zip_output
# Gets or sets the value determining how colors are rendered.
# { Normal | Grayscale}.
attr_accessor :color_mode
# Gets or sets the quality of the JPEG images inside PDF document.
attr_accessor :jpeg_quality
# Gets or sets the metafile rendering options.
attr_accessor :metafile_rendering_options
# Gets or sets the symbol set, that is used to represent numbers while rendering to fixed page formats.
attr_accessor :numeral_format
# Gets or sets a value indicating whether it is required to optimize output of XPS.
# If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated.
# Note: The accuracy of the content display may be affected if this property is set to true.. The default value is false.
attr_accessor :optimize_output
# Gets or sets the number of pages to render.
attr_accessor :page_count
# Gets or sets the 0-based index of the first page to render.
attr_accessor :page_index
# Gets or sets the horizontal resolution in dots per inch for the generated images.
# This property has effect only when saving to raster image formats.
# The default value is 96.
attr_accessor :horizontal_resolution
# Gets or sets the brightness level of the image.
attr_accessor :image_brightness
# Gets or sets the color mode of the image.
attr_accessor :image_color_mode
# Gets or sets the contrast level of the image.
attr_accessor :image_contrast
# Gets or sets the background (paper) color of the image.
attr_accessor :paper_color
# Gets or sets the pixel format of the image.
attr_accessor :pixel_format
# Gets or sets both horizontal and vertical resolution in dots per inch for the generated images.
# This property has effect only when saving to raster image formats.
# The default value is 96.
attr_accessor :resolution
# Gets or sets the zoom factor of the image.
attr_accessor :scale
# Gets or sets a value indicating whether to use anti-aliasing for rendering.
attr_accessor :use_anti_aliasing
# Gets or sets a value indicating whether to use GDI+ or Aspose.Words metafile renderer when saving to EMF.
attr_accessor :use_gdi_emf_renderer
# Gets or sets a value indicating whether to use high quality (i.e. slow) rendering algorithms.
attr_accessor :use_high_quality_rendering
# Gets or sets the vertical resolution in dots per inch for the generated images.
# This property has effect only when saving to raster image formats.
# The default value is 96.
attr_accessor :vertical_resolution
class EnumAttributeValidator
attr_reader :datatype
attr_reader :allowable_values
def initialize(datatype, allowable_values)
@allowable_values = allowable_values.map do |value|
case datatype.to_s
when /Integer/i
value.to_i
when /Float/i
value.to_f
else
value
end
end
end
def valid?(value)
!value || allowable_values.include?(value)
end
end
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'allow_embedding_post_script_fonts' => :'AllowEmbeddingPostScriptFonts',
:'custom_time_zone_info_data' => :'CustomTimeZoneInfoData',
:'dml3_d_effects_rendering_mode' => :'Dml3DEffectsRenderingMode',
:'dml_effects_rendering_mode' => :'DmlEffectsRenderingMode',
:'dml_rendering_mode' => :'DmlRenderingMode',
:'file_name' => :'FileName',
:'flat_opc_xml_mapping_only' => :'FlatOpcXmlMappingOnly',
:'iml_rendering_mode' => :'ImlRenderingMode',
:'save_format' => :'SaveFormat',
:'update_created_time_property' => :'UpdateCreatedTimeProperty',
:'update_fields' => :'UpdateFields',
:'update_last_printed_property' => :'UpdateLastPrintedProperty',
:'update_last_saved_time_property' => :'UpdateLastSavedTimeProperty',
:'update_sdt_content' => :'UpdateSdtContent',
:'zip_output' => :'ZipOutput',
:'color_mode' => :'ColorMode',
:'jpeg_quality' => :'JpegQuality',
:'metafile_rendering_options' => :'MetafileRenderingOptions',
:'numeral_format' => :'NumeralFormat',
:'optimize_output' => :'OptimizeOutput',
:'page_count' => :'PageCount',
:'page_index' => :'PageIndex',
:'horizontal_resolution' => :'HorizontalResolution',
:'image_brightness' => :'ImageBrightness',
:'image_color_mode' => :'ImageColorMode',
:'image_contrast' => :'ImageContrast',
:'paper_color' => :'PaperColor',
:'pixel_format' => :'PixelFormat',
:'resolution' => :'Resolution',
:'scale' => :'Scale',
:'use_anti_aliasing' => :'UseAntiAliasing',
:'use_gdi_emf_renderer' => :'UseGdiEmfRenderer',
:'use_high_quality_rendering' => :'UseHighQualityRendering',
:'vertical_resolution' => :'VerticalResolution'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'allow_embedding_post_script_fonts' => :'BOOLEAN',
:'custom_time_zone_info_data' => :'TimeZoneInfoData',
:'dml3_d_effects_rendering_mode' => :'String',
:'dml_effects_rendering_mode' => :'String',
:'dml_rendering_mode' => :'String',
:'file_name' => :'String',
:'flat_opc_xml_mapping_only' => :'BOOLEAN',
:'iml_rendering_mode' => :'String',
:'save_format' => :'String',
:'update_created_time_property' => :'BOOLEAN',
:'update_fields' => :'BOOLEAN',
:'update_last_printed_property' => :'BOOLEAN',
:'update_last_saved_time_property' => :'BOOLEAN',
:'update_sdt_content' => :'BOOLEAN',
:'zip_output' => :'BOOLEAN',
:'color_mode' => :'String',
:'jpeg_quality' => :'Integer',
:'metafile_rendering_options' => :'MetafileRenderingOptionsData',
:'numeral_format' => :'String',
:'optimize_output' => :'BOOLEAN',
:'page_count' => :'Integer',
:'page_index' => :'Integer',
:'horizontal_resolution' => :'Float',
:'image_brightness' => :'Float',
:'image_color_mode' => :'String',
:'image_contrast' => :'Float',
:'paper_color' => :'String',
:'pixel_format' => :'String',
:'resolution' => :'Float',
:'scale' => :'Float',
:'use_anti_aliasing' => :'BOOLEAN',
:'use_gdi_emf_renderer' => :'BOOLEAN',
:'use_high_quality_rendering' => :'BOOLEAN',
:'vertical_resolution' => :'Float'
}
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.key?(:'AllowEmbeddingPostScriptFonts')
self.allow_embedding_post_script_fonts = attributes[:'AllowEmbeddingPostScriptFonts']
end
if attributes.key?(:'CustomTimeZoneInfoData')
self.custom_time_zone_info_data = attributes[:'CustomTimeZoneInfoData']
end
if attributes.key?(:'Dml3DEffectsRenderingMode')
self.dml3_d_effects_rendering_mode = attributes[:'Dml3DEffectsRenderingMode']
end
if attributes.key?(:'DmlEffectsRenderingMode')
self.dml_effects_rendering_mode = attributes[:'DmlEffectsRenderingMode']
end
if attributes.key?(:'DmlRenderingMode')
self.dml_rendering_mode = attributes[:'DmlRenderingMode']
end
if attributes.key?(:'FileName')
self.file_name = attributes[:'FileName']
end
if attributes.key?(:'FlatOpcXmlMappingOnly')
self.flat_opc_xml_mapping_only = attributes[:'FlatOpcXmlMappingOnly']
end
if attributes.key?(:'ImlRenderingMode')
self.iml_rendering_mode = attributes[:'ImlRenderingMode']
end
if attributes.key?(:'SaveFormat')
self.save_format = attributes[:'SaveFormat']
end
if attributes.key?(:'UpdateCreatedTimeProperty')
self.update_created_time_property = attributes[:'UpdateCreatedTimeProperty']
end
if attributes.key?(:'UpdateFields')
self.update_fields = attributes[:'UpdateFields']
end
if attributes.key?(:'UpdateLastPrintedProperty')
self.update_last_printed_property = attributes[:'UpdateLastPrintedProperty']
end
if attributes.key?(:'UpdateLastSavedTimeProperty')
self.update_last_saved_time_property = attributes[:'UpdateLastSavedTimeProperty']
end
if attributes.key?(:'UpdateSdtContent')
self.update_sdt_content = attributes[:'UpdateSdtContent']
end
if attributes.key?(:'ZipOutput')
self.zip_output = attributes[:'ZipOutput']
end
if attributes.key?(:'ColorMode')
self.color_mode = attributes[:'ColorMode']
end
if attributes.key?(:'JpegQuality')
self.jpeg_quality = attributes[:'JpegQuality']
end
if attributes.key?(:'MetafileRenderingOptions')
self.metafile_rendering_options = attributes[:'MetafileRenderingOptions']
end
if attributes.key?(:'NumeralFormat')
self.numeral_format = attributes[:'NumeralFormat']
end
if attributes.key?(:'OptimizeOutput')
self.optimize_output = attributes[:'OptimizeOutput']
end
if attributes.key?(:'PageCount')
self.page_count = attributes[:'PageCount']
end
if attributes.key?(:'PageIndex')
self.page_index = attributes[:'PageIndex']
end
if attributes.key?(:'HorizontalResolution')
self.horizontal_resolution = attributes[:'HorizontalResolution']
end
if attributes.key?(:'ImageBrightness')
self.image_brightness = attributes[:'ImageBrightness']
end
if attributes.key?(:'ImageColorMode')
self.image_color_mode = attributes[:'ImageColorMode']
end
if attributes.key?(:'ImageContrast')
self.image_contrast = attributes[:'ImageContrast']
end
if attributes.key?(:'PaperColor')
self.paper_color = attributes[:'PaperColor']
end
if attributes.key?(:'PixelFormat')
self.pixel_format = attributes[:'PixelFormat']
end
if attributes.key?(:'Resolution')
self.resolution = attributes[:'Resolution']
end
if attributes.key?(:'Scale')
self.scale = attributes[:'Scale']
end
if attributes.key?(:'UseAntiAliasing')
self.use_anti_aliasing = attributes[:'UseAntiAliasing']
end
if attributes.key?(:'UseGdiEmfRenderer')
self.use_gdi_emf_renderer = attributes[:'UseGdiEmfRenderer']
end
if attributes.key?(:'UseHighQualityRendering')
self.use_high_quality_rendering = attributes[:'UseHighQualityRendering']
end
if attributes.key?(:'VerticalResolution')
self.vertical_resolution = attributes[:'VerticalResolution']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properies with the reasons
def list_invalid_properties
invalid_properties = []
return invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
dml3_d_effects_rendering_mode_validator = EnumAttributeValidator.new('String', ["Basic", "Advanced"])
return false unless dml3_d_effects_rendering_mode_validator.valid?(@dml3_d_effects_rendering_mode)
return true
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] dml3_d_effects_rendering_mode Object to be assigned
def dml3_d_effects_rendering_mode=(dml3_d_effects_rendering_mode)
validator = EnumAttributeValidator.new('String', ["Basic", "Advanced"])
if dml3_d_effects_rendering_mode.to_i == 0
unless validator.valid?(dml3_d_effects_rendering_mode)
raise ArgumentError, "invalid value for 'dml3_d_effects_rendering_mode', must be one of #{validator.allowable_values}."
end
@dml3_d_effects_rendering_mode = dml3_d_effects_rendering_mode
else
@dml3_d_effects_rendering_mode = validator.allowable_values[dml3_d_effects_rendering_mode.to_i]
end
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(other)
return true if self.equal?(other)
self.class == other.class &&
allow_embedding_post_script_fonts == other.allow_embedding_post_script_fonts &&
custom_time_zone_info_data == other.custom_time_zone_info_data &&
dml3_d_effects_rendering_mode == other.dml3_d_effects_rendering_mode &&
dml_effects_rendering_mode == other.dml_effects_rendering_mode &&
dml_rendering_mode == other.dml_rendering_mode &&
file_name == other.file_name &&
flat_opc_xml_mapping_only == other.flat_opc_xml_mapping_only &&
iml_rendering_mode == other.iml_rendering_mode &&
save_format == other.save_format &&
update_created_time_property == other.update_created_time_property &&
update_fields == other.update_fields &&
update_last_printed_property == other.update_last_printed_property &&
update_last_saved_time_property == other.update_last_saved_time_property &&
update_sdt_content == other.update_sdt_content &&
zip_output == other.zip_output &&
color_mode == other.color_mode &&
jpeg_quality == other.jpeg_quality &&
metafile_rendering_options == other.metafile_rendering_options &&
numeral_format == other.numeral_format &&
optimize_output == other.optimize_output &&
page_count == other.page_count &&
page_index == other.page_index &&
horizontal_resolution == other.horizontal_resolution &&
image_brightness == other.image_brightness &&
image_color_mode == other.image_color_mode &&
image_contrast == other.image_contrast &&
paper_color == other.paper_color &&
pixel_format == other.pixel_format &&
resolution == other.resolution &&
scale == other.scale &&
use_anti_aliasing == other.use_anti_aliasing &&
use_gdi_emf_renderer == other.use_gdi_emf_renderer &&
use_high_quality_rendering == other.use_high_quality_rendering &&
vertical_resolution == other.vertical_resolution
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(other)
self == other
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[allow_embedding_post_script_fonts, custom_time_zone_info_data, dml3_d_effects_rendering_mode, dml_effects_rendering_mode, dml_rendering_mode, file_name, flat_opc_xml_mapping_only, iml_rendering_mode, save_format, update_created_time_property, update_fields, update_last_printed_property, update_last_saved_time_property, update_sdt_content, zip_output, color_mode, jpeg_quality, metafile_rendering_options, numeral_format, optimize_output, page_count, page_index, horizontal_resolution, image_brightness, image_color_mode, image_contrast, paper_color, pixel_format, resolution, scale, use_anti_aliasing, use_gdi_emf_renderer, use_high_quality_rendering, vertical_resolution].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
Time.at(/\d/.match(value)[0].to_f).to_datetime
when :Date
Time.at(/\d/.match(value)[0].to_f).to_date
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 = AsposeWordsCloud.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
| 39.291809 | 686 | 0.676395 |
26db0590f796410cd062ad2dfaeb6c1fdde9fbe2 | 93 | Sequel.migration do
change do
drop_table :service_instance_dashboard_clients
end
end
| 15.5 | 50 | 0.806452 |
872d79c29a474106fbb78ae0cb0699f0d32e9f31 | 4,289 | require 'spec_helper'
require 'actions/transactional_metadata_update'
module VCAP::CloudController
RSpec.describe TransactionalMetadataUpdate do
describe '#update' do
let(:new_metadata) {
{
metadata: {
labels: {
freaky: 'wednesday'
},
annotations: {
tokyo: 'grapes'
}
}
}
}
let(:update_request_body) { new_metadata }
let(:resource) { Service.make }
let(:message) { MetadataUpdateMessage.new(update_request_body) }
context 'when the resource has no metadata' do
context 'and no metadata is specified' do
let(:update_request_body) { {} }
it 'adds no metadata' do
expect(message).to be_valid
updated_resource = TransactionalMetadataUpdate.update(resource, message)
resource.reload
expect(resource).to eq(updated_resource)
expect(updated_resource).not_to have_labels
expect(updated_resource).not_to have_annotations
end
end
it 'adds metadata to a resource' do
expect(message).to be_valid
updated_resource = TransactionalMetadataUpdate.update(resource, message)
expect(updated_resource).to have_labels({ key: 'freaky', value: 'wednesday' })
expect(updated_resource).to have_annotations({ key: 'tokyo', value: 'grapes' })
resource.reload
expect(resource).to eq(updated_resource)
end
end
context 'when the resource has existing metadata' do
before do
VCAP::CloudController::ServiceOfferingLabelModel.make(resource_guid: resource.guid, key_name: 'freaky', value: 'tuesday')
VCAP::CloudController::ServiceOfferingAnnotationModel.make(resource_guid: resource.guid, key: 'tokyo', value: 'apples')
end
context 'and no metadata is specified' do
let(:update_request_body) { {} }
it 'does not change the existing values' do
expect(message).to be_valid
updated_resource = TransactionalMetadataUpdate.update(resource, message)
resource.reload
expect(resource).to eq(updated_resource)
expect(updated_resource).to have_labels({ key: 'freaky', value: 'tuesday' })
expect(updated_resource).to have_annotations({ key: 'tokyo', value: 'apples' })
end
end
it 'can add new values' do
message = MetadataUpdateMessage.new({
metadata: {
labels: {
freaky: 'tuesday',
another_label: 'new-label',
},
annotations: {
tokyo: 'apples',
another_annotation: 'new-annotation',
}
}
})
expect(message).to be_valid
updated_resource = TransactionalMetadataUpdate.update(resource, message)
expect(updated_resource).to have_labels(
{ key: 'freaky', value: 'tuesday' },
{ key: 'another_label', value: 'new-label' },
)
expect(updated_resource).to have_annotations(
{ key: 'tokyo', value: 'apples' },
{ key: 'another_annotation', value: 'new-annotation' }
)
end
it 'can update existing values' do
expect(message).to be_valid
updated_resource = TransactionalMetadataUpdate.update(resource, message)
expect(updated_resource).to have_labels({ key: 'freaky', value: 'wednesday' })
expect(updated_resource).to have_annotations({ key: 'tokyo', value: 'grapes' })
end
it 'can delete existing values' do
new_body = {
metadata: {
labels: {
freaky: nil
},
annotations: {
tokyo: nil
}
}
}
new_message = MetadataUpdateMessage.new(new_body)
expect(new_message).to be_valid
updated_resource = TransactionalMetadataUpdate.update(resource, new_message)
expect(updated_resource).not_to have_labels
expect(updated_resource).not_to have_annotations
end
end
end
end
end
| 33.771654 | 131 | 0.583819 |
1a78cbad161e35c302baa6de44064efcbf484f7d | 128 | class AddUserIdToDashboards < ActiveRecord::Migration[5.1]
def change
add_column :dashboards, :user_id, :string
end
end
| 21.333333 | 58 | 0.757813 |
1c0487e83ce8d38857291f588bdcdbf22a0b3e9c | 767 | require 'rails_helper'
RSpec.describe LessonsController, type: :routing do
describe 'routing' do
it 'routes to #index' do
expect(get: '/lessons').to route_to('lessons#index')
end
it 'routes to #show' do
expect(get: '/lessons/1').to route_to('lessons#show', id: '1')
end
it 'routes to #create' do
expect(post: '/lessons').to route_to('lessons#create')
end
it 'routes to #update via PUT' do
expect(put: '/lessons/1').to route_to('lessons#update', id: '1')
end
it 'routes to #update via PATCH' do
expect(patch: '/lessons/1').to route_to('lessons#update', id: '1')
end
it 'routes to #destroy' do
expect(delete: '/lessons/1').to route_to('lessons#destroy', id: '1')
end
end
end
| 25.566667 | 74 | 0.621904 |
ffe98e7247f16a7d9bec0083e63eb69dd9a02790 | 751 | # frozen_string_literal: true
Gem::Specification.new do |spec|
spec.name = "jekyll-theme-clean-blog"
spec.version = "4.0.9"
spec.authors = ["Start Bootstrap"]
spec.email = ["[email protected]"]
spec.summary = "A simple blog theme based on Bootstrap 4 by Start Bootstrap."
spec.homepage = "https://github.com/blackrockdigital/startbootstrap-clean-blog-jekyll"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").select { |f| f.match(%r{^(assets|_layouts|_includes|_sass|LICENSE|README)}i) }
spec.add_runtime_dependency "jekyll", "~> 3.8.5"
spec.add_development_dependency "bundler", "~> 2.0.1"
spec.add_development_dependency "rake", "~> 12.0"
end
| 37.55 | 132 | 0.65779 |
e839af01d62f0d0f355b1b5a74feebff1397f536 | 304 | cask "font-righteous" do
version :latest
sha256 :no_check
url "https://github.com/google/fonts/raw/main/ofl/righteous/Righteous-Regular.ttf",
verified: "github.com/google/fonts/"
name "Righteous"
homepage "https://fonts.google.com/specimen/Righteous"
font "Righteous-Regular.ttf"
end
| 25.333333 | 85 | 0.733553 |
1cb3606126c60fda08066dabcf8b157da3f0c158 | 72 | module ComicVine
# Current gem version number
VERSION = '0.1.4'
end
| 14.4 | 30 | 0.708333 |
280db75168b56a218ae379e3343a8a2deb32addc | 4,002 | # :include: ../rdoc/syslogoutputter
#
# Version:: $Id$
# Author:: Steve Lumos
# Author:: Leon Torres
require 'log4r/formatter/formatter'
require 'log4r/outputter/outputter'
require 'log4r/configurator'
require 'syslog'
module Log4r
SYSLOGNAMES = Hash.new
class SyslogOutputter < Outputter
include Syslog::Constants
# maps default log4r levels to syslog priorities (logevents never see ALL and OFF)
# SYSLOG Levels are:
# "DEBUG" => Syslog::LOG_DEBUG
# "INFO" => Syslog::LOG_INFO
# "NOTICE" => Syslog::LOG_NOTICE
# "WARN" => Syslog::LOG_WARN
# "ERROR" => Syslog::LOG_ERROR
# "FATAL" => Syslog::LOG_FATAL
# "ALERT" => Syslog::LOG_ALERT
# "EMERG" => Syslog::LOG_EMERG
SYSLOG_LEVELS_MAP = {
"DEBUG" => LOG_DEBUG,
"INFO" => LOG_INFO,
"NOTICE" => LOG_NOTICE, # by default NOTICE is not in log4r
"WARN" => LOG_WARNING,
"ERROR" => LOG_ERR,
"FATAL" => LOG_CRIT,
"ALERT" => LOG_ALERT, # by default ALERT is not in log4r
"EMERG" => LOG_EMERG, # by default EMERG is not in log4r
}
# mapping from Log4r default levels to syslog, by string name
# "DEBUG" => "DEBUG"
# "INFO" => "INFO"
# "WARN" => "WARN"
# "ERROR" => "ERROR"
# "FATAL" => "FATAL"
SYSLOG_LOG4R_MAP = {
"DEBUG" => "DEBUG",
"INFO" => "INFO",
"WARN" => "WARN",
"ERROR" => "ERROR",
"FATAL" => "FATAL"
# "NOTICE" => "INFO", # by default NOTICE is not in log4r
# "ALERT" => "FATAL", # by default ALERT is not in log4r
# "EMERG" => "FATAL" # by default EMERG is not in log4r
}
@levels_map = SYSLOG_LOG4R_MAP
# There are 3 hash arguments
#
# [<tt>:ident</tt>] syslog ident, defaults to _name
# [<tt>:logopt</tt>] syslog logopt, defaults to LOG_PID | LOG_CONS
# [<tt>:facility</tt>] syslog facility, defaults to LOG_USER
def initialize(_name, hash={})
super(_name, hash)
@ident = (hash[:ident] or hash['ident'] or _name)
@logopt = (hash[:logopt] or hash['logopt'] or LOG_PID | LOG_CONS).to_i
@facility = (hash[:facility] or hash['facility'] or LOG_USER).to_i
map_levels_by_name_to_syslog()
end
def closed?
@level == OFF
end
def close
@level = OFF
OutputterFactory.create_methods(self)
Logger.log_internal {"Outputter '#{@name}' closed Syslog and set to OFF"}
end
# A single hash argument that maps custom names to syslog names
#
# [<tt>levels_map</tt>] A map that will create a linkage between levels
# in a hash and underlying syslog levels.
# By default, these are direct mapping of the log4r
# levels (e.g. "DEBUG" => "DEBUG")
# If you have defined your own custom levels, you
# should provide this underlying mapping, otherwise
# all messages will be mapped to the underlying syslog
# level of INFO by default.
# e.g.
# You have created custom levels called:
# <tt>Configurator.custom_levels "HIGH", "MEDIUM", "LOW"</tt>
# To map these to 'equivilent' syslog levels, after instantiatin
# a syslogoutputter:
# <tt>SyslogOutputter.map_levels_by_name_to_syslog(
# { "HIGH" => "ALERT", "MEDIUM" => "WARN", "LOW" => "INFO" }
# )</tt>
def map_levels_by_name_to_syslog( lmap = SYSLOG_LOG4R_MAP )
@levels_map = lmap
end
def get_levels_map()
return @levels_map
end
private
def canonical_log(logevent)
pri = SYSLOG_LEVELS_MAP[@levels_map[LNAMES[logevent.level]]] rescue pri = LOG_INFO
o = format(logevent)
if o.kind_of? Exception then
msg = "#{o.class} at (#{o.backtrace[0]}): #{o.message}"
elsif o.respond_to? :to_str then
msg = o.to_str
else
msg = o.inspect
end
Syslog.open(@ident, @logopt, @facility) do |s|
s.log(pri, '%s', msg)
end
end
end
end
| 31.511811 | 88 | 0.595952 |
03805a97ffb940bcd47d8b428d4888e814876c36 | 2,223 | require 'uri'
require 'rkelly'
class ContentUrls
# +JavaScriptParser+ finds and rewrites URLs in JavaScript content.
#
# === Implementation note:
# This methods in this class identify URLs by locating strings which match +URI+'s regexp.
class JavaScriptParser
# Returns the URLs found in the JavaScript content.
#
# @param [String] content the JavaScript content.
# @return [Array] the unique URLs found in the content.
#
# @example Parse JavaScript code for URLs
# javascript = 'var link="http://example.com/"'
# ContentUrls::JavaScriptParser.urls(javascript).each do |url|
# puts "Found URL: #{url}"
# end
# # => "Found URL: http://example.com/"
def self.urls(content)
urls = []
return urls if content.nil? || content.length == 0
rewrite_each_url(content) { |url| urls << url; url }
urls.uniq!
urls
end
# Rewrites each URL in the JavaScript content by calling the supplied block with each URL.
#
# @param [String] content the JavaScript content.
#
# @example Rewrite URLs in JavaScript code
# javascript = 'var link="http://example.com/"'
# javascript = ContentUrls::JavaScriptParser.rewrite_each_url(javascript) {|url| url.upcase}
# puts "Rewritten: #{javascript}"
# # => "Rewritten: var link="HTTP://EXAMPLE.COM/""
#
def self.rewrite_each_url(content, &block)
rewritten_content = content.dup
rewrite_urls = {}
parser = RKelly::Parser.new
ast = parser.parse(content)
return content if ast.nil?
ast.each do |node|
if node.kind_of? RKelly::Nodes::StringNode
value = node.value
if match = /^'(.*)'$/.match(value)
value = match[1] # remove single quotes
end
if match = URI.regexp.match(value)
url = match.to_s
rewritten_url = yield url
rewrite_urls[url] = rewritten_url if url != rewritten_url
end
end
end
if rewrite_urls.count > 0
rewrite_urls.each do |url, rewritten_url|
rewritten_content[url] = rewritten_url.to_s
end
end
rewritten_content
end
end
end
| 31.757143 | 98 | 0.618534 |
39588f85aece208fa0d719889e53e0c9f7617ba8 | 1,763 | class UserMailer < ApplicationMailer
default from: "Feedbin <#{ENV["FROM_ADDRESS"]}>", skip_premailer: true
add_template_helper(ApplicationHelper)
def payment_receipt(billing_event)
@billing_event = BillingEvent.find(billing_event)
@user = @billing_event.billable
mail to: @user.email, subject: "[Feedbin] Payment Receipt"
end
def payment_failed(billing_event)
@billing_event = BillingEvent.find(billing_event)
@user = @billing_event.billable
mail to: @user.email, subject: "[Feedbin] Please Update Your Billing Information"
end
def password_reset(user_id, reset_token)
@user = User.find(user_id)
@reset_token = reset_token
mail to: @user.email, subject: "[Feedbin] Password Reset"
end
def trial_expiration(user_id)
@user = User.find(user_id)
mail to: @user.email, subject: "[Feedbin] Your Trial is About to End"
end
def timed_plan_expiration(user_id)
@user = User.find(user_id)
mail to: @user.email, subject: "[Feedbin] Your Account has Expired"
end
def starred_export_download(user_id, download_link)
@user = User.find(user_id)
@download_link = download_link
mail to: @user.email, subject: "[Feedbin] Starred Items Export Complete"
end
def kindle(kindle_address, mobi_file)
attachments["kindle.mobi"] = File.read(mobi_file)
mail to: kindle_address, subject: "Kindle Content", body: "", from: ENV["KINDLE_EMAIL"]
end
def account_closed(user_id, opml)
@user = User.find(user_id)
attachments["subscriptions.xml"] = opml
mail to: @user.email, subject: "[Feedbin] Account Closed"
end
def twitter_connection_error(user_id)
@user = User.find(user_id)
mail to: @user.email, subject: "[Feedbin] Twitter Connection Error"
end
end
| 32.054545 | 91 | 0.718094 |
385c6885a263d95ad2c3811979c04806de991107 | 1,373 | #! /your/favourite/path/to/ruby
# -*- coding: utf-8; mode: ruby; ruby-indent-level: 2 -*-
#
# Copyright (c) 2014 Urabe, Shyouhei
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
require_relative "space_observatory/version"
module SpaceObservatory
require_relative 'space_observatory/railtie' if defined? ::Rails
end
| 47.344828 | 79 | 0.749454 |
21d63232bfd1fadcfe14bf13e539213caad993e4 | 178 | class AddUuidToSaveableMultipleChoiceAnswers < ActiveRecord::Migration[5.1]
def change
add_column :saveable_multiple_choice_answers, :uuid, :string, :limit => 36
end
end
| 29.666667 | 78 | 0.786517 |
8777a0a00ba2d5d35bfb863661eed446de60aed5 | 116 | class RealtimeController < ApplicationController
before_action :require_administrator!
def answers
end
end
| 16.571429 | 48 | 0.810345 |
bf81d6c1c1ce1569f478dd1c31bfcd4de5bfb9cd | 16,896 | # frozen_string_literal: true
require 'spec_helper'
require 'yaml'
module Cucumber
module Cli
module ExposesOptions
attr_reader :options
end
describe Configuration do
def given_cucumber_yml_defined_as(hash_or_string)
allow(File).to receive(:exist?) { true }
cucumber_yml = hash_or_string.is_a?(Hash) ? hash_or_string.to_yaml : hash_or_string
allow(IO).to receive(:read).with('cucumber.yml') { cucumber_yml }
end
def given_the_following_files(*files)
allow(File).to receive(:directory?) { true }
allow(File).to receive(:file?) { true }
allow(Dir).to receive(:[]) { files }
end
before(:each) do
allow(File).to receive(:exist?) { false } # Meaning, no cucumber.yml exists
allow(Kernel).to receive(:exit)
end
def config
@config ||= Configuration.new(@out = StringIO.new, @error = StringIO.new).extend(ExposesOptions)
end
def reset_config
@config = nil
end
attr_reader :out, :error
it 'uses the default profile when no profile is defined' do
given_cucumber_yml_defined_as('default' => '--require some_file')
config.parse!(%w[--format progress])
expect(config.options[:require]).to include('some_file')
end
context '--profile' do
include RSpec::WorkInProgress
it 'expands args from profiles in the cucumber.yml file' do
given_cucumber_yml_defined_as('bongo' => '--require from/yml')
config.parse!(%w[--format progress --profile bongo])
expect(config.options[:formats]).to eq [['progress', {}, out]]
expect(config.options[:require]).to eq ['from/yml']
end
it 'expands args from the default profile when no flags are provided' do
given_cucumber_yml_defined_as('default' => '--require from/yml')
config.parse!([])
expect(config.options[:require]).to eq ['from/yml']
end
it 'allows --strict to be set by a profile' do
given_cucumber_yml_defined_as('bongo' => '--strict')
config.parse!(%w[--profile bongo])
expect(config.options[:strict].strict?(:undefined)).to be true
expect(config.options[:strict].strict?(:pending)).to be true
expect(config.options[:strict].strict?(:flaky)).to be true
end
it 'allows --strict from a profile to be selectively overridden' do
given_cucumber_yml_defined_as('bongo' => '--strict')
config.parse!(%w[--profile bongo --no-strict-flaky])
expect(config.options[:strict].strict?(:undefined)).to be true
expect(config.options[:strict].strict?(:pending)).to be true
expect(config.options[:strict].strict?(:flaky)).to be false
end
it 'parses ERB syntax in the cucumber.yml file' do
given_cucumber_yml_defined_as("---\ndefault: \"<%=\"--require some_file\"%>\"\n")
config.parse!([])
expect(config.options[:require]).to include('some_file')
end
it 'parses ERB in cucumber.yml that makes uses nested ERB sessions' do
given_cucumber_yml_defined_as(<<ERB_YML)
<%= ERB.new({'standard' => '--require some_file'}.to_yaml).result %>
<%= ERB.new({'enhanced' => '--require other_file'}.to_yaml).result %>
ERB_YML
config.parse!(%w[-p standard])
expect(config.options[:require]).to include('some_file')
end
it 'provides a helpful error message when a specified profile does not exists in cucumber.yml' do
given_cucumber_yml_defined_as('default' => '--require from/yml', 'json_report' => '--format json')
expected_message = <<-END_OF_MESSAGE
Could not find profile: 'i_do_not_exist'
Defined profiles in cucumber.yml:
* default
* json_report
END_OF_MESSAGE
expect { config.parse!(%w[--profile i_do_not_exist]) }.to raise_error(ProfileNotFound, expected_message)
end
it 'allows profiles to be defined in arrays' do
given_cucumber_yml_defined_as('foo' => ['-f', 'progress'])
config.parse!(%w[--profile foo])
expect(config.options[:formats]).to eq [['progress', {}, out]]
end
it 'disregards default STDOUT formatter defined in profile when another is passed in (via cmd line)' do
given_cucumber_yml_defined_as('foo' => %w[--format pretty])
config.parse!(%w[--format progress --profile foo])
expect(config.options[:formats]).to eq [['progress', {}, out]]
end
['--no-profile', '-P'].each do |flag|
context 'when none is specified with #{flag}' do # rubocop:disable Lint/InterpolationCheck
it 'disables profiles' do
given_cucumber_yml_defined_as('default' => '-v --require file_specified_in_default_profile.rb')
config.parse!("#{flag} --require some_file.rb".split(' '))
expect(config.options[:require]).to eq ['some_file.rb']
end
it 'notifies the user that the profiles are being disabled' do
given_cucumber_yml_defined_as('default' => '-v')
config.parse!("#{flag} --require some_file.rb".split(' '))
expect(out.string).to match(/Disabling profiles.../)
end
end
end
it 'issues a helpful error message when a specified profile exists but is nil or blank' do
[nil, ' '].each do |bad_input|
given_cucumber_yml_defined_as('foo' => bad_input)
expected_error = /The 'foo' profile in cucumber.yml was blank. Please define the command line arguments for the 'foo' profile in cucumber.yml./
expect { config.parse!(%w[--profile foo]) }.to raise_error(expected_error)
end
end
it 'issues a helpful error message when no YAML file exists and a profile is specified' do
expect(File).to receive(:exist?).with('cucumber.yml') { false }
expected_error = /cucumber\.yml was not found/
expect { config.parse!(%w[--profile i_do_not_exist]) }.to raise_error(expected_error)
end
it 'issues a helpful error message when cucumber.yml is blank or malformed' do
expected_error_message = /cucumber\.yml was found, but was blank or malformed. Please refer to cucumber's documentation on correct profile usage./
['', 'sfsadfs', "--- \n- an\n- array\n", '---dddfd'].each do |bad_input|
given_cucumber_yml_defined_as(bad_input)
expect { config.parse!([]) }.to raise_error(expected_error_message)
reset_config
end
end
it 'issues a helpful error message when cucumber.yml can not be parsed' do
expected_error_message = /cucumber.yml was found, but could not be parsed. Please refer to cucumber's documentation on correct profile usage./
given_cucumber_yml_defined_as('input that causes an exception in YAML loading')
expect(YAML).to receive(:load).and_raise(ArgumentError)
expect { config.parse!([]) }.to raise_error(expected_error_message)
end
it 'issues a helpful error message when cucumber.yml can not be parsed by ERB' do
expected_error_message = /cucumber.yml was found, but could not be parsed with ERB. Please refer to cucumber's documentation on correct profile usage./
given_cucumber_yml_defined_as('<% this_fails %>')
expect { config.parse!([]) }.to raise_error(expected_error_message)
end
end
it 'accepts --dry-run option' do
config.parse!(%w[--dry-run])
expect(config.options[:dry_run]).to be true
end
it 'implies --no-duration with --dry-run option' do
config.parse!(%w[--dry-run])
expect(config.options[:duration]).to be false
end
it 'accepts --no-source option' do
config.parse!(%w[--no-source])
expect(config.options[:source]).to be false
end
it 'accepts --no-snippets option' do
config.parse!(%w[--no-snippets])
expect(config.options[:snippets]).to be false
end
it 'sets snippets and source and duration to false with --quiet option' do
config.parse!(%w[--quiet])
expect(config.options[:snippets]).to be false
expect(config.options[:source]).to be false
expect(config.options[:duration]).to be false
end
it 'sets duration to false with --no-duration' do
config.parse!(%w[--no-duration])
expect(config.options[:duration]).to be false
end
it 'accepts --verbose option' do
config.parse!(%w[--verbose])
expect(config.options[:verbose]).to be true
end
it 'uses the pretty formatter to stdout when no formatter is defined' do
config.parse!([])
expect(config.formats).to eq [['pretty', {}, out]]
end
it 'adds the default formatter when no other formatter is defined with --publish' do
config.parse!(['--publish'])
expect(config.formats).to eq [
['pretty', {}, out],
['message', {}, 'https://messages.cucumber.io/api/reports -X GET']
]
end
it 'does not add the default formatter when a formatter is defined with --publish' do
config.parse!(['--publish', '--format', 'progress'])
expect(config.formats).to eq [
['progress', {}, out],
['message', {}, 'https://messages.cucumber.io/api/reports -X GET']
]
end
it 'does not add the default formatter with --format message' do
config.parse!(['--format', 'message'])
expect(config.formats).to eq [
['message', {}, out]
]
end
it 'accepts --out option' do
config.parse!(%w[--out jalla.txt])
expect(config.formats).to eq [['pretty', {}, 'jalla.txt']]
end
it 'accepts multiple --out options' do
config.parse!(%w[--format progress --out file1 --out file2])
expect(config.formats).to eq [['progress', {}, 'file2']]
end
it 'accepts multiple --format options and put the STDOUT one first so progress is seen' do
config.parse!(%w[--format pretty --out pretty.txt --format progress])
expect(config.formats).to eq [['progress', {}, out], ['pretty', {}, 'pretty.txt']]
end
it 'does not accept multiple --format options when both use implicit STDOUT' do
expect { config.parse!(%w[--format pretty --format progress]) }.to raise_error('All but one formatter must use --out, only one can print to each stream (or STDOUT)')
end
it 'does not accept multiple --format options when both use implicit STDOUT (using profile with no formatters)' do
given_cucumber_yml_defined_as('default' => ['-q'])
expect { config.parse!(%w[--format pretty --format progress]) }.to raise_error('All but one formatter must use --out, only one can print to each stream (or STDOUT)')
end
it 'accepts same --format options with implicit STDOUT, and keep only one' do
config.parse!(%w[--format pretty --format pretty])
expect(config.formats).to eq [['pretty', {}, out]]
end
it 'does not accept multiple --out streams pointing to the same place' do
expected_error = 'All but one formatter must use --out, only one can print to each stream (or STDOUT)'
expect { config.parse!(%w[--format pretty --out file1 --format progress --out file1]) }.to raise_error(expected_error)
end
it 'does not accept multiple --out streams pointing to the same place (one from profile, one from command line)' do
given_cucumber_yml_defined_as('default' => ['-f', 'progress', '--out', 'file1'])
expect { config.parse!(%w[--format pretty --out file1]) }.to raise_error('All but one formatter must use --out, only one can print to each stream (or STDOUT)')
end
it 'associates --out to previous --format' do
config.parse!(%w[--format progress --out file1 --format profile --out file2])
expect(config.formats).to match_array([['progress', {}, 'file1'], ['profile', {}, 'file2']])
end
it 'accepts same --format options with same --out streams and keep only one' do
config.parse!(%w[--format json --out file --format pretty --format json --out file])
expect(config.formats).to eq [['pretty', {}, out], ['json', {}, 'file']]
end
it 'accepts same --format options with different --out streams' do
config.parse!(%w[--format json --out file1 --format json --out file2])
expect(config.formats).to match_array([['json', {}, 'file1'], ['json', {}, 'file2']])
end
it 'accepts --color option' do
expect(Cucumber::Term::ANSIColor).to receive(:coloring=).with(true)
config.parse!(['--color'])
end
it 'accepts --no-color option' do
expect(Cucumber::Term::ANSIColor).to receive(:coloring=).with(false)
config = Configuration.new(StringIO.new)
config.parse!(['--no-color'])
end
describe '--backtrace' do
before do
Cucumber.use_full_backtrace = false
end
it 'shows full backtrace when --backtrace is present' do
Main.new(['--backtrace'])
begin
expect('x').to eq 'y'
rescue RSpec::Expectations::ExpectationNotMetError => e
expect(e.backtrace[0]).not_to eq "#{__FILE__}:#{__LINE__ - 2}"
end
end
after do
Cucumber.use_full_backtrace = false
end
end
it 'accepts multiple --name options' do
config.parse!(['--name', 'User logs in', '--name', 'User signs up'])
expect(config.options[:name_regexps]).to include(/User logs in/)
expect(config.options[:name_regexps]).to include(/User signs up/)
end
it 'accepts multiple -n options' do
config.parse!(['-n', 'User logs in', '-n', 'User signs up'])
expect(config.options[:name_regexps]).to include(/User logs in/)
expect(config.options[:name_regexps]).to include(/User signs up/)
end
it 'should allow specifying environment variables on the command line' do
config.parse!(['foo=bar'])
expect(ENV['foo']).to eq 'bar'
expect(config.paths).not_to include('foo=bar')
end
it 'allows specifying environment variables in profiles' do
given_cucumber_yml_defined_as('selenium' => 'RAILS_ENV=selenium')
config.parse!(['--profile', 'selenium'])
expect(ENV['RAILS_ENV']).to eq 'selenium'
expect(config.paths).not_to include('RAILS_ENV=selenium')
end
describe '#tag_expressions' do
it 'returns an empty expression when no tags are specified' do
config.parse!([])
expect(config.tag_expressions).to be_empty
end
it 'returns an expression when tags are specified' do
config.parse!(['--tags', '@foo'])
expect(config.tag_expressions).not_to be_empty
end
end
describe '#tag_limits' do
it 'returns an empty hash when no limits are specified' do
config.parse!([])
expect(config.tag_limits).to eq({})
end
it 'returns a hash of limits when limits are specified' do
config.parse!(['--tags', '@foo:1'])
expect(config.tag_limits).to eq('@foo' => 1)
end
end
describe '#dry_run?' do
it 'returns true when --dry-run was specified on in the arguments' do
config.parse!(['--dry-run'])
expect(config.dry_run?).to be true
end
it 'returns true when --dry-run was specified in yaml file' do
given_cucumber_yml_defined_as('default' => '--dry-run')
config.parse!([])
expect(config.dry_run?).to be true
end
it 'returns false by default' do
config.parse!([])
expect(config.dry_run?).to be false
end
end
describe '#snippet_type' do
it 'returns the snippet type when it was set' do
config.parse!(['--snippet-type', 'classic'])
expect(config.snippet_type).to eq :classic
end
it 'returns the snippet type when it was set with shorthand option' do
config.parse!(['-I', 'classic'])
expect(config.snippet_type).to eq :classic
end
it 'returns the default snippet type if it was not set' do
config.parse!([])
expect(config.snippet_type).to eq :cucumber_expression
end
end
describe '#retry_attempts' do
it 'returns the specified number of retries' do
config.parse!(['--retry=3'])
expect(config.retry_attempts).to eql 3
end
end
end
end
end
| 35.126819 | 173 | 0.613518 |
edc33ffc8dda9e7a746a2ae790f2a7fd61ec0861 | 4,933 | require "spec_helper"
require "nightcrawler_swift/cli"
describe NightcrawlerSwift::CLI::OptParser do
let :runner do
instance_double "Runner", options: OpenStruct.new(config_hash: {}, config_file: nil, default_config_file: true)
end
let :config_dir do
File.expand_path(File.join(File.dirname(__FILE__), "../../../fixtures"))
end
subject do
NightcrawlerSwift::CLI::OptParser.new runner
end
describe "options" do
["-v", "--version"].each do |switch|
context switch do
it "prints the version number" do
allow(runner).to receive(:argv).and_return([switch])
expect(runner).to receive(:log).with(NightcrawlerSwift::VERSION)
expect { subject.parse! }.to raise_error SystemExit
end
end
end
["-h", "--help"].each do |switch|
context switch do
it "prints the help" do
allow(runner).to receive(:argv).and_return([switch])
expect(runner).to receive(:log).with(subject.help)
expect { subject.parse! }.to raise_error SystemExit
end
end
end
["-c PATH", "--config=PATH"].each do |switch|
context switch do
let :config_file do
File.join(config_dir, "#{NightcrawlerSwift::CLI::CONFIG_FILE}-test")
end
let :command do
switch.gsub(/PATH/, config_file)
end
before do
File.open(config_file, "w") {|f| f.write("test")}
end
after do
File.delete(config_file) if File.exist?(config_file)
end
it "configures the config_file" do
allow(runner).to receive(:log)
allow(runner).to receive(:argv).and_return([command])
subject.parse!
expect(runner.options.config_file).to eql config_file
expect(runner.options.default_config_file).to eql false
end
context "when the config file does not exist" do
let :invalid_filename do
"invalid-file"
end
let :invalid_filepath do
File.expand_path(File.join(File.dirname(__FILE__), "../../../../", invalid_filename))
end
let :command do
switch.gsub(/PATH/, invalid_filename)
end
it "prints the error and exit with a failure" do
expect(runner).to receive(:argv).and_return([command])
expect(runner).to receive(:log).with("Error: No such file or directory - #{invalid_filepath}")
exited = false
begin
subject.parse!
rescue SystemExit => e
exited = true
expect(e.status).to eql 1
ensure
expect(exited).to eql true
end
end
end
end
end
["-b NAME", "--bucket=NAME"].each do |switch|
context switch do
let :bucket_name do
"rogue"
end
let :command do
switch.gsub(/NAME/, bucket_name)
end
it "configures the bucket name" do
allow(runner).to receive(:argv).and_return([command])
allow(runner).to receive(:log)
subject.parse!
expect(runner.options.config_hash).to include(bucket: bucket_name)
end
end
end
["--max-age=VALUE"].each do |switch|
context switch do
let :max_age do
300
end
let :command do
switch.gsub(/VALUE/, max_age.to_s)
end
it "configures the max-age" do
allow(runner).to receive(:argv).and_return([command])
allow(runner).to receive(:log)
subject.parse!
expect(runner.options.config_hash).to include(max_age: max_age)
end
end
end
["--content-encoding=VALUE"].each do |switch|
context switch do
let(:content_encoding) { 'gzip' }
let(:command) { switch.gsub(/VALUE/, content_encoding) }
it "configures the content-encoding" do
allow(runner).to receive(:argv).and_return([command])
allow(runner).to receive(:log)
subject.parse!
expect(runner.options.config_hash).to include(content_encoding: content_encoding)
end
end
end
["--no-cache"].each do |switch|
context switch do
it "configures use_cache with false" do
allow(runner).to receive(:argv).and_return([switch])
subject.parse!
expect(runner.options.use_cache).to eql false
end
end
end
end
describe "#parse!" do
before do
allow(runner).to receive(:argv).and_return([])
end
it "calls method 'parse!' in OptionParser with runner argv" do
expect(subject.parser).to receive(:parse!).with(runner.argv)
subject.parse!
end
end
describe "#help" do
it "calls method 'help' in OptionParser" do
expect(subject.parser).to receive(:help)
subject.help
end
end
end
| 27.558659 | 115 | 0.58585 |
7991f5bd6bf358ae93b25cde73026500473e6621 | 7,601 | HERE = File.dirname(__FILE__)
$LOAD_PATH << "#{HERE}/../../lib/"
UNIX_SOCKET_NAME = File.join('/tmp', 'memcached')
JRUBY = defined?(JRUBY_VERSION)
require 'ffi/times' if JRUBY
require 'memcached'
require 'benchmark'
require 'rubygems'
require 'ruby-debug' if ENV['DEBUG'] && !JRUBY
if ENV['PROFILE']
require 'ruby-prof'
require 'fileutils'
FileUtils.mkdir_p 'profiles'
end
begin; require 'memory'; rescue LoadError; end
puts `uname -a`
puts `ruby -v`
puts `env | egrep '^RUBY'`
puts "Ruby #{RUBY_VERSION}p#{RUBY_PATCHLEVEL}"
[
["memcached"],
["remix-stash", "remix/stash"],
[JRUBY ? "jruby-memcache-client" : "memcache-client", "memcache"],
["kgio"], ["dalli"]
].each do |gem_name, requirement|
begin
require requirement || gem_name
gem gem_name
puts "Loaded #{gem_name} #{Gem.loaded_specs[gem_name].version.to_s rescue nil}"
rescue LoadError
end
end
class Remix::Stash
# Remix::Stash API doesn't let you set servers
@@clusters = {:default => Remix::Stash::Cluster.new(['127.0.0.1:43042', '127.0.0.1:43043'])}
end
class Dalli::ClientCompat < Dalli::Client
def set(*args)
super(*args[0..2])
end
def get(*args)
super(args.first)
end
def get_multi(*args)
super(args.first)
end
def append(*args)
super
rescue Dalli::DalliError
end
def prepend(*args)
super
rescue Dalli::DalliError
end
def exist?(key)
!get(key).nil?
end
end
class Bench
def initialize(loops = nil, stack_depth = nil)
@loops = (loops || 50000).to_i
@stack_depth = (stack_depth || 0).to_i
puts "PID is #{Process.pid}"
puts "Loops is #{@loops}"
puts "Stack depth is #{@stack_depth}"
@m_value = Marshal.dump(
@small_value = ["testing"])
@m_large_value = Marshal.dump(
@large_value = [{"test" => "1", "test2" => "2", Object.new => "3", 4 => 4, "test5" => 2**65}] * 2048)
puts "Small value size is: #{@m_value.size} bytes"
puts "Large value size is: #{@m_large_value.size} bytes"
@keys = [
@k1 = "Short",
@k2 = "Sym1-2-3::45" * 8,
@k3 = "Long" * 40,
@k4 = "Medium" * 8,
@k5 = "Medium2" * 8,
@k6 = "Long3" * 40]
reset_servers
reset_clients
Benchmark.bm(36) do |x|
@benchmark = x
end
end
def run(level = @stack_depth)
level > 0 ? run(level - 1) : run_without_recursion
end
private
def reset_servers
system("ruby #{HERE}/../setup.rb")
sleep(1)
end
def reset_clients
# Other clients
@clients = {
"mclient:ascii" => MemCache.new(['127.0.0.1:43042', '127.0.0.1:43043']),
"stash:bin" => Remix::Stash.new(:root),
"dalli:bin" => Dalli::ClientCompat.new(['127.0.0.1:43042', '127.0.0.1:43043'], :marshal => false, :threadsafe => false)}
# Us
@clients.merge!({
"libm:ascii" => Memcached::Client.new(
['127.0.0.1:43042', '127.0.0.1:43043'],
:buffer_requests => false, :no_block => false, :prefix_key => "namespace"),
"libm:ascii:pipeline" => Memcached::Client.new(
['127.0.0.1:43042', '127.0.0.1:43043'],
:no_block => true, :buffer_requests => true, :noreply => true, :prefix_key => "namespace"),
"libm:ascii:udp" => Memcached::Client.new(
["#{UNIX_SOCKET_NAME}0", "#{UNIX_SOCKET_NAME}1"],
:buffer_requests => false, :no_block => false, :prefix_key => "namespace"),
"libm:bin" => Memcached::Client.new(
['127.0.0.1:43042', '127.0.0.1:43043'],
:buffer_requests => false, :no_block => false, :prefix_key => "namespace", :binary_protocol => true),
"libm:bin:buffer" => Memcached::Client.new(
['127.0.0.1:43042', '127.0.0.1:43043'],
:no_block => true, :buffer_requests => true, :prefix_key => "namespace", :binary_protocol => true)})
end
def benchmark_clients(test_name, populate_keys = true)
return if ENV["TEST"] and !test_name.include?(ENV["TEST"])
@clients.keys.sort.each do |client_name|
next if ENV["CLIENT"] and !client_name.include?(ENV["CLIENT"])
next if client_name == "stash" and test_name == "set-large" # Don't let stash break the world
client = @clients[client_name]
begin
if populate_keys
client.set @k1, @m_value
client.set @k2, @m_value
client.set @k3, @m_value
else
client.delete @k1
client.delete @k2
client.delete @k3
end
# Force any JITs to run
10003.times { yield client }
GC.disable if !JRUBY
RubyProf.start if ENV['PROFILE']
@benchmark.report("#{test_name}: #{client_name}") { @loops.times { yield client } }
if ENV['PROFILE']
prof = RubyProf::MultiPrinter.new(RubyProf.stop)
prof.print(:path => 'profiles', :profile => "#{test_name}-#{client_name.gsub(':','-')}")
end
rescue Exception => e
# FIXME: stop swallowing errors
puts "#{test_name}: #{client_name} => #{e.inspect}" if ENV["DEBUG"]
reset_clients
end
GC.enable if !JRUBY
end
puts
end
def benchmark_hashes(hashes, test_name)
hashes.each do |hash_name, int|
@m = Memcached::Rails.new(:hash => hash_name)
@benchmark.report("#{test_name}:#{hash_name}") do
(@loops * 5).times { yield int }
end
end
end
def run_without_recursion
benchmark_clients("set") do |c|
c.set @k1, @m_value
c.set @k2, @m_value
c.set @k3, @m_value
end
benchmark_clients("get") do |c|
c.get @k1
c.get @k2
c.get @k3
end
benchmark_clients("get-multi") do |c|
c.get_multi @keys
end
benchmark_clients("append") do |c|
c.append @k1, @m_value
c.append @k2, @m_value
c.append @k3, @m_value
end
benchmark_clients("prepend") do |c|
c.prepend @k1, @m_value
c.prepend @k2, @m_value
c.prepend @k3, @m_value
end
benchmark_clients("delete") do |c|
c.delete @k1
c.delete @k2
c.delete @k3
end
benchmark_clients("exist") do |c|
c.exist? @k1
c.exist? @k2
c.exist? @k3
end
benchmark_clients("get-missing", false) do |c|
c.get @k1
c.get @k2
c.get @k3
end
benchmark_clients("append-missing", false) do |c|
c.append @k1, @m_value
c.append @k2, @m_value
c.append @k3, @m_value
end
benchmark_clients("prepend-missing", false) do |c|
c.prepend @k1, @m_value
c.prepend @k2, @m_value
c.prepend @k3, @m_value
end
benchmark_clients("exist-missing", false) do |c|
c.exist? @k1
c.exist? @k2
c.exist? @k3
end
benchmark_clients("set-large") do |c|
c.set @k1, @m_large_value
c.set @k2, @m_large_value
c.set @k3, @m_large_value
end
benchmark_clients("get-large") do |c|
c.get @k1
c.get @k2
c.get @k3
end
## TODO: benchmark this in another file
# if defined?(Memcached) && !ENV['TEST'] && !ENV['CLIENT']
# benchmark_hashes(Memcached::HASH_VALUES, "hash") do |i|
# Rlibmemcached.memcached_generate_hash_rvalue(@k1, i)
# Rlibmemcached.memcached_generate_hash_rvalue(@k2, i)
# Rlibmemcached.memcached_generate_hash_rvalue(@k3, i)
# Rlibmemcached.memcached_generate_hash_rvalue(@k4, i)
# Rlibmemcached.memcached_generate_hash_rvalue(@k5, i)
# Rlibmemcached.memcached_generate_hash_rvalue(@k6, i)
# end
# end
end
end
Bench.new(ENV["LOOPS"], ENV["STACK_DEPTH"]).run
Process.memory.each do |key, value|
puts "#{key}: #{value/1024.0}M"
end if Process.respond_to? :memory
| 27.049822 | 126 | 0.600974 |
26b36d42fea4d80ce910f994a23602993e84ddd6 | 2,249 | module Onecloud
# Operations with DNS
module DNS # TODO: Rename to 'Domains'
# Get record by ID
def dns_by_id(record_id)
get("dns/record/#{record_id}")
end
def domain_by_id(domain_id)
get("dns/#{domain_id}")
end
# Update CNAME record
def dns_update_cname(record_id, params)
put("dns/recordname/#{record_id}", params)
end
# Update MX record
def dns_update_mx(record_id, params)
put("dns/recordmx/#{record_id}", params)
end
# Update NS record
def dns_update_ns(record_id, params)
put("dns/recordns/#{record_id}", params)
end
# Update SRV record
def dns_update_srv(record_id, params)
put("dns/recordsrc/#{record_id}", params)
end
# Update TXT record
def dns_update_txt(record_id, params)
put("dns/recordtxt/#{record_id}", params)
end
# Update A record
def dns_update_a(record_id, params)
put("dns/recorda/#{record_id}", params)
end
# Update AAAA record
def dns_update_aaaa(record_id, params)
put("dns/recordaaaa/#{record_id}", params)
end
# Create CNAME record
def dns_create_cname(params)
post('dns/recordcname', params)
end
# Create MX record
def dns_create_mx(params)
post('dns/recordmx', params)
end
# Create NS record
def dns_create_ns(params)
post('dns/recordns', params)
end
# Create SRV record
def dns_create_srv(params)
post('dns/recordsrc', params)
end
# Create TXT record
def dns_create_txt(params)
post('dns/recordtxt', params)
end
# Create A record
def dns_create_a(params)
post('dns/recorda', params)
end
# Create AAAA record
def dns_create_aaaa(params)
post('dns/recordaaaa', params)
end
# Create new domain
def add_domain(params)
post('dns', params)
end
# List of all domains
def domains
get('dns') # TODO: alias: all_dns, dns, dns_list
end
# Delete domain by ID
def remove_domain(domain_id)
delete("dns/#{domain_id}")
end
# Remove record for domain by ID
def remove_domain_record(domain_id, record_id)
delete("dns/#{domain_id}/#{record_id}")
end
end
end
| 21.625 | 54 | 0.635394 |
1c2e0079f8d02d388ff77e040974152b32aef815 | 652 | # frozen_string_literal: true
module Api
module Internal
class StatisticsController < Api::Internal::ApplicationController
include TimeZoneHelper
def user_heatmap(username, start_date, end_date)
start_date = Time.parse(start_date)
end_date = Time.parse(end_date)
user = User.published.find_by!(username: username)
time_zone = local_time_zone.presence || user.time_zone
@days = user.records.between_times(start_date, end_date).
group_by_day(:created_at, time_zone: time_zone).count.
map { |date, val| [date.to_time.to_i, val] }.
to_h
end
end
end
end
| 29.636364 | 69 | 0.67638 |
91078a14e1936f049f8dfd515daab652b19fbb43 | 688 | module Hashie
# Hash of great sloth
#
# Hashie::Mash.send(:include, Hashie::Lazy)
#
# local_variable = "I'm fat and lazy"
#
# hash = Hashie::Mash.new
# hash.lazy :lazy_attribute do
# local_variable # this block is evaluated later
# end
# hash.lazy_attribute # "I'm fat and lazy"
module Lazy
def lazy(key, &blk)
lazy_attributes << key.to_sym
self[key] = blk
self
end
def lazy_attributes
@lazy_attributes ||= Set.new
end
def [](key)
value = super
lazy_attributes.include?(key.to_sym) ? value.call : value
end
def delete(key)
lazy_attributes.delete(key.to_sym)
super
end
end
end | 20.235294 | 63 | 0.616279 |
f8b051571c8361e4e09317fdb47797957df8716c | 725 | class LessonsController < ApplicationController
def create
@lesson = Lesson.create_with_datetime(lesson_params, current_user)
@invitees = params[:user][:id]
@language_problem = LanguageProblem.find_language_problem(params[:language_id], params[:problem][:id])
@lesson.build_room(:title => @lesson.description, :language_problem => @language_problem)
if @lesson.save
Invitation.create_invitations(@lesson, @invitees)
redirect_to progress_path(@lesson.language.slug)
else
redirect_to :back
end
end
def edit
end
def update
end
def delete
end
private
def lesson_params
params.require(:lesson).permit(:description, :schedule, :time_zone)
end
end
| 23.387097 | 106 | 0.717241 |
797d5d185bb20faffd746a4a36de6c4eeeb6a51e | 413 | module HoganAssets
class Engine < ::Rails::Engine
initializer 'sprockets.hogan', group: :all do |_app|
HoganAssets::Config.load_yml! if HoganAssets::Config.yml_exists?
Rails.application.config.assets.configure do |env|
HoganAssets::Config.template_extensions.each do |ext|
env.register_engine(".#{ext}", Tilt, silence_deprecation: true)
end
end
end
end
end
| 31.769231 | 73 | 0.682809 |
ac0db510ff2c80392396e76c6b82563b91169789 | 2,915 | # frozen_string_literal: true
require "forwardable"
module Archimate
module DataModel
# A base string type for multi-language strings.
class LangString
include Comparable
include Comparison
extend Forwardable
def_delegators :@default_text, :strip, :tr, :+, :gsub, :sub, :downcase, :empty?, :split, :size, :include?
# @!attribute [r] lang_hash
# @return [Hash]
model_attr :lang_hash
# @!attribute [r] default_lang
# @return [String, NilClass]
model_attr :default_lang
# @!attribute [r] default_text
# @return [String]
model_attr :default_text
def self.string(str, lang = nil)
return nil if !str || str.strip.empty?
new(str, default_lang: lang)
end
# @param str [String, LangString] optional shortcut to set define this LangString
# @param lang_hash [Hash{Symbol => Object}] attributes
# @param default_lang [String] optional setting of the default language
# @raise [Struct::Error] if the given attributes don't conform {#schema}
# with given {# # constructor_type}
def initialize(str = nil, lang_hash: {}, default_lang: nil)
@lang_hash = lang_hash
@default_lang = default_lang || lang_hash.keys.first
@default_text = str || lang_hash.fetch(@default_lang, nil)
case str
when String
@lang_hash[@default_lang] = @default_text = str.strip
when LangString
@lang_hash = str.lang_hash
@default_lang = str.default_lang
@default_text = str.default_text
else
@lang_hash[default_lang] = @default_text if @default_text
end
end
def langs
@lang_hash.keys
end
def to_str
to_s
end
def to_s
@default_text ||= @lang_hash.fetch(default_lang) do |key|
@lang_hash.fetch(nil, nil) if key
end
end
def by_lang(lang)
lang_hash.fetch(lang, nil)
end
def text
to_s
end
def lang
default_lang
end
def ==(other)
if other.is_a?(String)
to_s == other
else
super
end
end
def =~(other)
str = to_s
if other.is_a?(Regexp)
other =~ str
else
Regexp.new(Regexp.escape(str)) =~ other
end
end
def <=>(other)
to_s <=> other.to_s
end
def merge(other)
return unless other
other.lang_hash.each do |k, v|
if @lang_hash.include?(k)
@lang_hash[k] = [@lang_hash[k], v].join("\n") if @lang_hash[k] != other.lang_hash[k]
else
@lang_hash[k] = v
end
end
@default_lang = @default_lang || other.default_lang || @lang_hash.keys.first
@default_text = @lang_hash[@default_lang]
end
end
end
end
| 25.79646 | 111 | 0.5753 |
03efbf96bfae61cc891ba57fea459f3323e3b2dc | 2,349 | class Deno < Formula
desc "Command-line JavaScript / TypeScript engine"
homepage "https://deno.land/"
url "https://github.com/denoland/deno.git",
:tag => "v0.21.0",
:revision => "4e88ba9a114279b3969d5ccca1cca0f74c8fc1fd"
bottle do
cellar :any_skip_relocation
sha256 "756c9df9b5e32392768d7c7e3755d0dd98dbeb14079aef7e1af1c82d20c25b96" => :catalina
sha256 "f44bd18decbca28176aee495a58ee58f03181fec2768ec3f73f10968c62a4aad" => :mojave
sha256 "0601da71e421b3935f18e15e99adc19ac6c9c10146b10311b8202cd02b12088c" => :high_sierra
end
depends_on "llvm" => :build if DevelopmentTools.clang_build_version < 1100
depends_on "ninja" => :build
depends_on "rust" => :build
depends_on :xcode => ["10.0", :build] # required by v8 7.9+
resource "gn" do
url "https://gn.googlesource.com/gn.git",
:revision => "972ed755f8e6d31cae9ba15fcd08136ae1a7886f"
end
def install
# Build gn from source (used as a build tool here)
(buildpath/"gn").install resource("gn")
cd "gn" do
system "python", "build/gen.py"
system "ninja", "-C", "out/", "gn"
end
# env args for building a release build with our clang, ninja and gn
ENV["DENO_NO_BINARY_DOWNLOAD"] = "1"
ENV["DENO_GN_PATH"] = buildpath/"gn/out/gn"
args = %W[
clang_use_chrome_plugins=false
mac_deployment_target="#{MacOS.version}"
treat_warnings_as_errors=false
]
if DevelopmentTools.clang_build_version < 1100
# build with llvm and link against system libc++ (no runtime dep)
args << "clang_base_path=\"#{Formula["llvm"].prefix}\""
ENV.remove "HOMEBREW_LIBRARY_PATHS", Formula["llvm"].opt_lib
else # build with system clang
args << "clang_base_path=\"/usr/\""
end
ENV["DENO_BUILD_ARGS"] = args.join(" ")
cd "cli" do
system "cargo", "install", "-vv", "--root", prefix, "--path", "."
end
# Install bash and zsh completion
output = Utils.popen_read("#{bin}/deno completions bash")
(bash_completion/"deno").write output
output = Utils.popen_read("#{bin}/deno completions zsh")
(zsh_completion/"_deno").write output
end
test do
(testpath/"hello.ts").write <<~EOS
console.log("hello", "deno");
EOS
hello = shell_output("#{bin}/deno run hello.ts")
assert_includes hello, "hello deno"
end
end
| 33.557143 | 93 | 0.674755 |
382be769a9d86fda97811cb92043a2167c906bcb | 1,414 | class Viewvc < Formula
desc "Browser interface for CVS and Subversion repositories"
homepage "http://www.viewvc.org"
url "https://github.com/viewvc/viewvc/releases/download/1.2.1/viewvc-1.2.1.tar.gz"
sha256 "afbc2d35fc0469df90f5cc2e855a9e99865ae8c22bf21328cbafcb9578a23e49"
license "BSD-2-Clause"
bottle do
cellar :any_skip_relocation
rebuild 1
sha256 "6e18a6a9766105bad19b6030401ef95c3d8f634c86df22134a2fae667ef7a6e7" => :big_sur
sha256 "d56de2b10e8bd8f161071b9d39ae435ee1fc70e4be5056b39d48dec7e77f185e" => :catalina
sha256 "6cd2fbb98cdc1ff4f689aae5ebea8cf4bee6f078671f812c492758274f22a5d6" => :mojave
sha256 "19c07a79667814ccb1b14b6214a3d5fcca65ec31381e6e46a5db3ac3f72fc2d4" => :high_sierra
end
depends_on :macos # Due to Python 2 (https://github.com/viewvc/viewvc/issues/138)
def install
system "python", "./viewvc-install", "--prefix=#{libexec}", "--destdir="
Pathname.glob(libexec/"bin/*") do |f|
next if f.directory?
bin.install_symlink f => "viewvc-#{f.basename}"
end
end
test do
port = free_port
begin
pid = fork do
exec "#{bin}/viewvc-standalone.py", "--port=#{port}"
end
sleep 2
output = shell_output("curl -s http://localhost:#{port}/viewvc")
assert_match "[ViewVC] Repository Listing", output
ensure
Process.kill "SIGTERM", pid
Process.wait pid
end
end
end
| 31.422222 | 93 | 0.712871 |
616613e450b41265e9ea6cd7109d1b37f79d3cb6 | 933 | require_relative '../../test_helper'
module JPush
module Push
class AudienceTest < JPush::Test
def setup
@audience = Audience.new
end
def test_set_tag
result = @audience.set_tag('jpush').to_hash
assert_equal 1, result.size
assert_true result.has_key?(:tag)
assert_true result[:tag].include?('jpush')
end
def test_sets
result = @audience.
set_tag(['jpush', 'j', 'p', 'u', 's', 'h']).
set_tag_and('jpush').
set_alias('jpush').
set_registration_id('jpush').
to_hash
assert_equal 4, result.size
assert_true result[:tag].include?('jpush')
assert_true result[:tag_and].include?('jpush')
assert_true result[:alias].include?('jpush')
assert_true result[:registration_id].include?('jpush')
assert_equal 6, result[:tag].size
end
end
end
end
| 23.923077 | 62 | 0.587353 |
f7c1becb7ca91424b3f3f2d468c8626248a3206e | 1,894 | class Model
def initialize(hash={})
@attributes = hash
end
def read_attribute_for_serialization(name)
if name == :id || name == 'id'
id
else
@attributes[name]
end
end
def id
@attributes[:id] || @attributes['id'] || object_id
end
def method_missing(meth, *args)
if meth.to_s =~ /^(.*)=$/
@attributes[$1.to_sym] = args[0]
elsif @attributes.key?(meth)
@attributes[meth]
else
super
end
end
end
class Profile < Model
end
class ProfileSerializer < ActiveModel::Serializer
attributes :name, :description
urls :posts, :comments
end
class ProfilePreviewSerializer < ActiveModel::Serializer
attributes :name
urls :posts, :comments
end
Post = Class.new(Model)
Comment = Class.new(Model)
Author = Class.new(Model)
Bio = Class.new(Model)
Blog = Class.new(Model)
Role = Class.new(Model)
PostSerializer = Class.new(ActiveModel::Serializer) do
attributes :title, :body, :id
has_many :comments
belongs_to :author
url :comments
end
CommentSerializer = Class.new(ActiveModel::Serializer) do
attributes :id, :body
belongs_to :post
belongs_to :author
end
AuthorSerializer = Class.new(ActiveModel::Serializer) do
attributes :id, :name
has_many :posts, embed: :ids
has_many :roles, embed: :ids
belongs_to :bio
end
RoleSerializer = Class.new(ActiveModel::Serializer) do
attributes :id, :name
belongs_to :author
end
BioSerializer = Class.new(ActiveModel::Serializer) do
attributes :id, :content
belongs_to :author
end
BlogSerializer = Class.new(ActiveModel::Serializer) do
attributes :id, :name
belongs_to :writer
has_many :articles
end
PaginatedSerializer = Class.new(ActiveModel::Serializer::ArraySerializer) do
def json_key
'paginated'
end
end
AlternateBlogSerializer = Class.new(ActiveModel::Serializer) do
attribute :id
attribute :name, key: :title
end
| 18.38835 | 76 | 0.708025 |
289cb44f1e8a0014f3848e109abd371a1f5d14f2 | 920 | # frozen_string_literal: true
module BroadcastMessagesHelper
def broadcast_message(message)
return unless message.present?
content_tag :div, class: 'broadcast-message', style: broadcast_message_style(message) do
icon('bullhorn') << ' ' << render_broadcast_message(message)
end
end
def broadcast_message_style(broadcast_message)
style = []
if broadcast_message.color.present?
style << "background-color: #{broadcast_message.color}"
end
if broadcast_message.font.present?
style << "color: #{broadcast_message.font}"
end
style.join('; ')
end
def broadcast_message_status(broadcast_message)
if broadcast_message.active?
'Active'
elsif broadcast_message.ended?
'Expired'
else
'Pending'
end
end
def render_broadcast_message(broadcast_message)
Banzai.render_field(broadcast_message, :message).html_safe
end
end
| 23 | 92 | 0.711957 |
1cbd95ca4d673a7fdda00ae97af2b0a694fefd54 | 801 | class TastingsController < ApplicationController
# redirect back to events show_quiz method
def create
event_wine = EventWine.find(params[:event_wine_id])
event = event_wine.event
tasting = current_user.tastings.create(tasting_params)
# TO DO: refactor this conditional and test with wine_bringer = current_user
# and wine_bringer != current_user states
# if tasting.wine == event.event_wines.find_by(wine_bringer: current_user).wine
# tasting.update(is_blind: false)
# end
redirect_to "/events/#{event.id}/quiz"
end
private
def tasting_params
params.permit([:event_wine_id, :red_fruits, :white_fruits, :fruit_condition, :minerality, :oak, :dry, :acid, :tannin, :alcohol, :climate, :country, :red_grape, :white_grape, :tasting_notes])
end
end
| 36.409091 | 194 | 0.734082 |
1acb7fd733dfe5f7264a78ae0dd6a0369055014f | 198 | component 'rubygem-rubyntlm' do |pkg, settings, platform|
pkg.version '0.6.2'
pkg.md5sum 'e74146db2e08c5254d15d63f0befcc78'
instance_eval File.read('configs/components/_base-rubygem.rb')
end
| 28.285714 | 64 | 0.777778 |
62b002138347bcba80cc5435d69a69d60b69dc06 | 722 | require 'fetchers/log_access_fetcher'
module VCAP::CloudController
class LogAccessController < RestController::BaseController
get '/internal/log_access/:guid', :lookup
def lookup(guid)
check_read_permissions!
if roles.admin?
found = LogAccessFetcher.new.app_exists?(guid)
else
allowed_space_guids = membership.space_guids_for_roles([Membership::SPACE_DEVELOPER, Membership::SPACE_MANAGER, Membership::SPACE_AUDITOR, Membership::ORG_MANAGER])
found = LogAccessFetcher.new.app_exists_by_space?(guid, allowed_space_guids)
end
found ? HTTP::OK : HTTP::NOT_FOUND
end
def membership
@membership ||= Membership.new(current_user)
end
end
end
| 30.083333 | 172 | 0.727147 |
5de041f406d47425ed6fb73ba925837187f056ac | 2,962 | API_HOST = "api.openbeerdatabase.local"
# Request
When /^I send an API GET request to (.*)$/ do |path|
get "http://#{API_HOST}#{path}"
end
When /^I send an API POST request to (.*)$/ do |path, body|
post "http://#{API_HOST}#{path}", body, { "CONTENT_TYPE" => "application/json" }
end
When /^I send an API PUT request to (.*)$/ do |path, *body|
put "http://#{API_HOST}#{path}", body.first, { "CONTENT_TYPE" => "application/json" }
end
When /^I send an API DELETE request to (.*)$/ do |path|
delete "http://#{API_HOST}#{path}"
end
# Response
Then /^I should receive a (\d+) response$/ do |status|
last_response.status.should == status
end
Then /^the Location header should be set to (.+)$/ do |page_name|
location = case page_name
when /^the API beer page for "([^"]+)"$/
beer = Beer.find_by_name!($1)
v1_beer_url(beer, format: :json, host: API_HOST)
when /^the API brewery page for "([^"]+)"$/
brewery = Brewery.find_by_name!($1)
v1_brewery_url(brewery, format: :json, host: API_HOST)
end
last_response.headers["Location"].should == location
end
Then /^I should see the following JSON response:$/ do |expected_json|
require "json"
expected = JSON.pretty_generate(JSON.parse(expected_json))
actual = JSON.pretty_generate(JSON.parse(last_response.body))
expected.should == actual
end
Then /^I should see the following JSONP response with an? "([^"]*)" callback:$/ do |callback, expected_json|
require "json"
expected = JSON.pretty_generate(JSON.parse(expected_json))
actual = JSON.pretty_generate(JSON.parse(last_response.body.match(/^#{callback}\((.+)\)$/)[1]))
expected.should == actual
end
# Beer
When /^I create the following beers? via the API for the "([^"]*)" brewery using the "([^"]*)" token:$/ do |brewery_name, token, table|
brewery = Brewery.find_by_name!(brewery_name)
table.hashes.each do |hash|
step %{I send an API POST request to /v1/beers.json?token=#{token}}, {
brewery_id: brewery.id,
beer: hash
}.to_json
end
end
When /^I update the "([^"]*)" beer via the API using the "([^"]*)" token:$/ do |name, token, table|
beer = Beer.find_by_name!(name)
table.hashes.each do |hash|
step %{I send an API PUT request to /v1/beers/#{beer.id}.json?token=#{token}}, { beer: hash }.to_json
end
end
# Brewery
When /^I create the following (?:brewery|breweries) via the API using the "([^"]*)" token:$/ do |token, table|
table.hashes.each do |hash|
step %{I send an API POST request to /v1/breweries.json?token=#{token}}, { brewery: hash }.to_json
end
end
When /^I update the "([^"]*)" brewery via the API using the "([^"]*)" token:$/ do |name, token, table|
brewery = Brewery.find_by_name!(name)
table.hashes.each do |hash|
step %{I send an API PUT request to /v1/breweries/#{brewery.id}.json?token=#{token}}, { brewery: hash }.to_json
end
end
| 31.849462 | 135 | 0.640783 |
392f4dcfa70e5b0a0b2fc9a12fb8dfa88ff1c3c0 | 393 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe BreadcrumbItemComponent, type: :component do
pending "add some examples to (or delete) #{__FILE__}"
# it "renders something useful" do
# expect(
# render_inline(described_class.new(attr: "value")) { "Hello, components!" }.css("p").to_html
# ).to include(
# "Hello, components!"
# )
# end
end
| 24.5625 | 99 | 0.669211 |
abef7c7fa70ef83d13e4bb43380f48c52484cb91 | 368 | name 'windows'
maintainer 'Chef Software, Inc.'
maintainer_email '[email protected]'
license 'Apache 2.0'
description 'Provides a set of useful Windows-specific primitives.'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '1.34.8'
supports 'windows'
depends 'chef_handler'
| 36.8 | 72 | 0.663043 |
5dc725e132ca77c7b4706b04b6fbdfb701aa71c3 | 1,620 | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'rex/proto/ntlm/message'
class MetasploitModule < Msf::Auxiliary
include Msf::Exploit::Remote::WinRM
include Msf::Auxiliary::Report
include Msf::Auxiliary::Scanner
def initialize
super(
'Name' => 'WinRM Authentication Method Detection',
'Description' => %q{
This module sends a request to an HTTP/HTTPS service to see if it is a WinRM service.
If it is a WinRM service, it also gathers the Authentication Methods supported.
},
'Author' => [ 'thelightcosine' ],
'License' => MSF_LICENSE
)
deregister_options('USERNAME', 'PASSWORD')
end
def run_host(ip)
resp = winrm_poke
return nil if resp.nil?
if resp.code == 401 and resp.headers['Server'] and resp.headers['Server'].include? "Microsoft-HTTPAPI"
methods = parse_auth_methods(resp)
desc = resp.headers['Server'] + " Authentication Methods: " + methods.to_s
report_service(
:host => ip,
:port => rport,
:proto => 'tcp',
:name => 'winrm',
:info => desc
)
print_good "#{ip}:#{rport}: Negotiate protocol supported" if methods.include? "Negotiate"
print_good "#{ip}:#{rport}: Kerberos protocol supported" if methods.include? "Kerberos"
print_good "#{ip}:#{rport}: Basic protocol supported" if methods.include? "Basic"
else
print_error "#{ip}:#{rport} Does not appear to be a WinRM server"
end
end
end
| 28.421053 | 107 | 0.635185 |
e880af346cab718d3768ff11b113fcc3cff600d8 | 1,933 | require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: "Example User", email: "[email protected]",
password: "foobar", password_confirmation: "foobar")
end
test "should be valid" do
assert @user.valid?
end
test "name should be present" do
@user.name = " "
assert_not @user.valid?
end
test "email should be present" do
@user.email = " "
assert_not @user.valid?
end
test "name should not be too long" do
@user.name = "a" * 51
assert_not @user.valid?
end
test "email should not be too long" do
@user.email = "a" * 244 + "@example.com"
assert_not @user.valid?
end
test "email validation should accept valid addresses" do
invalid_addresses = %w[user@example,com user_at_foo.org user.name@example. foo@bar_baz.com foo@bar+baz.com [email protected]]
invalid_addresses.each do |invalid_address|
@user.email = invalid_address
assert_not @user.valid?, "#{invalid_address.inspect} should be invalid"
end
end
test "email addresses should be unique" do
duplicate_user = @user.dup
duplicate_user.email = @user.email.upcase
@user.save
assert_not duplicate_user.valid?
end
test "email addresses should be save as lower-case" do
mixed_case_email = "[email protected]"
@user.email = mixed_case_email
@user.save
assert_equal mixed_case_email.downcase,@user.reload.email
end
test "password should be present (nonblank)" do
@user.password = @user.password_confirmation = " " * 6
assert_not @user.valid?
end
test "password should have a minimum length" do
@user.password = @user.password_confirmation = "a" * 5
assert_not @user.valid?
end
test "associated microposts should be destroyed" do
@user.save
@user.microposts.create!(content: "Lorem ipsum")
assert_difference 'Micropost.count', -1 do
@user.destroy
end
end
end
| 26.479452 | 124 | 0.685463 |
266bad5941194f4f4b156b6e1ec8773118f42ca6 | 1,628 | class Ripgrep < Formula
desc "Search tool like grep and The Silver Searcher"
homepage "https://github.com/BurntSushi/ripgrep"
url "https://github.com/BurntSushi/ripgrep/archive/12.1.1.tar.gz"
sha256 "2513338d61a5c12c8fea18a0387b3e0651079ef9b31f306050b1f0aaa926271e"
license "Unlicense"
head "https://github.com/BurntSushi/ripgrep.git"
livecheck do
url :stable
strategy :github_latest
end
bottle do
cellar :any
sha256 "0ca7397f9a0ccef6cbb8ff0fd8fb18c6fe86219abaef350e3d7ef248d07440fd" => :big_sur
sha256 "e0147ba489a8d96e33fc8be7e2172c632075d5d31a4f6267c3606e463280e0e3" => :arm64_big_sur
sha256 "60460d422253113af3ed60332104f309638942821c655332211a6bc2213c472c" => :catalina
sha256 "de4b18789f5d9bc4aaa4d906501200ae4ece7a1971dd1b86e2b2d0a2c8e0d764" => :mojave
sha256 "cfea5335bf4eccfb7cd1d93bec234d96bd49dce8d593ea966687f777909ba291" => :high_sierra
end
depends_on "asciidoctor" => :build
depends_on "pkg-config" => :build
depends_on "rust" => :build
depends_on "pcre2"
def install
system "cargo", "install", "--features", "pcre2", *std_cargo_args
# Completion scripts and manpage are generated in the crate's build
# directory, which includes a fingerprint hash. Try to locate it first
out_dir = Dir["target/release/build/ripgrep-*/out"].first
man1.install "#{out_dir}/rg.1"
bash_completion.install "#{out_dir}/rg.bash"
fish_completion.install "#{out_dir}/rg.fish"
zsh_completion.install "complete/_rg"
end
test do
(testpath/"Hello.txt").write("Hello World!")
system "#{bin}/rg", "Hello World!", testpath
end
end
| 36.177778 | 95 | 0.751843 |
9179b9ded461e4b82815ca84f91fb9f453141ff1 | 1,373 | class Chrony < Formula
desc "Versatile implementation of the Network Time Protocol (NTP)"
homepage "https://chrony.tuxfamily.org"
url "https://download.tuxfamily.org/chrony/chrony-4.1.tar.gz"
sha256 "ed76f2d3f9347ac6221a91ad4bd553dd0565ac188cd7490d0801d08f7171164c"
license "GPL-2.0-only"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "90fcce18cd0b68629e37023124cb961ac67c2f36da2bdfaeeeb2f6b146a49b9c"
sha256 cellar: :any_skip_relocation, big_sur: "ecba024c1c74b0f2d8094b06043a6ceafbc4bcd4cba944e3600792789adcfb4b"
sha256 cellar: :any_skip_relocation, catalina: "dfe728a9f5ecc085ba6582a2791e1e6a2f5d2ef609ee4f3da237e4442d016dbe"
sha256 cellar: :any_skip_relocation, mojave: "b908fae19168cb50d7d1fe33e2885ad19ff8bb1e190442aa3ee6ea6c47f4c72f"
sha256 cellar: :any_skip_relocation, x86_64_linux: "b3bf23ccc84b2182fb5e7e05a6e5e212c9241e5e0c4570a67929d8ac0f750a13"
end
depends_on "nettle"
uses_from_macos "libedit"
def install
system "./configure", "--prefix=#{prefix}",
"--localstatedir=#{var}"
system "make", "install"
end
test do
(testpath/"test.conf").write "pool pool.ntp.org iburst\n"
output = shell_output(sbin/"chronyd -Q -f #{testpath}/test.conf 2>&1")
assert_match(/System clock wrong by -?\d+\.\d+ seconds \(ignored\)/, output)
end
end
| 42.90625 | 122 | 0.753095 |
1def33e040449074d6699a2cae1e5968a94af04f | 855 | require 'workers'
# リストの分割数
DIVIDE_NUM = 10
logger = nil
task_pool = Workers::Pool.new(size: DEVIDE_NUM+1, logger: logger, on_exception: nil)
Hoge.where(some_statement).find_in_batches do |list|
# TaskGroup自体がそもそもstate-fullであるため、
# 再利用が出来ない
# ただし、pool自体は再利用が可能
task_group = Workers::TaskGroup.new(pool: task_pool, logger: logger)
sublists = list.each_slice(list.count / DEVIDE_NUM)
sublists.each do |sublist|
task_group.add(max_tries: 1, input: sublist) do |items|
# items自体は、sublistと同じもの
items.map do |item|
# itemを何らかの形に加工する
end
end
end
# これにより、処理が開始されて全処理が完了するまでここでblockingされることになる
unless group.run
# 何かが処理を失敗している
end
result_list = group.tasks.map(&:result).flatten.compact.sort do |a, b|
a.id <=> b.id
end
# あとは、result_listをどう料理するか?だけ
end
| 23.108108 | 85 | 0.678363 |
1cc0792392e037b9b52be96893f296754aecc395 | 305 | class DataExportJob < ActiveJob::Base
queue_as :high
def perform(options={})
ActiveRecord::Base.connection_pool.with_connection do
data_export = DataExport.find_by_id!(options[:id])
data_export.export!
end
rescue Exception => ex
Notification.create(exception: ex)
end
end
| 23.461538 | 57 | 0.721311 |
ab7f0987a2ba635a969a2d05c867ad0ddaf5a054 | 1,121 | # frozen_string_literal: true
require "forwardable"
require "uri"
module RuboCop
module Cop
module Cask
# This cop checks that a cask's homepage ends with a slash
# if it does not have a path component.
class HomepageUrlTrailingSlash < Cop
include OnHomepageStanza
MSG_NO_SLASH = "'%{url}' must have a slash after the domain."
def on_homepage_stanza(stanza)
url_node = stanza.stanza_node.first_argument
url = url_node.str_content
return if url !~ %r{^.+://[^/]+$}
add_offense(url_node, location: :expression,
message: format(MSG_NO_SLASH, url: url))
end
def autocorrect(node)
domain = URI(node.str_content).host
# This also takes URLs like 'https://example.org?path'
# and 'https://example.org#path' into account.
corrected_source = node.source.sub("://#{domain}", "://#{domain}/")
lambda do |corrector|
corrector.replace(node.source_range, corrected_source)
end
end
end
end
end
end
| 27.341463 | 77 | 0.598573 |
01d094365dd2d2ad4f5b72b45091f0d2cd00ffee | 1,496 | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "Backend - Asset (HTML)", type: :feature do
describe "show" do
before { stub_authorization! }
describe "is available" do
let(:resource) { create(:asset, file_name: "amazing.jpg") }
it "finds the Asset file_name" do
visit "/backend/assets/#{resource.id}"
expect(page).to have_content("File Name: amazing.jpg")
end
it "finds the Asset file" do
visit "/backend/assets/#{resource.id}"
expect(page).to have_css(
"img[src^='/uploads/archangel/asset/file/#{resource.id}']"
)
end
it "finds the Asset file_size" do
visit "/backend/assets/#{resource.id}"
expect(page).to have_content("File Size: 442 KB")
end
it "finds the Asset content_type" do
visit "/backend/assets/#{resource.id}"
expect(page).to have_content("Content Type: image/gif")
end
end
describe "is not available" do
it "return 404 when it does not exist" do
visit "/backend/assets/0"
expect(page)
.to have_content("Page not found. Could not find what was requested")
end
it "returns error message when deleted" do
resource = create(:asset, :deleted, file_name: "amazing.jpg")
visit "/backend/assets/#{resource.id}"
expect(page)
.to have_content("Page not found. Could not find what was requested")
end
end
end
end
| 25.793103 | 79 | 0.61631 |
f79c6014783720f685f266906bd0bd51a9f560ca | 931 | #
# Be sure to run `pod spec lint CommonKit.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see https://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |spec|
spec.name = "WJCommonKit"
spec.version = "3.3.5"
spec.summary = "通用框架"
spec.homepage = "https://github.com/18225905675/WJCommonKit"
spec.license = "MIT"
spec.author = { "RuanYunKeji" => "[email protected]" }
spec.platform = :ios, "9.0"
spec.source = { :git => "https://github.com/18225905675/WJCommonKit.git", :tag =>spec.version }
spec.source_files = "Classes/**/*.{h,m}"
spec.requires_arc = true
spec.dependency "Masonry", "~> 1.1.0"
spec.dependency "QMUIKit", "~> 3.1.1"
end
| 30.032258 | 103 | 0.648765 |
610df9f64fc77d6f1968c1457c800f271bb1e0ca | 1,920 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module App
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
end
end | 45.714286 | 99 | 0.726042 |
ed43f857bbbde328602257dbc08742740fcecf75 | 55 | set_unless[:bundler][:apps_path] = "/home/ubuntu/apps"
| 27.5 | 54 | 0.727273 |
1c945916f1e14cf900ea939fe47c93ec3df2a262 | 1,243 | class Ps2eps < Formula
desc "Convert PostScript to EPS files"
homepage "https://www.tm.uka.de/~bless/ps2eps"
url "https://www.tm.uka.de/~bless/ps2eps-1.68.tar.gz"
sha256 "b08f12eed88965d1891261fb70e87c7e3a3f3172ebc31bdb7994a7ce854dd925"
bottle do
cellar :any_skip_relocation
sha256 "55396ec4ff00cfc85c4e34f1f7b872834264d8640677cd430c16b10fe67f2fa9" => :sierra
sha256 "a651d45a267206348a36d213620790b0951e5343070d8613548b80066ec5a584" => :el_capitan
sha256 "99b3838d2a7135d8794e4f48e428bd8afc0f18db8998f071c74faa449591ad7f" => :yosemite
sha256 "01fbee92f6a8534a4618bb94b9d21913f203b42f7abe41023c7c2b2f68775880" => :mavericks
sha256 "4671a8ae732598cbf5c006b7cf6f9924455a8f61dcc660733e14104707974c27" => :mountain_lion
end
depends_on "ghostscript"
def install
system ENV.cc, "src/C/bbox.c", "-o", "bbox"
bin.install "bbox"
(libexec/"bin").install "bin/ps2eps"
(bin/"ps2eps").write <<-EOS.undent
#!/bin/sh
perl -S #{libexec}/bin/ps2eps $*
EOS
share.install "doc/man"
doc.install "doc/pdf", "doc/html"
end
test do
cp test_fixtures("test.ps"), testpath/"test.ps"
system bin/"ps2eps", testpath/"test.ps"
assert (testpath/"test.eps").exist?
end
end
| 34.527778 | 95 | 0.736927 |
ed615aa9401226984ada3112e888a7c72207ecda | 991 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/google_ads/v0/enums/mime_type.proto
require 'google/protobuf'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_message "google.ads.googleads.v0.enums.MimeTypeEnum" do
end
add_enum "google.ads.googleads.v0.enums.MimeTypeEnum.MimeType" do
value :UNSPECIFIED, 0
value :UNKNOWN, 1
value :IMAGE_JPEG, 2
value :IMAGE_GIF, 3
value :IMAGE_PNG, 4
value :FLASH, 5
value :TEXT_HTML, 6
value :PDF, 7
value :MSWORD, 8
value :MSEXCEL, 9
value :RTF, 10
value :AUDIO_WAV, 11
value :AUDIO_MP3, 12
value :HTML5_AD_ZIP, 13
end
end
module Google::Ads::GoogleAds::V0::Enums
MimeTypeEnum = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v0.enums.MimeTypeEnum").msgclass
MimeTypeEnum::MimeType = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v0.enums.MimeTypeEnum.MimeType").enummodule
end
| 31.967742 | 147 | 0.740666 |
3913c2c1f7595deea1cb06186ed316198c6eb58d | 393 | class ApptTimeValidator < ActiveModel::Validator
def validate(appointment)
if appointment.appt_date == DateTime.now.strftime("%Y-%m-%d")
unless appointment.appt_time >= (DateTime.now + 1.hours).strftime("%H:%M")
appointment.errors[:appt_time] << "Time must be at least an hour later than the current time."
end
end
end
end | 35.727273 | 110 | 0.62341 |
38710c549edf27be60696a90ec011d694e73cf8c | 244 | module Rubycritic
module SourceControlSystem
class Double < Base
def revisions_count(_)
"N/A"
end
def date_of_last_commit(_)
nil
end
def revision?
false
end
end
end
end
| 12.842105 | 32 | 0.561475 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.