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
|
---|---|---|---|---|---|
e2f0e3ff1b1493aed80588bda58a464b51a630c6
| 1,087 |
class ApiAssertion < ApplicationRecord
belongs_to :api_response
before_create :set_results
private
def set_results
case kind
when 'Response JSON'
assert_from_response
when 'Status Code'
assert_from_status
end
self.success = api_value ? assert_values : false
rescue JSON::ParserError => e
self.success = false
end
def assert_from_response
response = JSON.parse(api_response.response_body)
self.api_value = fetch_api_value(response)
end
def assert_from_status
self.key = ''
self.api_value = api_response.status_code
end
def assert_values
case comparison
when 'equals'
api_value.to_s == value.to_s
when 'contains'
api_value.to_s.include?(value.to_s)
when 'lesser than'
api_value.to_i < value.to_i
when 'greater than'
api_value.to_i > value.to_i
else
false
end
end
def fetch_api_value(response)
keys = key.scan(/(\d+)|(\w+)/).map do |number, string|
number&.to_i || string
end
keys.empty? ? 'Null' : response.dig(*keys)
end
end
| 20.903846 | 58 | 0.671573 |
e2307639992be0bd9d08f64aec01c61e05aea2bd
| 317 |
# frozen_string_literal: true
control 'Docker service' do
title 'should_not be running and enabled'
describe service('dockerd') do
it { should_not be_enabled }
it { should_not be_running }
end
describe service('docker') do
it { should_not be_enabled }
it { should_not be_running }
end
end
| 21.133333 | 43 | 0.709779 |
8706a971a1aca8fa34e3aa7fd17fec03bba9b8ab
| 1,656 |
# frozen_string_literal: true
module API
# Deployments RESTful API endpoints
class Deployments < Grape::API
include PaginationParams
before { authenticate! }
params do
requires :id, type: String, desc: 'The project ID'
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
desc 'Get all deployments of the project' do
detail 'This feature was introduced in GitLab 8.11.'
success Entities::Deployment
end
params do
use :pagination
optional :order_by, type: String, values: %w[id iid created_at ref], default: 'id', desc: 'Return deployments ordered by `id` or `iid` or `created_at` or `ref`'
optional :sort, type: String, values: %w[asc desc], default: 'asc', desc: 'Sort by asc (ascending) or desc (descending)'
end
# rubocop: disable CodeReuse/ActiveRecord
get ':id/deployments' do
authorize! :read_deployment, user_project
present paginate(user_project.deployments.order(params[:order_by] => params[:sort])), with: Entities::Deployment
end
# rubocop: enable CodeReuse/ActiveRecord
desc 'Gets a specific deployment' do
detail 'This feature was introduced in GitLab 8.11.'
success Entities::Deployment
end
params do
requires :deployment_id, type: Integer, desc: 'The deployment ID'
end
get ':id/deployments/:deployment_id' do
authorize! :read_deployment, user_project
deployment = user_project.deployments.find(params[:deployment_id])
present deployment, with: Entities::Deployment
end
end
end
end
| 34.5 | 168 | 0.674517 |
d53320ad4d1628c6cfd7927bd59fbc6589a3b4b5
| 268 |
##
## Example Test
##
assert("Example#hello") do
t = Example.new "hello"
assert_equal("hello", t.hello)
end
assert("Example#bye") do
t = Example.new "hello"
assert_equal("hello bye", t.bye)
end
assert("Example.hi") do
assert_equal("hi!!", Example.hi)
end
| 14.888889 | 34 | 0.660448 |
39855dc46e685baaf6252605e274914dba5caced
| 798 |
cask :v1 => 'flash' do
version '16.0.0.235'
sha256 'd47bdc510f35e35ecf5260e35f6c86a4750f95b8505841bc10e1b6a1af82d346'
url "http://fpdownload.macromedia.com/get/flashplayer/current/licensing/mac/install_flash_player_#{version.to_i}_osx_pkg.dmg"
homepage 'https://www.adobe.com/products/flashplayer/distribution3.html'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
pkg 'Install Adobe Flash Player.pkg'
uninstall :pkgutil => 'com.adobe.pkg.FlashPlayer',
:delete => '/Library/Internet Plug-Ins/Flash Player.plugin'
zap :delete => [
'~/Library/Caches/Adobe/Flash Player',
'~/Library/Logs/FlashPlayerInstallManager.log',
]
end
| 44.333333 | 127 | 0.680451 |
bf899ab51bda4d75111a8736a4128a2794bfb7dc
| 1,537 |
# Use: it { should accept_nested_attributes_for(:association_name).and_accept({valid_values => true}).but_reject({ :reject_if_nil => nil })}
RSpec::Matchers.define :accept_nested_attributes_for do |association|
match do |model|
@model = model
@nested_att_present = model.respond_to?("#{association}_attributes=".to_sym)
if @nested_att_present && @reject
model.send("#{association}_attributes=".to_sym,[@reject])
@reject_success = model.send("#{association}").empty?
end
if @nested_att_present && @accept
model.send("#{association}_attributes=".to_sym,[@accept])
@accept_success = ! (model.send("#{association}").empty?)
end
@nested_att_present && ( @reject.nil? || @reject_success ) && ( @accept.nil? || @accept_success )
end
failure_message_for_should do
messages = []
messages << "expected #{@model.class} to accept nested attributes for #{association}" unless @nested_att_present
messages << "expected #{@model.class} to reject values #{@reject.inspect} for association #{association}" unless @reject_success
messages << "expected #{@model.class} to accept values #{@accept.inspect} for association #{association}" unless @accept_success
messages.join(", ")
end
description do
desc = "accept nested attributes for #{expected}"
if @reject
desc << ", but reject if attributes are #{@reject.inspect}"
end
end
chain :but_reject do |reject|
@reject = reject
end
chain :and_accept do |accept|
@accept = accept
end
end
| 38.425 | 140 | 0.688354 |
7a381cb094868c0382857eeac38afc5e8354c396
| 32,755 |
# 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 ResellerV1
# JSON template for address of a customer.
class Address
include Google::Apis::Core::Hashable
# A customer's physical address. An address can be composed of one to three
# lines. The `addressline2` and `addressLine3` are optional.
# Corresponds to the JSON property `addressLine1`
# @return [String]
attr_accessor :address_line1
# Line 2 of the address.
# Corresponds to the JSON property `addressLine2`
# @return [String]
attr_accessor :address_line2
# Line 3 of the address.
# Corresponds to the JSON property `addressLine3`
# @return [String]
attr_accessor :address_line3
# The customer contact's name. This is required.
# Corresponds to the JSON property `contactName`
# @return [String]
attr_accessor :contact_name
# For `countryCode` information, see the ISO 3166 country code elements. Verify
# that country is approved for resale of Google products. This property is
# required when creating a new customer.
# Corresponds to the JSON property `countryCode`
# @return [String]
attr_accessor :country_code
# Identifies the resource as a customer address. Value: `customers#address`
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# An example of a `locality` value is the city of `San Francisco`.
# Corresponds to the JSON property `locality`
# @return [String]
attr_accessor :locality
# The company or company division name. This is required.
# Corresponds to the JSON property `organizationName`
# @return [String]
attr_accessor :organization_name
# A `postalCode` example is a postal zip code such as `94043`. This property is
# required when creating a new customer.
# Corresponds to the JSON property `postalCode`
# @return [String]
attr_accessor :postal_code
# An example of a `region` value is `CA` for the state of California.
# Corresponds to the JSON property `region`
# @return [String]
attr_accessor :region
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@address_line1 = args[:address_line1] if args.key?(:address_line1)
@address_line2 = args[:address_line2] if args.key?(:address_line2)
@address_line3 = args[:address_line3] if args.key?(:address_line3)
@contact_name = args[:contact_name] if args.key?(:contact_name)
@country_code = args[:country_code] if args.key?(:country_code)
@kind = args[:kind] if args.key?(:kind)
@locality = args[:locality] if args.key?(:locality)
@organization_name = args[:organization_name] if args.key?(:organization_name)
@postal_code = args[:postal_code] if args.key?(:postal_code)
@region = args[:region] if args.key?(:region)
end
end
# JSON template for the ChangePlan rpc request.
class ChangePlanRequest
include Google::Apis::Core::Hashable
# Google-issued code (100 char max) for discounted pricing on subscription plans.
# Deal code must be included in `changePlan` request in order to receive
# discounted rate. This property is optional. If a deal code has already been
# added to a subscription, this property may be left empty and the existing
# discounted rate will still apply (if not empty, only provide the deal code
# that is already present on the subscription). If a deal code has never been
# added to a subscription and this property is left blank, regular pricing will
# apply.
# Corresponds to the JSON property `dealCode`
# @return [String]
attr_accessor :deal_code
# Identifies the resource as a subscription change plan request. Value: `
# subscriptions#changePlanRequest`
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# The `planName` property is required. This is the name of the subscription's
# payment plan. For more information about the Google payment plans, see API
# concepts. Possible values are: - `ANNUAL_MONTHLY_PAY` - The annual commitment
# plan with monthly payments *Caution: *`ANNUAL_MONTHLY_PAY` is returned as `
# ANNUAL` in all API responses. - `ANNUAL_YEARLY_PAY` - The annual commitment
# plan with yearly payments - `FLEXIBLE` - The flexible plan - `TRIAL` - The 30-
# day free trial plan
# Corresponds to the JSON property `planName`
# @return [String]
attr_accessor :plan_name
# This is an optional property. This purchase order (PO) information is for
# resellers to use for their company tracking usage. If a `purchaseOrderId`
# value is given it appears in the API responses and shows up in the invoice.
# The property accepts up to 80 plain text characters.
# Corresponds to the JSON property `purchaseOrderId`
# @return [String]
attr_accessor :purchase_order_id
# JSON template for subscription seats.
# Corresponds to the JSON property `seats`
# @return [Google::Apis::ResellerV1::Seats]
attr_accessor :seats
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@deal_code = args[:deal_code] if args.key?(:deal_code)
@kind = args[:kind] if args.key?(:kind)
@plan_name = args[:plan_name] if args.key?(:plan_name)
@purchase_order_id = args[:purchase_order_id] if args.key?(:purchase_order_id)
@seats = args[:seats] if args.key?(:seats)
end
end
# When a Google customer's account is registered with a reseller, the customer's
# subscriptions for Google services are managed by this reseller. A customer is
# described by a primary domain name and a physical address.
class Customer
include Google::Apis::Core::Hashable
# Like the "Customer email" in the reseller tools, this email is the secondary
# contact used if something happens to the customer's service such as service
# outage or a security issue. This property is required when creating a new
# customer and should not use the same domain as `customerDomain`.
# Corresponds to the JSON property `alternateEmail`
# @return [String]
attr_accessor :alternate_email
# The customer's primary domain name string. `customerDomain` is required when
# creating a new customer. Do not include the `www` prefix in the domain when
# adding a customer.
# Corresponds to the JSON property `customerDomain`
# @return [String]
attr_accessor :customer_domain
# Whether the customer's primary domain has been verified.
# Corresponds to the JSON property `customerDomainVerified`
# @return [Boolean]
attr_accessor :customer_domain_verified
alias_method :customer_domain_verified?, :customer_domain_verified
# This property will always be returned in a response as the unique identifier
# generated by Google. In a request, this property can be either the primary
# domain or the unique identifier generated by Google.
# Corresponds to the JSON property `customerId`
# @return [String]
attr_accessor :customer_id
# Identifies the resource as a customer. Value: `reseller#customer`
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# Customer contact phone number. Must start with "+" followed by the country
# code. The rest of the number can be contiguous numbers or respect the phone
# local format conventions, but it must be a real phone number and not, for
# example, "123". This field is silently ignored if invalid.
# Corresponds to the JSON property `phoneNumber`
# @return [String]
attr_accessor :phone_number
# JSON template for address of a customer.
# Corresponds to the JSON property `postalAddress`
# @return [Google::Apis::ResellerV1::Address]
attr_accessor :postal_address
# URL to customer's Admin console dashboard. The read-only URL is generated by
# the API service. This is used if your client application requires the customer
# to complete a task in the Admin console.
# Corresponds to the JSON property `resourceUiUrl`
# @return [String]
attr_accessor :resource_ui_url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@alternate_email = args[:alternate_email] if args.key?(:alternate_email)
@customer_domain = args[:customer_domain] if args.key?(:customer_domain)
@customer_domain_verified = args[:customer_domain_verified] if args.key?(:customer_domain_verified)
@customer_id = args[:customer_id] if args.key?(:customer_id)
@kind = args[:kind] if args.key?(:kind)
@phone_number = args[:phone_number] if args.key?(:phone_number)
@postal_address = args[:postal_address] if args.key?(:postal_address)
@resource_ui_url = args[:resource_ui_url] if args.key?(:resource_ui_url)
end
end
# JSON template for a subscription renewal settings.
class RenewalSettings
include Google::Apis::Core::Hashable
# Identifies the resource as a subscription renewal setting. Value: `
# subscriptions#renewalSettings`
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# Renewal settings for the annual commitment plan. For more detailed information,
# see renewal options in the administrator help center. When renewing a
# subscription, the `renewalType` is a required property.
# Corresponds to the JSON property `renewalType`
# @return [String]
attr_accessor :renewal_type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@kind = args[:kind] if args.key?(:kind)
@renewal_type = args[:renewal_type] if args.key?(:renewal_type)
end
end
# JSON template for resellernotify getwatchdetails response.
class ResellernotifyGetwatchdetailsResponse
include Google::Apis::Core::Hashable
# List of registered service accounts.
# Corresponds to the JSON property `serviceAccountEmailAddresses`
# @return [Array<String>]
attr_accessor :service_account_email_addresses
# Topic name of the PubSub
# Corresponds to the JSON property `topicName`
# @return [String]
attr_accessor :topic_name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@service_account_email_addresses = args[:service_account_email_addresses] if args.key?(:service_account_email_addresses)
@topic_name = args[:topic_name] if args.key?(:topic_name)
end
end
# JSON template for resellernotify response.
class ResellernotifyResource
include Google::Apis::Core::Hashable
# Topic name of the PubSub
# Corresponds to the JSON property `topicName`
# @return [String]
attr_accessor :topic_name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@topic_name = args[:topic_name] if args.key?(:topic_name)
end
end
# JSON template for subscription seats.
class Seats
include Google::Apis::Core::Hashable
# Identifies the resource as a subscription seat setting. Value: `subscriptions#
# seats`
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# Read-only field containing the current number of users that are assigned a
# license for the product defined in `skuId`. This field's value is equivalent
# to the numerical count of users returned by the Enterprise License Manager API
# method: [`listForProductAndSku`](/admin-sdk/licensing/v1/reference/
# licenseAssignments/listForProductAndSku).
# Corresponds to the JSON property `licensedNumberOfSeats`
# @return [Fixnum]
attr_accessor :licensed_number_of_seats
# This is a required property and is exclusive to subscriptions with `FLEXIBLE`
# or `TRIAL` plans. This property sets the maximum number of licensed users
# allowed on a subscription. This quantity can be increased up to the maximum
# limit defined in the reseller's contract. The minimum quantity is the current
# number of users in the customer account. *Note: *G Suite subscriptions
# automatically assign a license to every user.
# Corresponds to the JSON property `maximumNumberOfSeats`
# @return [Fixnum]
attr_accessor :maximum_number_of_seats
# This is a required property and is exclusive to subscriptions with `
# ANNUAL_MONTHLY_PAY` and `ANNUAL_YEARLY_PAY` plans. This property sets the
# maximum number of licenses assignable to users on a subscription. The reseller
# can add more licenses, but once set, the `numberOfSeats` cannot be reduced
# until renewal. The reseller is invoiced based on the `numberOfSeats` value
# regardless of how many of these user licenses are assigned. *Note: *G Suite
# subscriptions automatically assign a license to every user.
# Corresponds to the JSON property `numberOfSeats`
# @return [Fixnum]
attr_accessor :number_of_seats
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@kind = args[:kind] if args.key?(:kind)
@licensed_number_of_seats = args[:licensed_number_of_seats] if args.key?(:licensed_number_of_seats)
@maximum_number_of_seats = args[:maximum_number_of_seats] if args.key?(:maximum_number_of_seats)
@number_of_seats = args[:number_of_seats] if args.key?(:number_of_seats)
end
end
# JSON template for a subscription.
class Subscription
include Google::Apis::Core::Hashable
# Read-only field that returns the current billing method for a subscription.
# Corresponds to the JSON property `billingMethod`
# @return [String]
attr_accessor :billing_method
# The `creationTime` property is the date when subscription was created. It is
# in milliseconds using the Epoch format. See an example Epoch converter.
# Corresponds to the JSON property `creationTime`
# @return [Fixnum]
attr_accessor :creation_time
# Primary domain name of the customer
# Corresponds to the JSON property `customerDomain`
# @return [String]
attr_accessor :customer_domain
# This property will always be returned in a response as the unique identifier
# generated by Google. In a request, this property can be either the primary
# domain or the unique identifier generated by Google.
# Corresponds to the JSON property `customerId`
# @return [String]
attr_accessor :customer_id
# Google-issued code (100 char max) for discounted pricing on subscription plans.
# Deal code must be included in `insert` requests in order to receive
# discounted rate. This property is optional, regular pricing applies if left
# empty.
# Corresponds to the JSON property `dealCode`
# @return [String]
attr_accessor :deal_code
# Identifies the resource as a Subscription. Value: `reseller#subscription`
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# The `plan` property is required. In this version of the API, the G Suite plans
# are the flexible plan, annual commitment plan, and the 30-day free trial plan.
# For more information about the API"s payment plans, see the API concepts.
# Corresponds to the JSON property `plan`
# @return [Google::Apis::ResellerV1::Subscription::Plan]
attr_accessor :plan
# This is an optional property. This purchase order (PO) information is for
# resellers to use for their company tracking usage. If a `purchaseOrderId`
# value is given it appears in the API responses and shows up in the invoice.
# The property accepts up to 80 plain text characters.
# Corresponds to the JSON property `purchaseOrderId`
# @return [String]
attr_accessor :purchase_order_id
# JSON template for a subscription renewal settings.
# Corresponds to the JSON property `renewalSettings`
# @return [Google::Apis::ResellerV1::RenewalSettings]
attr_accessor :renewal_settings
# URL to customer's Subscriptions page in the Admin console. The read-only URL
# is generated by the API service. This is used if your client application
# requires the customer to complete a task using the Subscriptions page in the
# Admin console.
# Corresponds to the JSON property `resourceUiUrl`
# @return [String]
attr_accessor :resource_ui_url
# JSON template for subscription seats.
# Corresponds to the JSON property `seats`
# @return [Google::Apis::ResellerV1::Seats]
attr_accessor :seats
# A required property. The `skuId` is a unique system identifier for a product's
# SKU assigned to a customer in the subscription. For products and SKUs
# available in this version of the API, see Product and SKU IDs.
# Corresponds to the JSON property `skuId`
# @return [String]
attr_accessor :sku_id
# Read-only external display name for a product's SKU assigned to a customer in
# the subscription. SKU names are subject to change at Google's discretion. For
# products and SKUs available in this version of the API, see Product and SKU
# IDs.
# Corresponds to the JSON property `skuName`
# @return [String]
attr_accessor :sku_name
# This is an optional property.
# Corresponds to the JSON property `status`
# @return [String]
attr_accessor :status
# The `subscriptionId` is the subscription identifier and is unique for each
# customer. This is a required property. Since a `subscriptionId` changes when a
# subscription is updated, we recommend not using this ID as a key for
# persistent data. Use the `subscriptionId` as described in retrieve all
# reseller subscriptions.
# Corresponds to the JSON property `subscriptionId`
# @return [String]
attr_accessor :subscription_id
# Read-only field containing an enumerable of all the current suspension reasons
# for a subscription. It is possible for a subscription to have many concurrent,
# overlapping suspension reasons. A subscription's `STATUS` is `SUSPENDED` until
# all pending suspensions are removed. Possible options include: - `
# PENDING_TOS_ACCEPTANCE` - The customer has not logged in and accepted the G
# Suite Resold Terms of Services. - `RENEWAL_WITH_TYPE_CANCEL` - The customer's
# commitment ended and their service was cancelled at the end of their term. - `
# RESELLER_INITIATED` - A manual suspension invoked by a Reseller. - `
# TRIAL_ENDED` - The customer's trial expired without a plan selected. - `OTHER`
# - The customer is suspended for an internal Google reason (e.g. abuse or
# otherwise).
# Corresponds to the JSON property `suspensionReasons`
# @return [Array<String>]
attr_accessor :suspension_reasons
# Read-only transfer related information for the subscription. For more
# information, see retrieve transferable subscriptions for a customer.
# Corresponds to the JSON property `transferInfo`
# @return [Google::Apis::ResellerV1::Subscription::TransferInfo]
attr_accessor :transfer_info
# The G Suite annual commitment and flexible payment plans can be in a 30-day
# free trial. For more information, see the API concepts.
# Corresponds to the JSON property `trialSettings`
# @return [Google::Apis::ResellerV1::Subscription::TrialSettings]
attr_accessor :trial_settings
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@billing_method = args[:billing_method] if args.key?(:billing_method)
@creation_time = args[:creation_time] if args.key?(:creation_time)
@customer_domain = args[:customer_domain] if args.key?(:customer_domain)
@customer_id = args[:customer_id] if args.key?(:customer_id)
@deal_code = args[:deal_code] if args.key?(:deal_code)
@kind = args[:kind] if args.key?(:kind)
@plan = args[:plan] if args.key?(:plan)
@purchase_order_id = args[:purchase_order_id] if args.key?(:purchase_order_id)
@renewal_settings = args[:renewal_settings] if args.key?(:renewal_settings)
@resource_ui_url = args[:resource_ui_url] if args.key?(:resource_ui_url)
@seats = args[:seats] if args.key?(:seats)
@sku_id = args[:sku_id] if args.key?(:sku_id)
@sku_name = args[:sku_name] if args.key?(:sku_name)
@status = args[:status] if args.key?(:status)
@subscription_id = args[:subscription_id] if args.key?(:subscription_id)
@suspension_reasons = args[:suspension_reasons] if args.key?(:suspension_reasons)
@transfer_info = args[:transfer_info] if args.key?(:transfer_info)
@trial_settings = args[:trial_settings] if args.key?(:trial_settings)
end
# The `plan` property is required. In this version of the API, the G Suite plans
# are the flexible plan, annual commitment plan, and the 30-day free trial plan.
# For more information about the API"s payment plans, see the API concepts.
class Plan
include Google::Apis::Core::Hashable
# In this version of the API, annual commitment plan's interval is one year. *
# Note: *When `billingMethod` value is `OFFLINE`, the subscription property
# object `plan.commitmentInterval` is omitted in all API responses.
# Corresponds to the JSON property `commitmentInterval`
# @return [Google::Apis::ResellerV1::Subscription::Plan::CommitmentInterval]
attr_accessor :commitment_interval
# The `isCommitmentPlan` property's boolean value identifies the plan as an
# annual commitment plan: - `true` β The subscription's plan is an annual
# commitment plan. - `false` β The plan is not an annual commitment plan.
# Corresponds to the JSON property `isCommitmentPlan`
# @return [Boolean]
attr_accessor :is_commitment_plan
alias_method :is_commitment_plan?, :is_commitment_plan
# The `planName` property is required. This is the name of the subscription's
# plan. For more information about the Google payment plans, see the API
# concepts. Possible values are: - `ANNUAL_MONTHLY_PAY` β The annual commitment
# plan with monthly payments. *Caution: *`ANNUAL_MONTHLY_PAY` is returned as `
# ANNUAL` in all API responses. - `ANNUAL_YEARLY_PAY` β The annual commitment
# plan with yearly payments - `FLEXIBLE` β The flexible plan - `TRIAL` β The 30-
# day free trial plan. A subscription in trial will be suspended after the 30th
# free day if no payment plan is assigned. Calling `changePlan` will assign a
# payment plan to a trial but will not activate the plan. A trial will
# automatically begin its assigned payment plan after its 30th free day or
# immediately after calling `startPaidService`. - `FREE` β The free plan is
# exclusive to the Cloud Identity SKU and does not incur any billing.
# Corresponds to the JSON property `planName`
# @return [String]
attr_accessor :plan_name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@commitment_interval = args[:commitment_interval] if args.key?(:commitment_interval)
@is_commitment_plan = args[:is_commitment_plan] if args.key?(:is_commitment_plan)
@plan_name = args[:plan_name] if args.key?(:plan_name)
end
# In this version of the API, annual commitment plan's interval is one year. *
# Note: *When `billingMethod` value is `OFFLINE`, the subscription property
# object `plan.commitmentInterval` is omitted in all API responses.
class CommitmentInterval
include Google::Apis::Core::Hashable
# An annual commitment plan's interval's `endTime` in milliseconds using the
# UNIX Epoch format. See an example Epoch converter.
# Corresponds to the JSON property `endTime`
# @return [Fixnum]
attr_accessor :end_time
# An annual commitment plan's interval's `startTime` in milliseconds using UNIX
# Epoch format. See an example Epoch converter.
# Corresponds to the JSON property `startTime`
# @return [Fixnum]
attr_accessor :start_time
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@end_time = args[:end_time] if args.key?(:end_time)
@start_time = args[:start_time] if args.key?(:start_time)
end
end
end
# Read-only transfer related information for the subscription. For more
# information, see retrieve transferable subscriptions for a customer.
class TransferInfo
include Google::Apis::Core::Hashable
# Sku id of the current resold subscription. This is populated only when
# customer has subscription with legacy sku and the subscription resource is
# populated with recommeded sku for transfer in.
# Corresponds to the JSON property `currentLegacySkuId`
# @return [String]
attr_accessor :current_legacy_sku_id
# When inserting a subscription, this is the minimum number of seats listed in
# the transfer order for this product. For example, if the customer has 20 users,
# the reseller cannot place a transfer order of 15 seats. The minimum is 20
# seats.
# Corresponds to the JSON property `minimumTransferableSeats`
# @return [Fixnum]
attr_accessor :minimum_transferable_seats
# The time when transfer token or intent to transfer will expire. The time is in
# milliseconds using UNIX Epoch format.
# Corresponds to the JSON property `transferabilityExpirationTime`
# @return [Fixnum]
attr_accessor :transferability_expiration_time
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@current_legacy_sku_id = args[:current_legacy_sku_id] if args.key?(:current_legacy_sku_id)
@minimum_transferable_seats = args[:minimum_transferable_seats] if args.key?(:minimum_transferable_seats)
@transferability_expiration_time = args[:transferability_expiration_time] if args.key?(:transferability_expiration_time)
end
end
# The G Suite annual commitment and flexible payment plans can be in a 30-day
# free trial. For more information, see the API concepts.
class TrialSettings
include Google::Apis::Core::Hashable
# Determines if a subscription's plan is in a 30-day free trial or not: - `true`
# β The plan is in trial. - `false` β The plan is not in trial.
# Corresponds to the JSON property `isInTrial`
# @return [Boolean]
attr_accessor :is_in_trial
alias_method :is_in_trial?, :is_in_trial
# Date when the trial ends. The value is in milliseconds using the UNIX Epoch
# format. See an example Epoch converter.
# Corresponds to the JSON property `trialEndTime`
# @return [Fixnum]
attr_accessor :trial_end_time
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@is_in_trial = args[:is_in_trial] if args.key?(:is_in_trial)
@trial_end_time = args[:trial_end_time] if args.key?(:trial_end_time)
end
end
end
# A subscription manages the relationship of a Google customer's payment plan
# with a product's SKU, user licenses, 30-day free trial status, and renewal
# options. A primary role of a reseller is to manage the Google customer's
# subscriptions.
class Subscriptions
include Google::Apis::Core::Hashable
# Identifies the resource as a collection of subscriptions. Value: reseller#
# subscriptions
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# The continuation token, used to page through large result sets. Provide this
# value in a subsequent request to return the next page of results.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
# The subscriptions in this page of results.
# Corresponds to the JSON property `subscriptions`
# @return [Array<Google::Apis::ResellerV1::Subscription>]
attr_accessor :subscriptions
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@kind = args[:kind] if args.key?(:kind)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
@subscriptions = args[:subscriptions] if args.key?(:subscriptions)
end
end
end
end
end
| 46.659544 | 132 | 0.644482 |
e9d274425c886a7916d930ed724002d3da4661c9
| 9,037 |
=begin
#Datadog API V2 Collection
#Collection of all Datadog Public endpoints.
The version of the OpenAPI document: 1.0
Contact: [email protected]
Generated by: https://openapi-generator.tech
Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
This product includes software developed at Datadog (https://www.datadoghq.com/).
Copyright 2020-Present Datadog, Inc.
=end
require 'date'
require 'time'
module DatadogAPIClient::V2
# Attributes of the organization.
class OrganizationAttributes
# whether the object has unparsed attributes
attr_accessor :_unparsed
# Creation time of the organization.
attr_accessor :created_at
# Description of the organization.
attr_accessor :description
# Whether or not the organization is disabled.
attr_accessor :disabled
# Time of last organization modification.
attr_accessor :modified_at
# Name of the organization.
attr_accessor :name
# Public ID of the organization.
attr_accessor :public_id
# Sharing type of the organization.
attr_accessor :sharing
# URL of the site that this organization exists at.
attr_accessor :url
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'created_at' => :'created_at',
:'description' => :'description',
:'disabled' => :'disabled',
:'modified_at' => :'modified_at',
:'name' => :'name',
:'public_id' => :'public_id',
:'sharing' => :'sharing',
:'url' => :'url'
}
end
# Returns all the JSON keys this model knows about
def self.acceptable_attributes
attribute_map.values
end
# Attribute type mapping.
def self.openapi_types
{
:'created_at' => :'Time',
:'description' => :'String',
:'disabled' => :'Boolean',
:'modified_at' => :'Time',
:'name' => :'String',
:'public_id' => :'String',
:'sharing' => :'String',
:'url' => :'String'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `DatadogAPIClient::V2::OrganizationAttributes` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `DatadogAPIClient::V2::OrganizationAttributes`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'created_at')
self.created_at = attributes[:'created_at']
end
if attributes.key?(:'description')
self.description = attributes[:'description']
end
if attributes.key?(:'disabled')
self.disabled = attributes[:'disabled']
end
if attributes.key?(:'modified_at')
self.modified_at = attributes[:'modified_at']
end
if attributes.key?(:'name')
self.name = attributes[:'name']
end
if attributes.key?(:'public_id')
self.public_id = attributes[:'public_id']
end
if attributes.key?(:'sharing')
self.sharing = attributes[:'sharing']
end
if attributes.key?(:'url')
self.url = attributes[:'url']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
created_at == o.created_at &&
description == o.description &&
disabled == o.disabled &&
modified_at == o.modified_at &&
name == o.name &&
public_id == o.public_id &&
sharing == o.sharing &&
url == o.url
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[created_at, description, disabled, modified_at, name, public_id, sharing, url].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
elsif type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :Time
Time.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when :Array
# generic array, return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
# models (e.g. Pet) or oneOf
klass = DatadogAPIClient::V2.const_get(type)
res = klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
if res.instance_of? DatadogAPIClient::V2::UnparsedObject
self._unparsed = true
end
res
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 29.726974 | 222 | 0.618789 |
b9204d8d05fa21cc1db650e20aa49f07bc35f234
| 833 |
# frozen_string_literal: true
require 'rails_helper'
require 'models/shared_examples/shared_examples_for_loadable'
require 'models/shared_examples/shared_examples_for_exportable'
RSpec.describe Program, type: :model do
it_behaves_like 'a loadable model', skip_lines: 0
it_behaves_like 'an exportable model', skip_lines: 0
describe 'when validating' do
subject(:program) { build :program }
it 'has a valid factory' do
expect(program).to be_valid
end
it 'requires a valid facility_code' do
expect(build(:program, facility_code: nil)).not_to be_valid
end
it 'requires a valid description' do
expect(build(:program, description: nil)).not_to be_valid
end
it 'requires a valid program_type' do
expect(build(:program, program_type: 'NCD')).to be_valid
end
end
end
| 26.870968 | 65 | 0.732293 |
01aaa26d5a765a7146bdf7f415345a989c430eaa
| 164 |
require 'active_document'
class Photo < ActiveDocument::Base
path '/var/data'
accessor :id, :tagged_ids, :user_id, :description
index_by :tagged_ids
end
| 16.4 | 51 | 0.731707 |
f884d7204a7f4be2cc334c8d219e599c4308af8c
| 2,386 |
Rails.application.eager_load!
require "rails/generators/base"
require "administrate/namespace"
module Administrate
module Generators
class RoutesGenerator < Rails::Generators::Base
source_root File.expand_path("../templates", __FILE__)
def insert_dashboard_routes
if should_route_dashboard?
route(dashboard_routes)
end
end
def warn_about_invalid_models
namespaced_models.each do |invalid_model|
puts "WARNING: Unable to generate a dashboard for #{invalid_model}."
puts " Administrate does not yet support namespaced models."
end
models_without_tables.each do |invalid_model|
puts "WARNING: Unable to generate a dashboard for #{invalid_model}."
puts " It is not connected to a database table."
puts " Make sure your database migrations are up to date."
end
unnamed_constants.each do |invalid_model|
puts "NOTICE: Skipping dynamically generated model #{invalid_model}."
end
end
private
def dashboard_resources
valid_dashboard_models.map do |model|
model.to_s.pluralize.underscore
end
end
def valid_dashboard_models
database_models - invalid_database_models
end
def database_models
ActiveRecord::Base.descendants.reject(&:abstract_class?)
end
def invalid_database_models
models_without_tables + namespaced_models + unnamed_constants
end
def models_without_tables
database_models.reject(&:table_exists?)
end
def namespaced_models
database_models.select { |model| model.to_s.include?("::") }
end
def unnamed_constants
ActiveRecord::Base.descendants.reject { |d| d.name == d.to_s }
end
def dashboard_routes
ERB.new(File.read(routes_file_path)).result(binding)
end
def routes_includes_resources?
File.read(rails_routes_file_path).include?(dashboard_routes)
end
def rails_routes_file_path
Rails.root.join("config/routes.rb")
end
def routes_file_path
File.expand_path(find_in_source_paths("routes.rb.erb"))
end
def should_route_dashboard?
routes_includes_resources? || valid_dashboard_models.any?
end
end
end
end
| 27.425287 | 79 | 0.662615 |
183fe4d7a6a02e59bb72b6bb2d45081ae7eb862d
| 797 |
module Gcl
module FulltextSearch
#
# MatchAgainst visitor methods for MySQL
#
module MysqlVisitorMethods
#
# @param [MatchAgainst]
#
def visit_Gcl_FulltextSearch_MatchAgainst(o, collector)
collector << 'MATCH ('
visit o.column, collector
collector << ') AGAINST ('
quoted = case o.expr
when String
Arel::Nodes.build_quoted o.expr
when Array
Arel::Nodes.build_quoted o.expr.map(&:to_s).compact.join(' ')
else
o.expr
end
visit quoted, collector
collector << (o.boolean ? ' IN BOOLEAN MODE)' : ')')
end
end
Arel::Visitors::MySQL.include MysqlVisitorMethods
end
end
| 24.151515 | 80 | 0.535759 |
bf1bb2631ae1bdf490aa482b643179cc2e760bcd
| 679 |
cask "fabfilter-pro-l" do
version "2.11"
sha256 "a235f6997adfcb7c682355712dda684ad559101c2bee50b0cc2a3d392540c737"
url "https://download.fabfilter.com/ffprol#{version.no_dots}.dmg"
name "FabFilter Pro-L"
desc "Limiter plug-in"
homepage "https://www.fabfilter.com/products/pro-l-2-limiter-plug-in"
livecheck do
url "https://www.fabfilter.com/download"
strategy :page_match do |page|
match = page.match(/ffprol(\d)(\d+)\.dmg/i)
next if match.blank?
"#{match[1]}.#{match[2]}"
end
end
depends_on macos: ">= :sierra"
pkg "FabFilter Pro-L #{version} Installer.pkg"
uninstall pkgutil: "com.fabfilter.Pro-L.#{version.major}"
end
| 26.115385 | 75 | 0.687776 |
39f2489d9cc02704583cd0e59473a9df7c4f1a15
| 48 |
module ContentScheduler
VERSION = "0.0.1"
end
| 12 | 23 | 0.729167 |
38ccfb3ebbc63fb57f4d0ba5247ebcc9c272b4f1
| 580 |
require_relative "../lib/php_pecl_formula"
class PhpAT74Ds < PhpPeclFormula
extension_dsl "Data Structures for PHP"
url "https://pecl.php.net/get/ds-1.4.0.tgz"
sha256 "a9b930582de8054e2b1a3502bec9d9e064941b5b9b217acc31e4b47f442b93ef"
license "MIT"
bottle do
root_url "https://kabel.jfrog.io/artifactory/bottles-pecl"
sha256 cellar: :any_skip_relocation, big_sur: "2e340a1e1d458059c6e516ecc91f2bc6a7ef5c2c93b327dc6c79fca83297a7c3"
sha256 cellar: :any_skip_relocation, catalina: "2bed9c882eb9700e4d41b241a136a3710162f329b26b4d1d3622e36f60447e73"
end
end
| 36.25 | 117 | 0.812069 |
0844aedd2955bc85de65de157f106ffa6a277e6c
| 2,008 |
class ComplexExample
include AASM
attr_accessor :activation_code, :activated_at, :deleted_at
aasm do
state :passive
state :pending, :initial => true, :before_enter => :make_activation_code
state :active, :before_enter => :do_activate
state :suspended
state :deleted, :before_enter => :do_delete#, :exit => :do_undelete
state :waiting
event :register do
transitions :from => :passive, :to => :pending do
guard do
can_register?
end
end
end
event :activate do
transitions :from => :pending, :to => :active
end
event :suspend do
transitions :from => [:passive, :pending, :active], :to => :suspended
end
event :delete do
transitions :from => [:passive, :pending, :active, :suspended], :to => :deleted
end
# a dummy event that can never happen
event :unpassify do
transitions :from => :passive, :to => :active, :guard => Proc.new {|u| false }
end
event :unsuspend do
transitions :from => :suspended, :to => :active, :guard => Proc.new { has_activated? }
transitions :from => :suspended, :to => :pending, :guard => :has_activation_code?
transitions :from => :suspended, :to => :passive
end
event :wait do
transitions :from => :suspended, :to => :waiting, :guard => :if_polite?
end
end
def initialize
# the AR backend uses a before_validate_on_create :aasm_ensure_initial_state
# lets do something similar here for testing purposes.
aasm.enter_initial_state
end
def make_activation_code
@activation_code = 'moo'
end
def do_activate
@activated_at = Time.now
@activation_code = nil
end
def do_delete
@deleted_at = Time.now
end
def do_undelete
@deleted_at = false
end
def can_register?
true
end
def has_activated?
!!@activated_at
end
def has_activation_code?
!!@activation_code
end
def if_polite?(phrase = nil)
phrase == :please
end
end
| 22.561798 | 93 | 0.640936 |
1cb3d315b39e8569324a9ff5447260e040bdd830
| 984 |
class User < ApplicationRecord
has_many :user_routines
has_many :routines, through: :user_routines
has_many :tasks, through: :routines
has_secure_password
validates_confirmation_of :password
validates :email, presence: true, uniqueness: true
validates :username, presence: true, uniqueness: true
validates :password, length: { minimum: 6, allow_nil: true }
def number_of_routines
self.routines.count
end
def number_of_tasks
self.tasks.count
end
def current_routine
routines = Array.new
self.routines.each do |routine|
if routine.begin_hour <= routine.current_hour && routine.end_hour >= routine.current_hour
routines << routine
end
end
routines
end
def upcoming_routine
routines = Array.new
self.routines.map do |routine|
if routine.end_hour >= routine.current_hour && !self.current_routine.include?(routine)
#return routine
routines << routine
end
end
routines
end
end
| 22.363636 | 94 | 0.716463 |
1a8feda6bd650f62dce37a2d0f94babee23dae76
| 276 |
module ROM
describe DynamoDB do
include_context 'dynamo'
let(:table) { build(:table) }
specify { expect { ROM::Configuration.new(:dynamodb, credentials) }.to_not raise_error }
specify { expect { {}.deep_merge(credentials) }.to_not raise_error }
end
end
| 23 | 92 | 0.692029 |
7a97fd4f8afdded6fbecd05e438e870a6bd35e2c
| 3,794 |
class SubmissionRule < ActiveRecord::Base
class InvalidRuleType < Exception
def initialize(rule_name)
super I18n.t('assignment.not_valid_submission_rule', type: rule_name)
end
end
belongs_to :assignment, inverse_of: :submission_rule
has_many :periods, -> { order('id') }, dependent: :destroy
accepts_nested_attributes_for :periods, allow_destroy: true
# validates_associated :assignment
# validates_presence_of :assignment
def self.descendants
[NoLateSubmissionRule,
PenaltyPeriodSubmissionRule,
PenaltyDecayPeriodSubmissionRule,
GracePeriodSubmissionRule]
end
def can_collect_now?
return @can_collect_now if !@can_collect_now.nil?
@can_collect_now = Time.zone.now >= get_collection_time
end
def can_collect_grouping_now?(grouping)
Time.zone.now >= calculate_grouping_collection_time(grouping)
end
# Cache that allows us to quickly get collection time
def get_collection_time
return @get_collection_time if !@get_collection_time.nil?
@get_collection_time = calculate_collection_time
end
def calculate_collection_time
assignment.latest_due_date + hours_sum.hours
end
def calculate_grouping_collection_time(grouping)
if grouping.inviter.section
SectionDueDate.due_date_for(grouping.inviter.section,
assignment)
else
assignment.due_date + hours_sum.hours
end
end
# When Students commit code after the collection time, MarkUs should warn
# the Students with a message saying that the due date has passed, and the
# work they're submitting will probably not be graded
def commit_after_collection_message
#I18n.t 'submission_rules.submission_rule.commit_after_collection_message'
raise NotImplementedError.new('SubmissionRule: commit_after_collection_message not implemented')
end
# When Students view the File Manager after the collection time,
# MarkUs should warnthe Students with a message saying that the
# due date has passed, and that any work they're submitting will
# probably not be graded
def after_collection_message
raise NotImplementedError.new('SubmissionRule: after_collection_message not implemented')
end
# When we're past the due date, the File Manager for the students will display
# a message to tell them that they're currently past the due date.
def overtime_message
raise NotImplementedError.new('SubmissionRule: overtime_message not implemented')
end
# Returns true or false based on whether the attached Assignment's properties
# will work with this particular SubmissionRule
def assignment_valid?
raise NotImplementedError.new('SubmissionRule: assignment_valid? not implemented')
end
# Takes a Submission (with an attached Result), and based on the properties of
# this SubmissionRule, applies penalties to the Result - for example, will
# add an ExtraMark of a negative value, or perhaps add the use of a Grace Day.
def apply_submission_rule(submission)
raise NotImplementedError.new('SubmissionRule: apply_submission_rule not implemented')
end
def description_of_rule
raise NotImplementedError.new('SubmissionRule: description_of_rule not implemented')
end
def grader_tab_partial(grouping)
raise NotImplementedError.new('SubmissionRule: render_grader_tab not implemented')
end
def reset_collection_time
@get_collection_time = nil
@can_collect_now = nil
end
private
def calculate_overtime_hours_from(from_time)
overtime_hours = ((from_time - assignment.due_date) / 1.hour).ceil
# If the overtime is less than 0, that means it was submitted early, so
# just return 0 - otherwise, return overtime_hours.
[0, overtime_hours].max
end
def hours_sum
0
end
end
| 33.575221 | 101 | 0.764101 |
391fb0bf8259d4de4447123629e3610711197707
| 2,294 |
require 'rails_helper'
describe MeetingResults, type: :strategy do
let(:meeting) { Meeting.last(300).sample }
context "well formed instance" do
subject { MeetingResults.new( meeting ) }
it_behaves_like( "(the existance of a method)", [
:meeting,
:data_retrieved, :max_updated_at,
:retrieve_data_by_query, :retrieve_data, :set_meeting_results_dao_from_query
] )
it "assigns attributes as given parameters" do
expect( subject.meeting ).to eq( meeting )
end
it "assigns defaults" do
expect( subject.max_updated_at ).to eq( 0 )
end
it "creates empty readable attributes" do
expect( subject.data_retrieved ).to be_nil
end
describe "#retrieve_data_by_query" do
it "returns a relation and sets date_retrieved" do
expect( subject.data_retrieved ).to be_nil
result = subject.retrieve_data_by_query
expect( result ).to be_a_kind_of( ActiveRecord::Result )
expect( subject.data_retrieved ).to be_a_kind_of( ActiveRecord::Result )
expect( subject.data_retrieved ).to eq( result )
end
it "returns a query result of elements with necessary columns" do
columns = [
'session_order', 'event_order', 'event_code', 'heat_type', 'gender_code', 'age_begin', 'category_code', 'rank', 'is_disqualified', 'minutes',
'seconds', 'hundreds', 'is_personal_best', 'reaction_time', 'standard_points', 'meeting_individual_points', 'goggle_cup_points', 'team_points',
'complete_name', 'year_of_birth', 'team_name', 'team_id', 'swimmer_id', 'meeting_event_id', 'meeting_program_id'
]
result = subject.retrieve_data_by_query
result.each do |element|
expect( element.size ).to eq( columns.size )
columns.each do |column|
expect( element.has_key?(column) ).to eq(true)
end
end
end
end
describe "#set_meeting_results_dao_from_query" do
it "returns a MeetingResultsDAO" do
result = subject.retrieve_data
expect( subject.set_meeting_results_dao_from_query ).to be_an_instance_of( MeetingResultsDAO )
end
end
end
#-- -------------------------------------------------------------------------
#++
end
| 37 | 153 | 0.641674 |
acb36aa3e11fc8adea36bd3e24b3b8133d169c06
| 1,472 |
require 'rails_helper'
RSpec.describe '<%= uri %>', type: :feature do
let(:resource_class) { <%= resource_class %> }
let(:resource) { create(:<%= factory_name %>) }
let(:resources) { create_list(:<%= factory_name %>, 3) }
# List
it { resources; expect(subject).to implement_index_action(self) }
# Create
it {
expect(subject).to implement_create_action(self)
.for(resource_class)
.within_form('<%= new_form_dom_selector %>') {
# fill the needed form inputs via capybara here
#
# Example:
#
# select 'de', from: 'slider[locale]'
# fill_in 'slider[name]', with: 'My first slider'
# check 'slider[auto_start]'
# fill_in 'slider[interval]', with: '3'
}
.increasing{ <%= resource_class %>.count }.by(1)
}
# Read
it { expect(subject).to implement_show_action(self).for(resource) }
# Update
it {
expect(subject).to implement_update_action(self)
.for(resource)
.within_form('<%= edit_form_dom_selector %>') {
# fill the needed form inputs via capybara here
#
# Example:
#
# fill_in 'slider[name]', with: 'New name'
}
.updating
.from(resource.attributes)
.to({ }) # Example: .to({ 'name' => 'New name' })
}
# Delete
it {
expect(subject).to implement_delete_action(self)
.for(resource)
.reducing{ resource_class.count }.by(1)
}
end
| 27.259259 | 69 | 0.578125 |
7acf4800f32b9ca03240b89dbd2d0074271141af
| 35 |
class Game < ApplicationRecord
end
| 11.666667 | 30 | 0.828571 |
ffa984ed917919b1cecd8810298c17cf74e9eff3
| 156 |
module EnjuIr
class FilesetStateMachine
include Statesman::Machine
state :pending, initial: true
state :draft
state :published
end
end
| 15.6 | 33 | 0.717949 |
793e2c68173ff69cebeceba2253fdb1eb13c0a33
| 536 |
cask "haptickey" do
version "0.5.0"
sha256 "ea7ce3a3c0761a0e0cbd13f2bccdc64c3f0cff363ecf89fcacb7081f634a412f"
url "https://github.com/niw/HapticKey/releases/download/#{version}/HapticKey.app.zip"
name "HapticKey"
desc "Trigger haptic feedback when tapping Touch Bar"
homepage "https://github.com/niw/HapticKey"
depends_on macos: ">= :sierra"
app "HapticKey.app"
uninstall quit: "at.niw.HapticKey"
zap trash: [
"~/Library/Caches/at.niw.HapticKey",
"~/Library/Preferences/at.niw.HapticKey.plist",
]
end
| 25.52381 | 87 | 0.729478 |
edebae5b0f2ac8a5e41250271385517c9353c517
| 9,473 |
# frozen_string_literal: true
class Product < ApplicationRecord
include TextHelpers::Translation
include EmailListAttribute
include FullTextSearch::Model
belongs_to :facility
belongs_to :initial_order_status, class_name: "OrderStatus"
belongs_to :facility_account
has_many :product_users
has_many :order_details
has_many :stored_files
has_many :price_group_products
has_many :price_groups, through: :price_group_products
has_many :product_accessories, -> { where(deleted_at: nil) }, dependent: :destroy
has_many :accessories, through: :product_accessories, class_name: "Product"
has_many :price_policies
has_many :training_requests, dependent: :destroy
has_many :product_research_safety_certification_requirements
has_many :research_safety_certificates, through: :product_research_safety_certification_requirements
has_one :product_display_group_product
has_one :product_display_group, through: :product_display_group_product
after_create :create_default_price_group_products
email_list_attribute :training_request_contacts
# Allow us to use `product.hidden?`
alias_attribute :hidden, :is_hidden
validates :type, presence: true
validates :name, presence: true, length: { maximum: 200 }
validate_url_name :url_name, :facility_id
validates :user_notes_field_mode, presence: true, inclusion: Products::UserNoteMode.all
validates :user_notes_label, length: { maximum: 255 }
validates :order_notification_recipient,
email_format: true,
allow_blank: true
validates(
:account,
presence: true,
numericality: { only_integer: true },
length: { minimum: 1, maximum: Settings.accounts.product_default.to_s.length },
if: -> { SettingsHelper.feature_on?(:expense_accounts) && requires_account? },
)
validates :facility_account_id, presence: true, if: :requires_account?
# Use lambda so we can dynamically enable/disable in specs
validate if: -> { SettingsHelper.feature_on?(:product_specific_contacts) } do
errors.add(:contact_email, text("errors.models.product.attributes.contact_email.required")) unless email.present?
end
scope :active, -> { where(is_archived: false, is_hidden: false) }
scope :alphabetized, -> { order(Arel.sql("LOWER(products.name)")) }
scope :archived, -> { where(is_archived: true) }
scope :not_archived, -> { where(is_archived: false) }
scope :mergeable_into_order, -> { not_archived.where(type: mergeable_types) }
scope :in_active_facility, -> { joins(:facility).where(facilities: { is_active: true }) }
scope :of_type, ->(type) { where(type: type) }
scope :with_schedule, -> { where.not(schedule_id: nil) }
scope :without_display_group, -> {
left_outer_joins(:product_display_group_product).where(product_display_group_products: { id: nil })
}
# All product types. This cannot be a cattr_accessor because the block is evaluated
# at definition time (not lazily as I expected) and this causes a circular dependency
# in some schools.
def self.types
@types ||= [Instrument, Item, Service, TimedService, Bundle]
end
# Those that can be added to an order by an administrator
def self.mergeable_types
@mergeable_types ||= ["Instrument", "Item", "Service", "TimedService", "Bundle"]
end
# Those that can be ordered via the NUcore homepage
def self.orderable_types
@orderable_types ||= ["Instrument", "Item", "Service", "TimedService", "Bundle"]
end
# Products that can be used as accessories
scope :accessorizable, -> { where(type: ["Item", "Service", "TimedService"]) }
def self.exclude(products)
where.not(id: products)
end
scope :for_facility, lambda { |facility|
if facility.blank?
none
elsif facility.single_facility?
where(facility_id: facility.id)
else # cross-facility
all
end
}
def self.requiring_approval
where(requires_approval: true)
end
def self.requiring_approval_by_type
requiring_approval.group_by_type
end
def self.group_by_type
order(:type, :name).group_by { |product| product.class.model_name.human }
end
def initial_order_status
self[:initial_order_status_id] ? OrderStatus.find(self[:initial_order_status_id]) : OrderStatus.default_order_status
end
def current_price_policies(date = Time.zone.now)
price_policies.current_for_date(date).purchaseable
end
def past_price_policies
price_policies.past
end
def past_price_policies_grouped_by_start_date
past_price_policies.order("start_date DESC").group_by(&:start_date)
end
def upcoming_price_policies
price_policies.upcoming
end
def upcoming_price_policies_grouped_by_start_date
upcoming_price_policies.order("start_date ASC").group_by(&:start_date)
end
# TODO: favor the alphabetized scope over relying on Array#sort
def <=>(other)
name.casecmp other.name
end
# If there isn't an email specific to the product, fall back to the facility's email
def email
# If product_specific_contacts is off, always return the facility's email
return facility.email unless SettingsHelper.feature_on? :product_specific_contacts
contact_email.presence || facility.try(:email)
end
def description
self[:description].html_safe if self[:description]
end
def parameterize
self.class.to_s.parameterize.to_s.pluralize
end
def can_be_used_by?(user)
if requires_approval?
product_user_exists?(user)
else
true
end
end
def to_param
if errors[:url_name].nil?
url_name
else
url_name_was
end
end
def to_s
name.presence || ""
end
def to_s_with_status
to_s + (is_archived? ? " (inactive)" : "")
end
def create_default_price_group_products
PriceGroup.globals.find_each do |price_group|
price_group_products.create!(price_group: price_group)
end
end
def available_for_purchase?
!is_archived? && facility.is_active?
end
def can_purchase?(group_ids)
return false unless available_for_purchase?
# return false if there are no existing policies at all
return false if price_policies.empty?
# return false if there are no existing policies for the user's groups, e.g. they're a new group
return false if price_policies.for_price_groups(group_ids).empty?
# if there are current rules, but the user is not part of them
if price_policies.current.any?
return price_policies.current.for_price_groups(group_ids).where(can_purchase: true).any?
end
# if there are no current price policies, find the most recent price policy for each group.
# if one of those can purchase, then allow the purchase
group_ids.each do |group_id|
# .try is in case the query doesn't return any values
return true if price_policies.for_price_groups(group_id).order(:expire_date).last.try(:can_purchase?)
end
false
end
def can_purchase_order_detail?(order_detail)
can_purchase? order_detail.price_groups.map(&:id)
end
def cheapest_price_policy(order_detail, date = Time.zone.now)
groups = order_detail.price_groups
return nil if groups.empty?
price_policies = current_price_policies(date).newest.to_a.delete_if { |pp| pp.restrict_purchase? || groups.exclude?(pp.price_group) }
# provide a predictable ordering of price groups so that equal unit costs
# are always handled the same way. Put the base group at the front of the
# price policy array so that it takes precedence over all others that have
# equal unit cost. See task #49823.
base_ndx = price_policies.index { |pp| pp.price_group == PriceGroup.base }
base = price_policies.delete_at base_ndx if base_ndx
price_policies.sort! { |pp1, pp2| pp1.price_group.name <=> pp2.price_group.name }
price_policies.unshift base if base
price_policies.min_by do |pp|
# default to very large number if the estimate returns a nil
costs = pp.estimate_cost_and_subsidy_from_order_detail(order_detail) || { cost: 999_999_999, subsidy: 0 }
costs[:cost] - costs[:subsidy]
end
end
def product_type
self.class.name.underscore.pluralize
end
# Used when displaying quantities throughout the site and when editing an order.
def quantity_as_time?
false
end
# Primarily used when adding to an existing order (merge orders)
def order_quantity_as_time?
false
end
def product_accessory_by_id(id)
product_accessories.where(accessory_id: id).first
end
def has_product_access_groups?
respond_to?(:product_access_groups) && product_access_groups.any?
end
def access_group_for_user(user)
find_product_user(user).try(:product_access_group)
end
def find_product_user(user)
product_users.find_by(user_id: user.id)
end
def visible?
!hidden?
end
def requires_merge?
false
end
def offline?
false
end
def online?
!offline?
end
def user_notes_field_mode
Products::UserNoteMode[self[:user_notes_field_mode]]
end
def user_notes_field_mode=(str_value)
self[:user_notes_field_mode] = Products::UserNoteMode[str_value]
end
def is_accessible_to_user?(user)
is_operator = user&.operator_of?(facility)
!(is_archived? || (is_hidden? && !is_operator))
end
def alert
nil
end
protected
def translation_scope
self.class.i18n_scope
end
private
def requires_account?
true
end
def product_user_exists?(user)
find_product_user(user).present?
end
end
| 29.328173 | 137 | 0.737781 |
b9b096b645158a2e73fcbe99ee723db7147048b6
| 7,099 |
class Facility::Node::Importer
include Cms::CsvImportBase
self.required_headers = [ ::Facility::Node::Page.t(:filename) ]
attr_reader :site, :node, :user
def initialize(site, node, user)
@site = site
@node = node
@user = user
end
def import(file, opts = {})
@task = opts[:task]
@count_errors = 0
put_log("import start #{file.filename}")
import_csv(file)
put_log(I18n.t("cms.count_log_of_errors", number_of_errors: @count_errors))
end
private
def model
::Facility::Node::Page
end
def put_log(message)
if @task
@task.log(message)
else
Rails.logger.info(message)
end
end
def import_csv(file)
table = CSV.read(file.path, headers: true, encoding: 'SJIS:UTF-8')
table.each_with_index do |row, i|
row_num = i + 2
begin
update_row(row, row_num)
rescue => e
put_log("error #{row_num}#{I18n.t("cms.row_num")}: #{e}")
end
end
end
def update_row(row, row_num)
filename = "#{node.filename}/#{row[model.t(:filename)]}"
item = model.find_or_initialize_by filename: filename, site_id: site.id
item.cur_site = site
set_page_attributes(row, item)
put_log_of_insert(item, row_num, row)
if item.save
name = item.name
else
@count_errors += 1
raise item.errors.full_messages.join(", ")
end
if row[model.t(:map_points)].present?
filename = "#{filename}/map.html"
map = ::Facility::Map.find_or_create_by filename: filename
set_map_attributes(row, map, row_num)
map.site = site
map.save
name += " #{map.map_points.first.try(:[], "loc")}"
end
return name
end
def put_log_of_insert(item, row_num, row)
if item.invalid?
@count_errors += 1
put_log(I18n.t("cms.log_of_the_failed_import", row_num: row_num))
elsif item.new_record?
put_log("add #{row_num}#{I18n.t("cms.row_num")}: #{item.name}")
end
put_log_of_category(item.name, row_num, row)
put_log_of_location(item.name, row_num, row)
put_log_of_service(item.name, row_num, row)
put_log_of_group(item.name, row_num, row)
return if item.invalid? || item.new_record?
put_log_of_update(item, row_num)
end
def put_log_of_category(item_name, row_num, row)
inputted_category = row[model.t(:categories)].to_s.split(/\n/).map(&:strip)
category_in_db = Facility::Node::Category.in(id: node.st_category_ids).pluck(:name)
inputted_category.each do |category|
next if category_in_db.include?(category)
@count_errors += 1
put_log(I18n.t("cms.log_of_the_failed_category", category: category, row_num: row_num))
end
end
def put_log_of_location(item_name, row_num, row)
inputted_location = row[model.t(:locations)].to_s.split(/\n/).map(&:strip)
location_in_db = Facility::Node::Location.in(id: node.st_location_ids).pluck(:name)
inputted_location.each do |location|
next if location_in_db.include?(location)
@count_errors += 1
put_log(I18n.t("cms.log_of_the_failed_location", location: location, row_num: row_num))
end
end
def put_log_of_service(item_name, row_num, row)
inputted_service = row[model.t(:services)].to_s.split(/\n/).map(&:strip)
service_in_db = Facility::Node::Service.in(id: node.st_service_ids).pluck(:name)
inputted_service.each do |service|
next if service_in_db.include?(service)
@count_errors += 1
put_log(I18n.t("cms.log_of_the_failed_service", service: service, row_num: row_num))
end
end
def put_log_of_group(item_name, row_num, row)
inputted_group = row[model.t(:groups)].to_s.split(/\n/).map(&:strip)
group_in_db = SS::Group.in(id: node.group_ids).pluck(:name)
inputted_group.each do |group|
next if group_in_db.include?(group)
@count_errors += 1
put_log(I18n.t("cms.log_of_the_failed_group", group: group, row_num: row_num))
end
end
def put_log_of_update(item, row_num)
item.changes.each do |change_data|
changed_field = change_data[0]
before_changing_data = change_data[1][0]
after_changing_data = change_data[1][1]
next if changed_field == "additional_info" && before_changing_data.nil? && after_changing_data == []
field_name = "update #{row_num}#{I18n.t("cms.row_num")}: #{I18n.t("mongoid.attributes.facility/node/page.#{changed_field}")}οΌ"
if item.fields[changed_field].options[:metadata].nil?
put_log("#{field_name}#{before_changing_data} β #{after_changing_data}")
else
klass = item.fields[changed_field].options[:metadata][:elem_class].constantize
before_changing_metadata = klass.in(id: before_changing_data).pluck(:name)
after_changing_metadata = klass.in(id: after_changing_data).pluck(:name)
put_log("#{field_name}#{before_changing_metadata} β #{after_changing_metadata}")
end
end
end
def set_page_attributes(row, item)
item.name = row[model.t(:name)].try(:squish)
item.layout = Cms::Layout.site(site).where(name: row[model.t(:layout)].try(:squish)).first
item.kana = row[model.t(:kana)].try(:squish)
item.address = row[model.t(:address)].try(:squish)
item.postcode = row[model.t(:postcode)].try(:squish)
item.tel = row[model.t(:tel)].try(:squish)
item.fax = row[model.t(:fax)].try(:squish)
item.related_url = row[model.t(:related_url)].try(:gsub, /[\r\n]/, " ")
item.additional_info = row.to_h.select { |k, v| k =~ /^#{model.t(:additional_info)}[:οΌ]/ && v.present? }.
map { |k, v| {:field => k.sub(/^#{model.t(:additional_info)}[:οΌ]/, ""), :value => v} }
set_page_categories(row, item)
ids = SS::Group.in(name: row[model.t(:groups)].to_s.split(/\n/)).map(&:id)
item.group_ids = SS::Extensions::ObjectIds.new(ids)
end
def set_page_categories(row, item)
names = row[model.t(:categories)].to_s.split(/\n/).map(&:strip)
ids = node.st_categories.in(name: names).map(&:id)
item.category_ids = SS::Extensions::ObjectIds.new(ids)
names = row[model.t(:locations)].to_s.split(/\n/).map(&:strip)
ids = node.st_locations.in(name: names).map(&:id)
item.location_ids = SS::Extensions::ObjectIds.new(ids)
names = row[model.t(:services)].to_s.split(/\n/).map(&:strip)
ids = node.st_services.in(name: names).map(&:id)
item.service_ids = SS::Extensions::ObjectIds.new(ids)
end
def set_map_attributes(row, item, row_num)
points = row[model.t(:map_points)].split(/\n/).map do |loc|
{ loc: Map::Extensions::Loc.mongoize(loc) }
end
item.name = "map"
item.map_points = Map::Extensions::Points.new(points)
return if item.new_record?
item.changes.each do |change_data|
before_changing_data = change_data[1][0]#[0][:loc]
after_changing_data = change_data[1][1]#[0][:loc]
put_log("update #{row_num}#{I18n.t("cms.row_num")}: #{I18n.t("mongoid.attributes.facility/node/page.#{change_data[0]}")}οΌ#{before_changing_data} β #{after_changing_data}")
end
end
end
| 34.461165 | 178 | 0.657135 |
91984aa200a84fecb939207507abc228ae73fbf5
| 8,220 |
require File.join(File.dirname(File.expand_path(__FILE__)), "spec_helper")
describe "Composition plugin" do
before do
@c = Class.new(Sequel::Model(:items))
@c.plugin :composition
@c.columns :id, :year, :month, :day
@o = @c.load(:id=>1, :year=>1, :month=>2, :day=>3)
DB.reset
end
deprecated "should allow access to composition_module" do
@c.composition_module.must_be_kind_of Module
@c.composition_module = v = Module.new
@c.composition_module.must_equal v
end
it ".composition should add compositions" do
@o.wont_respond_to(:date)
@c.composition :date, :mapping=>[:year, :month, :day]
@o.date.must_equal Date.new(1, 2, 3)
end
it "loading the plugin twice should not remove existing compositions" do
@c.composition :date, :mapping=>[:year, :month, :day]
@c.plugin :composition
@c.compositions.keys.must_equal [:date]
end
it ".composition should raise an error if :composer and :decomposer options are not present and :mapping option is not provided" do
proc{@c.composition :date}.must_raise(Sequel::Error)
@c.composition :date, :composer=>proc{}, :decomposer=>proc{}
@c.composition :date, :mapping=>[]
end
it "should handle validations of underlying columns" do
@c.composition :date, :mapping=>[:year, :month, :day]
o = @c.new
def o.validate
[:year, :month, :day].each{|c| errors.add(c, "not present") unless send(c)}
end
o.valid?.must_equal false
o.date = Date.new(1, 2, 3)
o.valid?.must_equal true
end
it "should set column values even when not validating" do
@c.composition :date, :mapping=>[:year, :month, :day]
@c.load({}).set(:date=>Date.new(4, 8, 12)).save(:validate=>false)
sql = DB.sqls.last
sql.must_include("year = 4")
sql.must_include("month = 8")
sql.must_include("day = 12")
end
it ".compositions should return the reflection hash of compositions" do
@c.compositions.must_equal({})
@c.composition :date, :mapping=>[:year, :month, :day]
@c.compositions.keys.must_equal [:date]
r = @c.compositions.values.first
r[:mapping].must_equal [:year, :month, :day]
r[:composer].must_be_kind_of Proc
r[:decomposer].must_be_kind_of Proc
end
it "#compositions should be a hash of cached values of compositions" do
@o.compositions.must_equal({})
@c.composition :date, :mapping=>[:year, :month, :day]
@o.date
@o.compositions.must_equal(:date=>Date.new(1, 2, 3))
end
it "should work with custom :composer and :decomposer options" do
@c.composition :date, :composer=>proc{Date.new(year+1, month+2, day+3)}, :decomposer=>proc{[:year, :month, :day].each{|s| self.send("#{s}=", date.send(s) * 2)}}
@o.date.must_equal Date.new(2, 4, 6)
@o.save
sql = DB.sqls.last
sql.must_include("year = 4")
sql.must_include("month = 8")
sql.must_include("day = 12")
end
it "should allow call super in composition getter and setter method definition in class" do
@c.composition :date, :mapping=>[:year, :month, :day]
@c.class_eval do
def date
super + 1
end
def date=(v)
super(v - 3)
end
end
@o.date.must_equal Date.new(1, 2, 4)
@o.compositions[:date].must_equal Date.new(1, 2, 3)
@o.date = Date.new(1, 3, 5)
@o.compositions[:date].must_equal Date.new(1, 3, 2)
@o.date.must_equal Date.new(1, 3, 3)
end
it "should mark the object as modified whenever the composition is set" do
@c.composition :date, :mapping=>[:year, :month, :day]
@o.modified?.must_equal false
@o.date = Date.new(3, 4, 5)
@o.modified?.must_equal true
end
it "should only decompose existing compositions" do
called = false
@c.composition :date, :composer=>proc{}, :decomposer=>proc{called = true}
called.must_equal false
@o.save
called.must_equal false
@o.date = Date.new(1,2,3)
called.must_equal false
@o.save_changes
called.must_equal true
end
it "should clear compositions cache when refreshing" do
@c.composition :date, :composer=>proc{}, :decomposer=>proc{}
@o.date = Date.new(3, 4, 5)
@o.refresh
@o.compositions.must_equal({})
end
it "should not clear compositions cache when refreshing after save" do
@c.composition :date, :composer=>proc{}, :decomposer=>proc{}
@c.create(:date=>Date.new(3, 4, 5)).compositions.must_equal(:date=>Date.new(3, 4, 5))
end
it "should not clear compositions cache when saving with insert_select" do
@c.dataset = @c.dataset.with_extend do
def supports_insert_select?; true end
def insert_select(*) {:id=>1} end
end
@c.composition :date, :composer=>proc{}, :decomposer=>proc{}
@c.create(:date=>Date.new(3, 4, 5)).compositions.must_equal(:date=>Date.new(3, 4, 5))
end
it "should instantiate compositions lazily" do
@c.composition :date, :mapping=>[:year, :month, :day]
@o.compositions.must_equal({})
@o.date
@o.compositions.must_equal(:date=>Date.new(1,2,3))
end
it "should cache value of composition" do
times = 0
@c.composition :date, :composer=>proc{times+=1}, :decomposer=>proc{}
times.must_equal 0
@o.date
times.must_equal 1
@o.date
times.must_equal 1
end
it ":class option should take an string, symbol, or class" do
@c.composition :date1, :class=>'Date', :mapping=>[:year, :month, :day]
@c.composition :date2, :class=>:Date, :mapping=>[:year, :month, :day]
@c.composition :date3, :class=>Date, :mapping=>[:year, :month, :day]
@o.date1.must_equal Date.new(1, 2, 3)
@o.date2.must_equal Date.new(1, 2, 3)
@o.date3.must_equal Date.new(1, 2, 3)
end
it ":mapping option should work with a single array of symbols" do
c = Class.new do
def initialize(y, m)
@y, @m = y, m
end
def year
@y * 2
end
def month
@m * 3
end
end
@c.composition :date, :class=>c, :mapping=>[:year, :month]
@o.date.year.must_equal 2
@o.date.month.must_equal 6
@o.date = c.new(3, 4)
@o.save
sql = DB.sqls.last
sql.must_include("year = 6")
sql.must_include("month = 12")
end
it ":mapping option should work with an array of two pairs of symbols" do
c = Class.new do
def initialize(y, m)
@y, @m = y, m
end
def y
@y * 2
end
def m
@m * 3
end
end
@c.composition :date, :class=>c, :mapping=>[[:year, :y], [:month, :m]]
@o.date.y.must_equal 2
@o.date.m.must_equal 6
@o.date = c.new(3, 4)
@o.save
sql = DB.sqls.last
sql.must_include("year = 6")
sql.must_include("month = 12")
end
it ":mapping option :composer should return nil if all values are nil" do
@c.composition :date, :mapping=>[:year, :month, :day]
@c.new.date.must_be_nil
end
it ":mapping option :decomposer should set all related fields to nil if nil" do
@c.composition :date, :mapping=>[:year, :month, :day]
@o.date = nil
@o.save
sql = DB.sqls.last
sql.must_include("year = NULL")
sql.must_include("month = NULL")
sql.must_include("day = NULL")
end
it "should work with frozen instances" do
@c.composition :date, :mapping=>[:year, :month, :day]
@o.freeze
@o.date.must_equal Date.new(1, 2, 3)
proc{@o.date = Date.today}.must_raise
end
it "should have #dup duplicate compositions" do
@c.composition :date, :mapping=>[:year, :month, :day]
@o.date.must_equal Date.new(1, 2, 3)
@o.dup.compositions.must_equal @o.compositions
@o.dup.compositions.wont_be_same_as(@o.compositions)
end
it "should work correctly with subclasses" do
@c.composition :date, :mapping=>[:year, :month, :day]
c = Class.new(@c)
o = c.load(:id=>1, :year=>1, :month=>2, :day=>3)
o.date.must_equal Date.new(1, 2, 3)
o.save
sql = DB.sqls.last
sql.must_include("year = 1")
sql.must_include("month = 2")
sql.must_include("day = 3")
end
it "should freeze composition metadata when freezing model class" do
@c.composition :date, :mapping=>[:year, :month, :day]
@c.freeze
@c.compositions.frozen?.must_equal true
@c.compositions[:date].frozen?.must_equal true
end
end
| 31.860465 | 164 | 0.636983 |
010233f6929d37e1e8a563013e9ad3bc76e73346
| 1,063 |
# == Schema Information
#
# Table name: custom_fields
#
# id :integer not null, primary key
# type :string(255)
# sort_priority :integer
# search_filter :boolean default(TRUE), not null
# created_at :datetime not null
# updated_at :datetime not null
# community_id :integer
# required :boolean default(TRUE)
# min :float(24)
# max :float(24)
# allow_decimals :boolean default(FALSE)
# entity_type :integer default("for_listing")
# public :boolean default(FALSE)
# assignment :integer default("unassigned")
# search_category_filter :boolean default(FALSE)
#
# Indexes
#
# index_custom_fields_on_community_id (community_id)
# index_custom_fields_on_search_filter (search_filter)
#
class TextField < CustomField
def with_type(&block)
block.call(:text)
end
end
| 33.21875 | 67 | 0.549389 |
edb12aec1809c984aac66f975c5dd63d5fa780e9
| 97 |
class Frog < ActiveRecord::Base
# code goes here
has_many :tadpoles
belongs_to :pond
end
| 12.125 | 31 | 0.721649 |
0160c64f62b4f46d8785ded759e369e9143d4e48
| 944 |
cask :v1 => 'intellij-idea-ce' do
version '14.1.1'
sha256 'a7060871e1371163dfad44183836b3bb78e688d7c1ce94dcb61987e1697fe414'
url "http://download.jetbrains.com/idea/ideaIC-#{version}.dmg"
name 'IntelliJ IDEA Community Edition'
homepage 'https://www.jetbrains.com/idea/'
license :apache
app 'IntelliJ IDEA 14 CE.app'
zap :delete => [
'~/Library/Application Support/IdeaIC14',
'~/Library/Preferences/IdeaIC14',
'~/Library/Caches/IdeaIC14',
'~/Library/Logs/IdeaIC14',
]
caveats <<-EOS.undent
#{token} requires Java 6 like any other IntelliJ-based IDE.
You can install it with
brew cask install caskroom/homebrew-versions/java6
The vendor (JetBrains) doesn't support newer versions of Java (yet)
due to several critical issues, see details at
https://intellij-support.jetbrains.com/entries/27854363
EOS
end
| 31.466667 | 75 | 0.663136 |
21f82916e28bc0ffc78d1fe8af01d3a892290e85
| 157 |
Factory.define :feature, :class => Arturo::Feature do |f|
f.sequence(:symbol) { |n| "feature_#{n}".to_sym }
f.deployment_percentage { |_| rand(101) }
end
| 39.25 | 57 | 0.66879 |
084c146abe7d17aa7f36602a051c63d4d1f51241
| 7,043 |
# frozen_string_literal: true
module API
class Jobs < Grape::API::Instance
include PaginationParams
before { authenticate! }
params do
requires :id, type: String, desc: 'The ID of a project'
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
helpers do
params :optional_scope do
optional :scope, types: [String, Array[String]], desc: 'The scope of builds to show',
values: ::CommitStatus::AVAILABLE_STATUSES,
coerce_with: ->(scope) {
case scope
when String
[scope]
when ::Hash
scope.values
when ::Array
scope
else
['unknown']
end
}
end
end
desc 'Get a projects jobs' do
success Entities::Ci::Job
end
params do
use :optional_scope
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
get ':id/jobs' do
authorize_read_builds!
builds = user_project.builds.order('id DESC')
builds = filter_builds(builds, params[:scope])
builds = builds.preload(:user, :job_artifacts_archive, :job_artifacts, :runner, pipeline: :project)
present paginate(builds), with: Entities::Ci::Job
end
# rubocop: enable CodeReuse/ActiveRecord
desc 'Get pipeline jobs' do
success Entities::Ci::Job
end
params do
requires :pipeline_id, type: Integer, desc: 'The pipeline ID'
use :optional_scope
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
get ':id/pipelines/:pipeline_id/jobs' do
authorize!(:read_pipeline, user_project)
pipeline = user_project.all_pipelines.find(params[:pipeline_id])
authorize!(:read_build, pipeline)
builds = pipeline.builds
builds = filter_builds(builds, params[:scope])
builds = builds.preload(:job_artifacts_archive, :job_artifacts, project: [:namespace])
present paginate(builds), with: Entities::Ci::Job
end
# rubocop: enable CodeReuse/ActiveRecord
desc 'Get pipeline bridge jobs' do
success ::API::Entities::Ci::Bridge
end
params do
requires :pipeline_id, type: Integer, desc: 'The pipeline ID'
use :optional_scope
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
get ':id/pipelines/:pipeline_id/bridges' do
authorize!(:read_build, user_project)
pipeline = user_project.ci_pipelines.find(params[:pipeline_id])
authorize!(:read_pipeline, pipeline)
bridges = pipeline.bridges
bridges = filter_builds(bridges, params[:scope])
bridges = bridges.preload(
:metadata,
downstream_pipeline: [project: [:route, { namespace: :route }]],
project: [:namespace]
)
present paginate(bridges), with: ::API::Entities::Ci::Bridge
end
# rubocop: enable CodeReuse/ActiveRecord
desc 'Get a specific job of a project' do
success Entities::Ci::Job
end
params do
requires :job_id, type: Integer, desc: 'The ID of a job'
end
get ':id/jobs/:job_id' do
authorize_read_builds!
build = find_build!(params[:job_id])
present build, with: Entities::Ci::Job
end
# TODO: We should use `present_disk_file!` and leave this implementation for backward compatibility (when build trace
# is saved in the DB instead of file). But before that, we need to consider how to replace the value of
# `runners_token` with some mask (like `xxxxxx`) when sending trace file directly by workhorse.
desc 'Get a trace of a specific job of a project'
params do
requires :job_id, type: Integer, desc: 'The ID of a job'
end
get ':id/jobs/:job_id/trace' do
authorize_read_builds!
build = find_build!(params[:job_id])
header 'Content-Disposition', "infile; filename=\"#{build.id}.log\""
content_type 'text/plain'
env['api.format'] = :binary
trace = build.trace.raw
body trace
end
desc 'Cancel a specific job of a project' do
success Entities::Ci::Job
end
params do
requires :job_id, type: Integer, desc: 'The ID of a job'
end
post ':id/jobs/:job_id/cancel' do
authorize_update_builds!
build = find_build!(params[:job_id])
authorize!(:update_build, build)
build.cancel
present build, with: Entities::Ci::Job
end
desc 'Retry a specific build of a project' do
success Entities::Ci::Job
end
params do
requires :job_id, type: Integer, desc: 'The ID of a build'
end
post ':id/jobs/:job_id/retry' do
authorize_update_builds!
build = find_build!(params[:job_id])
authorize!(:update_build, build)
break forbidden!('Job is not retryable') unless build.retryable?
build = ::Ci::Build.retry(build, current_user)
present build, with: Entities::Ci::Job
end
desc 'Erase job (remove artifacts and the trace)' do
success Entities::Ci::Job
end
params do
requires :job_id, type: Integer, desc: 'The ID of a build'
end
post ':id/jobs/:job_id/erase' do
authorize_update_builds!
build = find_build!(params[:job_id])
authorize!(:erase_build, build)
break forbidden!('Job is not erasable!') unless build.erasable?
build.erase(erased_by: current_user)
present build, with: Entities::Ci::Job
end
desc 'Trigger a actionable job (manual, delayed, etc)' do
success Entities::Ci::Job
detail 'This feature was added in GitLab 8.11'
end
params do
requires :job_id, type: Integer, desc: 'The ID of a Job'
end
post ":id/jobs/:job_id/play" do
authorize_read_builds!
build = find_build!(params[:job_id])
authorize!(:update_build, build)
bad_request!("Unplayable Job") unless build.playable?
build.play(current_user)
status 200
present build, with: Entities::Ci::Job
end
end
helpers do
# rubocop: disable CodeReuse/ActiveRecord
def filter_builds(builds, scope)
return builds if scope.nil? || scope.empty?
available_statuses = ::CommitStatus::AVAILABLE_STATUSES
unknown = scope - available_statuses
render_api_error!('Scope contains invalid value(s)', 400) unless unknown.empty?
builds.where(status: available_statuses && scope)
end
# rubocop: enable CodeReuse/ActiveRecord
end
end
end
| 31.58296 | 123 | 0.596621 |
e884f3dfa056040f6847c07cc30df4eab3788721
| 918 |
# frozen_string_literal: true
require 'minitest/autorun'
require 'jekyll-money2/core'
class TestMoneyFromAmount < Minitest::Test
def test_processes_formatted_currency_input
assert_equal('$1,000.00', JekyllMoney2::Core.money_from_amount(1000))
assert_equal('$1,000.00', JekyllMoney2::Core.money_from_amount(1000.00))
assert_equal('$1,000.00', JekyllMoney2::Core.money_from_amount(1000.00))
end
def test_returns_string
assert_instance_of(String, JekyllMoney2::Core.money_from_amount(10.00))
end
def test_accepts_multiple_currency_formats
assert_equal('$10.00', JekyllMoney2::Core.money_from_amount(10.00))
assert_equal('Β£1.00', JekyllMoney2::Core.money_from_amount(1.00, 'GBP'))
assert_equal('β¬1,00', JekyllMoney2::Core.money_from_amount(1.00, 'EUR'))
end
def test_accepts_value_as_string
assert_equal('$10.00', JekyllMoney2::Core.money_from_amount('10.00'))
end
end
| 34 | 76 | 0.763617 |
d5e7e9c094f82f98c76e742404f99beaaf9e216a
| 425 |
cask 'frizzix' do
version '1.6.24'
sha256 '92d4555e0029251fb023a3dbe9ae4b7d826b2eb6c21cf028f13fb7e5a8f6dfcb'
url "http://frizzix.de/downloads/Frizzix_#{version}.dmg"
appcast 'http://frizzix.de/downloads/FrizzixUpdate.xml'
name 'Frizzix'
homepage 'http://mac.frizzix.de/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'Frizzix.app'
end
| 32.692308 | 115 | 0.755294 |
f8700053e0da77377156add13b8c08953b05906c
| 1,504 |
=begin
#Selling Partner API for Merchant Fulfillment
#The Selling Partner API for Merchant Fulfillment helps you build applications that let sellers purchase shipping for non-Prime and Prime orders using Amazonβs Buy Shipping Services.
OpenAPI spec version: v0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 3.0.33
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for AmzSpApi::MerchantFulfillmentV0::GetEligibleShipmentServicesResponse
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'GetEligibleShipmentServicesResponse' do
before do
# run before each test
@instance = AmzSpApi::MerchantFulfillmentV0::GetEligibleShipmentServicesResponse.new
end
after do
# run after each test
end
describe 'test an instance of GetEligibleShipmentServicesResponse' do
it 'should create an instance of GetEligibleShipmentServicesResponse' do
expect(@instance).to be_instance_of(AmzSpApi::MerchantFulfillmentV0::GetEligibleShipmentServicesResponse)
end
end
describe 'test attribute "payload"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "errors"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 32 | 182 | 0.777261 |
f8e718e1a256b699a849e9c2b28957c20db2aed7
| 666 |
# frozen_string_literal: true
module Bundle
module Lister
module_function
def list(entries)
entries.each do |entry|
puts entry.name if show? entry.type
end
end
private_class_method
def self.show?(type)
return true if ARGV.include?("--all")
return true if ARGV.include?("--casks") && type == :cask
return true if ARGV.include?("--taps") && type == :tap
return true if ARGV.include?("--mas") && type == :mac_app_store
return true if ARGV.include?("--brews") && type == :brew
return true if type == :brew && ["--casks", "--taps", "--mas"].none? { |e| ARGV.include?(e) }
end
end
end
| 27.75 | 99 | 0.597598 |
ac4b4a285ac4a63a07de63d0b9f2296f19a6061a
| 1,061 |
class CreateMorbids < ActiveRecord::Migration[5.1]
def change
create_table :morbids do |t|
t.references :patient, foreign_key: true, index: true
t.string :pre_existing_diseases_vascular_accident
t.string :pre_existing_diseases_cancer
t.string :pre_existing_diseases_hypertension
t.integer :pre_existing_diseases_cardiopathy
t.integer :pre_existing_diseases_diabetes
t.integer :pre_existing_diseases_renal
t.integer :pre_existing_diseases_pneumopathy
t.text :others_pre_existing_diseases
t.string :allergies_drugs
t.string :allergies_foods
t.string :allergies_cosmetics
t.string :allergies_plaster
t.string :allergies_wool
t.text :others_allergies
t.string :risk_factors_smoking
t.string :risk_factors_ethicism
t.string :risk_factors_chemotherapy
t.string :risk_factors_radiotherapy
t.string :risk_factors_chemical_dependency
t.string :risk_factors_violence
t.text :others_risk_factors
t.timestamps
end
end
end
| 34.225806 | 59 | 0.744581 |
1caf48035bb17ffcca30b423220d6f8c66fd98b2
| 7,316 |
run "if uname | grep -q 'Darwin'; then pgrep spring | xargs kill -9; fi"
# GEMFILE
########################################
inject_into_file 'Gemfile', before: 'group :development, :test do' do
<<~RUBY
gem 'devise'
gem 'autoprefixer-rails'
gem 'font-awesome-sass'
gem 'simple_form'
RUBY
end
inject_into_file 'Gemfile', after: 'group :development, :test do' do
<<-RUBY
gem 'pry-byebug'
gem 'pry-rails'
gem 'dotenv-rails'
gem 'rspec-rails'
RUBY
end
gsub_file('Gemfile', /# gem 'redis'/, "gem 'redis'")
# Assets
########################################
run 'rm -rf app/assets/stylesheets'
run 'rm -rf vendor'
run 'curl -L https://github.com/lewagon/stylesheets/archive/master.zip > stylesheets.zip'
run 'unzip stylesheets.zip -d app/assets && rm stylesheets.zip && mv app/assets/rails-stylesheets-master app/assets/stylesheets'
# Dev environment
########################################
gsub_file('config/environments/development.rb', /config\.assets\.debug.*/, 'config.assets.debug = false')
# Layout
########################################
if Rails.version < "6"
scripts = <<~HTML
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload', defer: true %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
HTML
gsub_file('app/views/layouts/application.html.erb', "<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>", scripts)
end
gsub_file('app/views/layouts/application.html.erb', "<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>", "<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload', defer: true %>")
style = <<~HTML
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
HTML
gsub_file('app/views/layouts/application.html.erb', "<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>", style)
# Flashes
########################################
file 'app/views/shared/_flashes.html.erb', <<~HTML
<% if notice %>
<div class="alert alert-info alert-dismissible fade show m-1" role="alert">
<%= notice %>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<% end %>
<% if alert %>
<div class="alert alert-warning alert-dismissible fade show m-1" role="alert">
<%= alert %>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<% end %>
HTML
run 'curl -L https://raw.githubusercontent.com/maeldd/rails-templates/master/bootstrap/views/_navbar.html.erb > app/views/shared/_navbar.html.erb'
inject_into_file 'app/views/layouts/application.html.erb', after: '<body>' do
<<-HTML
<%= render 'shared/navbar' %>
<%= render 'shared/flashes' %>
HTML
end
# README
########################################
markdown_file_content = <<-MARKDOWN
Rails app generated with [maeldd/rails-templates](https://github.com/maeldd/rails-templates).
MARKDOWN
file 'README.md', markdown_file_content, force: true
# Generators
########################################
generators = <<~RUBY
config.generators do |generate|
generate.assets false
generate.helper false
generate.test_framework :test_unit, fixture: false
end
RUBY
environment generators
########################################
# AFTER BUNDLE
########################################
after_bundle do
# Generators: db + simple form + pages controller
########################################
rails_command 'db:drop db:create db:migrate'
generate('simple_form:install', '--bootstrap')
generate(:controller, 'pages', 'home', '--skip-routes', '--no-test-framework')
# Routes
########################################
route "root to: 'pages#home'"
# Git ignore
########################################
append_file '.gitignore', <<~TXT
# Ignore .env file containing credentials.
.env*
# Ignore Mac and Linux file system files
*.swp
.DS_Store
TXT
# Devise install + user
########################################
generate('devise:install')
generate('devise', 'User')
# RSpec
#######################################
generate('rspec:install')
# App controller
########################################
run 'rm app/controllers/application_controller.rb'
file 'app/controllers/application_controller.rb', <<~RUBY
class ApplicationController < ActionController::Base
#{ "protect_from_forgery with: :exception\n" if Rails.version < "5.2"} before_action :authenticate_user!
end
RUBY
# migrate + devise views
########################################
rails_command 'db:migrate'
generate('devise:views')
# Pages Controller
########################################
run 'rm app/controllers/pages_controller.rb'
file 'app/controllers/pages_controller.rb', <<~RUBY
class PagesController < ApplicationController
skip_before_action :authenticate_user!, only: [ :home ]
def home
end
end
RUBY
# Environments
########################################
environment 'config.action_mailer.default_url_options = { host: "http://localhost:3000" }', env: 'development'
environment 'config.action_mailer.default_url_options = { host: "http://TODO_PUT_YOUR_DOMAIN_HERE" }', env: 'production'
# Webpacker / Yarn
########################################
run 'yarn add popper.js jquery bootstrap'
append_file 'app/javascript/packs/application.js', <<~JS
// ----------------------------------------------------
// Note: ABOVE IS RAILS DEFAULT CONFIGURATION
// WRITE YOUR OWN JS STARTING FROM HERE π
// ----------------------------------------------------
// External imports
import "bootstrap";
// Internal imports, e.g:
// import { initSelect2 } from '../components/init_select2';
document.addEventListener('turbolinks:load', () => {
// Call your functions here, e.g:
// initSelect2();
});
JS
inject_into_file 'config/webpack/environment.js', before: 'module.exports' do
<<~JS
const webpack = require('webpack');
// Preventing Babel from transpiling NodeModules packages
environment.loaders.delete('nodeModules');
// Bootstrap 4 has a dependency over jQuery & Popper.js:
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Popper: ['popper.js', 'default']
})
);
JS
end
# Dotenv
########################################
run 'touch .env'
# Rubocop
########################################
run 'curl -L https://raw.githubusercontent.com/maeldd/rails-templates/master/.rubocop.yml -o .rubocop.yml -s'
# Git
########################################
git add: '.'
git commit: "-m 'Initial commit with devise template from https://github.com/maeldd/rails-templates'"
# Fix puma config
gsub_file('config/puma.rb', 'pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }', '# pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }')
end
| 32.954955 | 222 | 0.583789 |
280bddc230113f2b7aba7a312f67aa4d8976c62d
| 1,805 |
module Iptablez
module Commands
# @todo Add inline document to this.
module Interface
def self.delete_chain(name: false, all: false)
if name
DeleteChain.chain(name: name)
elsif all
DeleteChain.all
else
raise "No chain name/all specified."
end
end
def self.flush(chain: false, all: true)
if chain
Flush.chain(name: chain)
elsif all
Flush.all
else
raise "No chain/all specified."
end
end
def self.list(chain: false, all: true, number: false)
if chain && ! number
List.chain(name: chain)
elsif number && chain
List.number(chain: chain, number: number)
elsif all
List.all
else
raise "No chain/number/all specified."
end
end
def self.new_chain(name:)
NewChain.chain(name: name)
end
def self.policy(target:, chain: false, all: true)
if chain && target
Policy.chain(name: chain, target: target)
elsif all && target
Policy.all(target: target)
else
raise "No chain/target/all specified."
end
end
def self.rename_chain(from:, to:)
if from && to
RenameChain.chain(from: from, to: to)
else
raise "No from/to specified."
end
end
def self.version(full: false)
if full
Version.full
else
Version.number
end
end
def self.zero(all: true, chain: false)
if chain
Zero.chain(name: chain)
elsif all
Zero.all
else
raise "No all/chain specified."
end
end
end
end
end
| 22.283951 | 60 | 0.52133 |
91c7ff6329d749bc9cca725430ceceefe59f013e
| 706 |
Rails.application.routes.draw do
get 'password_resets/new'
get 'password_resets/edit'
root 'static_pages#home'
get '/help', to: 'static_pages#help', as: 'helf'
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
resources :users
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
| 35.3 | 101 | 0.674221 |
acf650b79e3c881ff2a87fb9aff5983b51ab03ec
| 481 |
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end
| 17.814815 | 58 | 0.596674 |
03a4cb663cd0699da8cf11aeb0e20c40e5d3f1f9
| 804 |
require 'test_helper'
class <%= sessions_class_name %>ControllerTest < ActionController::TestCase
context "new action" do
should "render new template" do
get :new
assert_template 'new'
end
end
context "create action" do
should "render new template when authentication is invalid" do
<%= user_class_name %>.stubs(:authenticate).returns(nil)
post :create
assert_template 'new'
assert_nil session['<%= user_singular_name %>_id']
end
should "redirect when authentication is valid" do
<%= user_class_name %>.stubs(:authenticate).returns(<%= user_class_name %>.first)
post :create
assert_redirected_to root_url
assert_equal <%= user_class_name %>.first.id, session['<%= user_singular_name %>_id']
end
end
end
| 29.777778 | 91 | 0.679104 |
e962cb45e435e8f96ea6697b663c1e7c244978a9
| 119 |
class AddLogoToPartners < ActiveRecord::Migration[5.1]
def change
add_column :partners, :logo, :string
end
end
| 19.833333 | 54 | 0.739496 |
f74d42e38ced9edf7b32e93bef9c52beac673b45
| 2,804 |
class PawooApiClient
extend Memoist
PROFILE1 = %r!\Ahttps?://pawoo\.net/web/accounts/(\d+)!
PROFILE2 = %r!\Ahttps?://pawoo\.net/@([^/]+)!
STATUS1 = %r!\Ahttps?://pawoo\.net/web/statuses/(\d+)!
STATUS2 = %r!\Ahttps?://pawoo\.net/@.+?/([^/]+)!
class MissingConfigurationError < StandardError; end
class Account
attr_reader :json
def self.is_match?(url)
if url =~ PROFILE1
return $1
end
if url =~ PROFILE2
return $1
end
false
end
def initialize(json)
@json = json
end
def profile_url
json["url"]
end
def account_name
json["username"]
end
def image_url
nil
end
def image_urls
[]
end
def tags
[]
end
def commentary
nil
end
def to_h
json
end
end
class Status
attr_reader :json
def self.is_match?(url)
if url =~ STATUS1
return $1
end
if url =~ STATUS2
return $1
end
false
end
def initialize(json)
@json = json
end
def profile_url
json["account"]["url"]
end
def account_name
json["account"]["username"]
end
def image_url
image_urls.first
end
def image_urls
json["media_attachments"].map {|x| x["url"]}
end
def tags
json["tags"].map { |tag| [tag["name"], tag["url"]] }
end
def commentary
commentary = ""
commentary << "<p>#{json["spoiler_text"]}</p>" if json["spoiler_text"].present?
commentary << json["content"]
commentary
end
def to_h
json
end
end
def get(url)
if id = Status.is_match?(url)
begin
data = JSON.parse(access_token.get("/api/v1/statuses/#{id}").body)
rescue
data = {
"account" => {},
"media_attachments" => [],
"tags" => [],
"content" => "",
}
end
return Status.new(data)
end
if id = Account.is_match?(url)
begin
data = JSON.parse(access_token.get("/api/v1/accounts/#{id}").body)
rescue
data = {}
end
Account.new(data)
end
end
private
def fetch_access_token
raise MissingConfigurationError, "missing pawoo client id" if Danbooru.config.pawoo_client_id.nil?
raise MissingConfigurationError, "missing pawoo client secret" if Danbooru.config.pawoo_client_secret.nil?
Cache.get("pawoo-token") do
result = client.client_credentials.get_token
result.token
end
end
def access_token
OAuth2::AccessToken.new(client, fetch_access_token)
end
def client
OAuth2::Client.new(Danbooru.config.pawoo_client_id, Danbooru.config.pawoo_client_secret, :site => "https://pawoo.net")
end
memoize :client
end
| 17.859873 | 122 | 0.57311 |
e87071e645f43d5757947ef206c9ddac737eb6e7
| 1,188 |
cask "flash-player-debugger-npapi" do
version "32.0.0.445"
sha256 "a3cd363098648f989c5dbc356b79bd9c54083b8149f5669bc13b3b3275017a2f"
url "https://fpdownload.adobe.com/pub/flashplayer/updaters/#{version.major}/flashplayer_#{version.major}_plugin_debug.dmg"
appcast "https://www.adobe.com/support/flashplayer/debug_downloads.html"
name "Adobe Flash Player NPAPI (plugin for Safari and Firefox) content debugger"
homepage "https://www.adobe.com/support/flashplayer/debug_downloads.html"
pkg "Install Adobe Flash Player Debugger.app/Contents/Resources/Adobe Flash Player Debugger.pkg"
uninstall pkgutil: "com.adobe.pkg.FlashPlayer",
launchctl: "com.adobe.fpsaud",
delete: [
"/Library/Application Support/Adobe/Flash Player Install Manager",
"/Library/Internet Plug-Ins/Flash Player.plugin",
]
zap trash: [
"/Library/Internet Plug-Ins/flashplayer.xpt",
"~/Library/Caches/Adobe/Flash Player",
"~/Library/Logs/FlashPlayerInstallManager.log",
"~/Library/Preferences/Macromedia/Flash Player",
"~/Library/Saved Application State/com.adobe.flashplayer.installmanager.savedState",
]
end
| 44 | 124 | 0.729798 |
6a53a5a57f0afdee102676fce0b89e3f9f22a60a
| 8,162 |
require_relative "../../test_helper"
class ContentRendererTest < ActiveSupport::TestCase
class TestTag < ComfortableMexicanSofa::Content::Tag
def content
"test tag content"
end
end
class TestNestedTag < ComfortableMexicanSofa::Content::Tag
def content
"test {{cms:test}} content"
end
end
class TestBlockTag < ComfortableMexicanSofa::Content::Block
# ...
end
DEFAULT_REGISTERED_TAGS = {
"wysiwyg" => ComfortableMexicanSofa::Content::Tag::Wysiwyg,
"text" => ComfortableMexicanSofa::Content::Tag::Text,
"textarea" => ComfortableMexicanSofa::Content::Tag::TextArea,
"markdown" => ComfortableMexicanSofa::Content::Tag::Markdown,
"datetime" => ComfortableMexicanSofa::Content::Tag::Datetime,
"date" => ComfortableMexicanSofa::Content::Tag::Date,
"number" => ComfortableMexicanSofa::Content::Tag::Number,
"checkbox" => ComfortableMexicanSofa::Content::Tag::Checkbox,
"file" => ComfortableMexicanSofa::Content::Tag::File,
"files" => ComfortableMexicanSofa::Content::Tag::Files,
"snippet" => ComfortableMexicanSofa::Content::Tag::Snippet,
"asset" => ComfortableMexicanSofa::Content::Tag::Asset,
"file_link" => ComfortableMexicanSofa::Content::Tag::FileLink,
"helper" => ComfortableMexicanSofa::Content::Tag::Helper,
"partial" => ComfortableMexicanSofa::Content::Tag::Partial,
"template" => ComfortableMexicanSofa::Content::Tag::Template
}.freeze
setup do
@template = ComfortableMexicanSofa::Content::Renderer.new(comfy_cms_pages(:default))
ComfortableMexicanSofa::Content::Renderer.register_tag(:test, TestTag)
ComfortableMexicanSofa::Content::Renderer.register_tag(:test_nested, TestNestedTag)
ComfortableMexicanSofa::Content::Renderer.register_tag(:test_block, TestBlockTag)
end
teardown do
ComfortableMexicanSofa::Content::Renderer.tags.delete("test")
ComfortableMexicanSofa::Content::Renderer.tags.delete("test_nested")
ComfortableMexicanSofa::Content::Renderer.tags.delete("test_block")
end
# Test helper so we don't have to do this each time
def render_string(string, template = @template)
tokens = template.tokenize(string)
nodes = template.nodes(tokens)
template.render(nodes)
end
# -- Tests -------------------------------------------------------------------
def test_tags
assert_equal DEFAULT_REGISTERED_TAGS.merge(
"test" => ContentRendererTest::TestTag,
"test_nested" => ContentRendererTest::TestNestedTag,
"test_block" => ContentRendererTest::TestBlockTag
), ComfortableMexicanSofa::Content::Renderer.tags
end
def test_register_tags
ComfortableMexicanSofa::Content::Renderer.register_tag(:other, TestTag)
assert_equal DEFAULT_REGISTERED_TAGS.merge(
"test" => ContentRendererTest::TestTag,
"test_nested" => ContentRendererTest::TestNestedTag,
"test_block" => ContentRendererTest::TestBlockTag,
"other" => ContentRendererTest::TestTag
), ComfortableMexicanSofa::Content::Renderer.tags
ensure
ComfortableMexicanSofa::Content::Renderer.tags.delete("other")
end
def test_tokenize
assert_equal ["test text"], @template.tokenize("test text")
end
def test_tokenize_with_tag
assert_equal ["test ", { tag_class: "tag", tag_params: "" }, " text"],
@template.tokenize("test {{cms:tag}} text")
end
def test_tokenize_with_tag_and_params
assert_equal ["test ", { tag_class: "tag", tag_params: "name, key:val" }, " text"],
@template.tokenize("test {{cms:tag name, key:val}} text")
end
def test_tokenize_with_invalid_tag
assert_equal ["test {{abc:tag}} text"],
@template.tokenize("test {{abc:tag}} text")
end
def test_tokenize_with_newlines
assert_equal [{ tag_class: "test", tag_params: "" }, "\n", { tag_class: "test", tag_params: "" }],
@template.tokenize("{{cms:test}}\n{{cms:test}}")
end
def test_nodes
tokens = @template.tokenize("test")
nodes = @template.nodes(tokens)
assert_equal ["test"], nodes
end
def test_nodes_with_tags
tokens = @template.tokenize("test {{cms:test}} content {{cms:test}}")
nodes = @template.nodes(tokens)
assert_equal 4, nodes.count
assert_equal "test ", nodes[0]
assert nodes[1].is_a?(ContentRendererTest::TestTag)
assert_equal " content ", nodes[2]
assert nodes[3].is_a?(ContentRendererTest::TestTag)
end
def test_nodes_with_block_tag
string = "a {{cms:test_block}} b {{cms:end}} c"
tokens = @template.tokenize(string)
nodes = @template.nodes(tokens)
assert_equal 3, nodes.count
assert_equal "a ", nodes[0]
assert_equal " c", nodes[2]
block = nodes[1]
assert block.is_a?(ContentRendererTest::TestBlockTag)
assert_equal [" b "], block.nodes
end
def test_nodes_with_block_tag_and_tag
string = "a {{cms:test_block}} b {{cms:test}} c {{cms:end}} d"
tokens = @template.tokenize(string)
nodes = @template.nodes(tokens)
assert_equal 3, nodes.count
assert_equal "a ", nodes[0]
assert_equal " d", nodes[2]
block = nodes[1]
assert block.is_a?(ContentRendererTest::TestBlockTag)
assert_equal 3, block.nodes.count
assert_equal " b ", block.nodes[0]
assert_equal " c ", block.nodes[2]
tag = block.nodes[1]
assert tag.is_a?(ContentRendererTest::TestTag)
assert_equal ["test tag content"], tag.nodes
end
def test_nodes_with_nested_block_tag
string = "a {{cms:test_block}} b {{cms:test_block}} c {{cms:end}} d {{cms:end}} e"
tokens = @template.tokenize(string)
nodes = @template.nodes(tokens)
assert_equal 3, nodes.count
assert_equal "a ", nodes[0]
assert_equal " e", nodes[2]
block = nodes[1]
assert block.is_a?(ContentRendererTest::TestBlockTag)
assert_equal 3, block.nodes.count
assert_equal " b ", block.nodes[0]
assert_equal " d ", block.nodes[2]
block = block.nodes[1]
assert_equal [" c "], block.nodes
end
def test_nodes_with_unclosed_block_tag
string = "a {{cms:test_block}} b"
tokens = @template.tokenize(string)
assert_exception_raised ComfortableMexicanSofa::Content::Renderer::SyntaxError, "unclosed block detected" do
@template.nodes(tokens)
end
end
def test_nodes_with_closed_tag
string = "a {{cms:end}} b"
tokens = @template.tokenize(string)
assert_exception_raised ComfortableMexicanSofa::Content::Renderer::SyntaxError, "closing unopened block" do
@template.nodes(tokens)
end
end
def test_sanitize_erb
out = @template.sanitize_erb("<% test %>", false)
assert_equal "<% test %>", out
out = @template.sanitize_erb("<% test %>", true)
assert_equal "<% test %>", out
end
def test_render
out = render_string("test")
assert_equal "test", out
end
def test_render_with_tag
out = render_string("a {{cms:text content}} z")
assert_equal "a content z", out
end
def test_render_with_erb
out = render_string("<%= 1 + 1 %>")
assert_equal "<%= 1 + 1 %>", out
end
def test_render_with_erb_allowed
ComfortableMexicanSofa.config.allow_erb = true
out = render_string("<%= 1 + 1 %>")
assert_equal "<%= 1 + 1 %>", out
end
def test_render_with_erb_allowed_via_tag
out = render_string("{{cms:partial path}}")
assert_equal "<%= render partial: \"path\", locals: {} %>", out
end
def test_render_with_nested_tag
string = "a {{cms:text content}} b"
comfy_cms_fragments(:default).update_column(:content, "c {{cms:snippet default}} d")
comfy_cms_snippets(:default).update_column(:content, "e {{cms:helper test}} f")
out = render_string(string)
assert_equal "a c e <%= test() %> f d b", out
end
def test_render_stack_overflow
# making self-referencing content loop here
comfy_cms_snippets(:default).update_column(:content, "a {{cms:snippet default}} b")
message = "Deep tag nesting or recursive nesting detected"
assert_exception_raised ComfortableMexicanSofa::Content::Renderer::Error, message do
render_string("{{cms:snippet default}}")
end
end
end
| 33.178862 | 112 | 0.682308 |
bbfcef93a183c72a02e65e582c4278ee35f7b357
| 1,397 |
require 'nokogiri'
require 'faraday'
require 'itunes_charts/chart_item'
module ITunesCharts
extend self
def charts
%w(albums songs tv-shows movies movie-rentals free-apps paid-apps music-videos)
end
def method_missing(name, *args)
hyphened_name = name.to_s.gsub('_','-')
if charts.include?(hyphened_name)
request(hyphened_name)
else
super(name, *args)
end
end
private
def request(path)
response = Faraday.get("http://www.apple.com/itunes/charts/#{path}/")
doc = Nokogiri::HTML(response.body)
doc.css("div#grid ul li").map do |list_item|
item_link = list_item.at('a')['href']
item_uri = URI.parse(item_link)
item_id = item_uri.path.split('/').last.gsub(/\D/,'')
item_image = list_item.at('img')['src'] rescue nil
item_name = list_item.at('h3 a').content rescue nil
item = ChartItem.new(item_id, item_name, item_link, item_image)
item.parent = identify_parent(list_item)
item
end
end
def identify_parent(list_item)
begin
parent_link = list_item.at('h4 a')['href']
parent_uri = URI.parse(parent_link)
parent_id = parent_uri.path.split('/').last.gsub(/\D/,'')
parent_name = list_item.at('h4 a').content
ChartItem.new(parent_id, parent_name, parent_link)
rescue
nil
end
end
end
| 26.358491 | 83 | 0.634216 |
2119fed69bed7ebe980f4bcef1bd96202fd53d74
| 129 |
require 'test_helper'
class ArticlePlanningTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 16.125 | 51 | 0.72093 |
5d5090eac03829f703a04f44f15f5e1927e34c67
| 3,748 |
#
# Copyright (c) 2015, Arista Networks, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# Neither the name of Arista Networks nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
require 'spec_helper'
include FixtureHelpers
# Tests the type with the minimum number of options required for the
# create to validate that the provider is setting the defaults correctly.
describe Puppet::Type.type(:eos_vrrp).provider(:eos) do
# Puppet RAL memoized methods
let(:resource) do
resource_hash = {
name: 'Vlan150:50',
ensure: :present,
provider: described_class.name
}
Puppet::Type.type(:eos_vrrp).new(resource_hash)
end
let(:provider) { resource.provider }
let(:api) { double('vrrp') }
def vrrp
vrrp = Fixtures[:vrrp]
return vrrp if vrrp
fixture('vrrp', dir: File.dirname(__FILE__))
end
before :each do
allow(described_class.node).to receive(:api).with('vrrp').and_return(api)
allow(provider.node).to receive(:api).with('vrrp').and_return(api)
end
context 'resource (instance) methods' do
describe '#create with minimal options set' do
it 'sets ensure on the resource' do
expect(api).to receive(:create).with('Vlan150', 50,
preempt: true,
enable: true,
primary_ip: '0.0.0.0',
priority: 100,
ip_version: 2,
timers_advertise: 1,
mac_addr_adv_interval: 30,
preempt_delay_min: 0,
preempt_delay_reload: 0,
delay_reload: 0)
provider.create
provider.flush
# Don't need to check the values since they would need to
# be set in the resource above. Just needed to validate
# that the create call to rbeapi had the defaults set.
end
end
describe '#destroy' do
it 'sets ensure to :absent' do
resource[:ensure] = :absent
expect(api).to receive(:delete).with('Vlan150', 50)
provider.destroy
provider.flush
expect(provider.ensure).to eq(:absent)
end
end
end
end
| 38.639175 | 77 | 0.636073 |
6acb64e7e14c02a045d3c0cae68e3d4abfda0ede
| 9,217 |
# Copyright (c) 2008 Michael Fellinger [email protected]
# All files in this distribution are subject to the terms of the Ruby license.
module Ramaze
class Controller
# TODO:
# * fix caching, see todos below
# FILTER = [ :cached, :default ] unless defined?(FILTER)
FILTER = [ :default ] unless defined?(FILTER)
class << self
# Resolve an absolute path in the application by passing it to each
# element of Ramaze::Controller::FILTER.
# If an element does not respond to call it will be sent to self
# instead, in either case with path as argument.
def resolve(path, routed = false)
Thread.current[:routed] = routed
FILTER.each do |filter|
answer = if filter.respond_to?(:call)
filter.call(path)
else
send(filter.to_s, path)
end
return answer if answer
end
raise_no_filter(path)
end
# Default element of FILTER.
# Looks up the path in Cache.resolved and returns it if found.
def cached(path)
if found = Cache.resolved[path]
if found.respond_to?(:relaxed_hash)
return found.dup
else
Log.warn("Found faulty `#{path}' in Cache.resolved, deleting it for sanity.")
Cache.resolved.delete path
end
end
nil
end
# Default element of FILTER.
# The default handler that tries to find the best match for the given
# path in terms of Controller/method/template and given arguments.
# If a match is found it will be cached for further use.
def default(path)
mapping = Global.mapping
controllers = Global.controllers
raise_no_controller(path) if controllers.empty? or mapping.empty?
# TODO:
# * following code is dangerous (DoS):
# patterns = Cache.patterns[path] ||= pattern_for(path)
first_controller = nil
# Look through the possible ways of interpreting the path until we find
# one that matches an existing controller action.
patterns_for(path) do |controller, method, params|
if controller = mapping[controller]
first_controller ||= controller
action = controller.resolve_action(method, *params)
next unless action
template = action.template
valid_action =
if Action.stack.size > 0 || Global.actionless_templates
action.method or (params.empty? && template)
else
action.method
end
if valid_action
# TODO:
# * dangerous as well
# Cache.resolved[path] = action
return action
end
end
end
if !Thread.current[:routed] and new_path = Route.resolve(path)
Log.dev("Routing from `#{path}' to `#{new_path}'")
return resolve(new_path, true)
end
raise_no_action(first_controller, path) if first_controller
raise_no_controller(path)
end
# Try to produce an Action from the given path and paremters with the
# appropiate template if one exists.
def resolve_action(path, *parameter)
path, parameter = path.to_s, parameter.map{|e| e.to_s}
# Use ancestral_trait so if template is set in superclass, it is still found.
if info = ancestral_trait["#{path}_template"]
template = info[:file]
unless template
controller, action = info.values_at :controller, :action
# Controller may not have been explicitly set, in which case use self.
controller ||= self
template = controller.resolve_template(action)
end
end
method, params = resolve_method(path, *parameter)
if method or parameter.empty?
template ||= resolve_template(path)
end
action =
Action.create :path => path,
:method => method,
:params => params,
:template => template,
:controller => self
return false unless action.valid_rest?
action
end
# Search the #template_paths for a fitting template for path.
# Only the first found possibility for the generated glob is returned.
def resolve_template(path)
path = path.to_s
path_converted = path.split('__').inject{|s,v| File.join(s, v) }
possible_paths = [path, path_converted].compact
paths = template_paths.map{|pa|
possible_paths.map{|a|
File.join(pa, a)
}
}.flatten.uniq
glob = "{#{paths.join(',')}}.{#{extension_order.join(',')}}"
Dir[glob].first
end
# Composes an array with the template-paths to look up in the right order.
# Usually this is composed of Global.view_root and the mapping of the
# controller.
def template_paths
if paths = view_root
paths
else
view_root(File.join(Global.view_root, Global.mapping.invert[self]))
end
end
# Based on methodname and arity, tries to find the right method on
# current controller.
def resolve_method(name, *params)
cam = cached_action_methods
if cam.include?(name)
method = name
else
name = name.gsub(/__/, '/')
method = name if cam.include?(name)
end
if method
arity = instance_method(method).arity
if arity < 0 or params.size == arity
return method, params
end
end
return nil, []
end
# List or create a list of action methods to be cached
def cached_action_methods
Cache.action_methods[self] ||= action_methods
end
# methodnames that may be used for current controller.
def action_methods
ancs = relevant_ancestors + action_modules
ancs.reverse.inject [] do |meths, anc|
meths +
anc.public_instance_methods(false).map{|im| im.to_s } -
anc.private_instance_methods(false).map{|im| im.to_s }
end
end
# Array of all modules (so including Ramaze helpers) that are included in
# this controller and where the module is also in the Helper::LOOKUP set.
# Hence this is the included modules whose public methods may be exposed
# as actions of this controller.
def action_modules
Helper::LOOKUP.find_all {|mod| self.include?(mod)}
end
# Iterator that yields potential ways in which a given path could be mapped
# to controller, action and params. It produces them in strict order, with
# longest controller path favoured, then longest action path.
def patterns_for path
# Split into fragments, and remove empty ones (which split may have output).
# The to_s is vital as sometimes we are passed an array.
fragments = path.to_s.split '/'
fragments.delete ''
# Work through all the possible splits of controller and 'the rest' (action
# + params) starting with longest possible controller.
fragments.length.downto(0) do |ca_split|
controller = '/' + fragments[0...ca_split].join('/')
# Work on the remaining portion, generating all the action/params splits.
fragments.length.downto(ca_split) do |ap_split|
action = fragments[ca_split...ap_split].join '__'
params = fragments[ap_split..-1]
if action.empty?
yield controller, 'index', params
else
yield controller, "#{action}__index", params
yield controller, action, params
end
end
end
end
# Uses custom defined engines and all available engines and throws it
# against the extensions for the template to find the most likely
# templating-engine to use ordered by priority and likelyhood.
def extension_order
t_extensions = Template::ENGINES
all_extensions = t_extensions.values.flatten
if engine = ancestral_trait[:engine]
c_extensions = t_extensions.select{|k,v| k == engine}.map{|k,v| v}.flatten
return (c_extensions + all_extensions).uniq
end
all_extensions
end
# Raises Ramaze::Error::NoFilter
# TODO:
# * is this called at all for anybody?
# I think everybody has filters.
def raise_no_filter(path)
raise Ramaze::Error::NoFilter, "No Filter found for `#{path}'"
end
# Raises Ramaze::Error::NoController
def raise_no_controller(path)
raise Ramaze::Error::NoController, "No Controller found for `#{path}'"
end
# Raises Ramaze::Error::NoAction
def raise_no_action(controller, path)
STATE[:controller] = controller
raise Ramaze::Error::NoAction, "No Action found for `#{path}' on #{controller}"
end
end
end
end
| 33.035842 | 89 | 0.598134 |
f8e5b12e6b3b93ec146d4b5886effbc1eaf6d88f
| 2,685 |
module Validation
def all_adjacent_locations(previous_location)
up_letter = "#{previous_location[0].next}#{previous_location[1]}"
up_number = "#{previous_location[0]}#{previous_location[1].next}"
down_letter = "#{(previous_location[0].ord - 1).chr}#{previous_location[1]}"
down_number = "#{previous_location[0]}#{(previous_location[1].ord - 1).chr}"
possibilities = [up_letter, up_number, down_letter, down_number]
end
def random_option(possibilities)
possibilities.delete_at(rand(possibilities.length))
end
def check_for_third_spot(existing_locations)
if existing_locations[0][0] == existing_locations[1][0]
horizontal_placement(existing_locations)
else
vertical_placement(existing_locations)
end
end
def horizontal_placement(existing_locations)
if existing_locations[0][1] == '1'
final_location = existing_locations[0][0] + '3'
elsif existing_locations[0][1] == '3'
final_location = existing_locations[0][0] + '2'
else
final_location = existing_locations[0][0] + %w(1 4).sample
end
end
def vertical_placement(existing_locations)
if existing_locations[0][0] == 'A'
final_location = 'C' + existing_locations[0][1]
elsif existing_locations[0][0] == 'C'
final_location = 'B' + existing_locations[0][1]
else
final_location = %w(A D).sample + existing_locations[0][1]
end
end
def position_wrong_format_or_outside_range?(locations)
!locations.all? do |place|
place[0].between?('A', 'D') && place[1].between?('1', '4')
end
end
def position_taken?(locations, player)
!locations.all? do |place|
player.boards.my_ships.valid_locations.include?(place)
end
end
def positions_include_duplicates?(locations)
true if locations.uniq.size < locations.size
end
def position_wraps?(locations)
if contains(locations, 'A') && contains(locations, 'D')
true
elsif contains(locations, '1') && contains(locations, '4')
true
else
false
end
end
def contains(locations, char)
locations.any? { |place| place[0] == char }
end
def positions_not_adjacent?(locations)
outcome = false
if locations.size < 2
outcome
else
index = 0
while index < locations.size - 1
unless all_adjacent_locations(locations[index]).include?(locations[index + 1])
outcome = true
end
index += 1
end
end
outcome
end
def already_guessed?(input, player)
!player.boards.my_hits_and_misses.valid_locations.include?(input)
end
def too_many_letters?(locations)
locations.any? { |place| place.length > 2}
end
end
| 27.96875 | 86 | 0.675233 |
ab86c8b9a18d07c51c6bb7fd837a658e572f48b7
| 463 |
# This migration comes from sufia (originally 20160328222156)
class AddSocialToUsers < ActiveRecord::Migration
def self.up
add_column :users, :facebook_handle, :string
add_column :users, :twitter_handle, :string
add_column :users, :googleplus_handle, :string
end
def self.down
remove_column :users, :facebook_handle, :string
remove_column :users, :twitter_handle, :string
remove_column :users, :googleplus_handle, :string
end
end
| 30.866667 | 61 | 0.75378 |
21ef794546cd5c2d305adcdf2c733e60de395ba5
| 1,118 |
# frozen_string_literal: true
require_relative 'preprocessed_word_validatable'
module LittleWeasel
module Preprocessors
# This module provides methods to validate preprocessed words types.
# rubocop: disable Layout/LineLength
module PreprocessedWordsValidatable
module_function
def validate_prepreprocessed_words(preprocessed_words:)
raise ArgumentError, validation_error_message(object: preprocessed_words, respond_to: :original_word) unless preprocessed_words.respond_to? :original_word
raise ArgumentError, validation_error_message(object: preprocessed_words, respond_to: :preprocessed_words) unless preprocessed_words.respond_to? :preprocessed_words
preprocessed_words&.preprocessed_words&.each do |preprocessed_word|
PreprocessedWordValidatable.validate_prepreprocessed_word preprocessed_word: preprocessed_word
end
end
def validation_error_message(object:, respond_to:)
"Argument preprocessed_words does not respond to: #{object.class}##{respond_to}"
end
end
# rubocop: enable Layout/LineLength
end
end
| 39.928571 | 172 | 0.785331 |
f8d2d286ff6f7f789a53491a1cc914b28a67c481
| 929 |
#!/usr/bin/env ruby
require File.expand_path('../config/environment', __dir__)
puts "Fixing BinaryBlob and BinaryBlobPart sizes"
blob_ids = BinaryBlobPart.select(:binary_blob_id).where("size != LENGTH(data)")
BinaryBlob.where(:id => blob_ids).find_each do |bb|
bb_size = bb.binary_blob_parts.inject(0) do |total_size, part|
data = part.read_attribute(:data) # avoid error due to size mismatch
size = data.bytesize
# binary_blob_parts size is allowed to be nil
if part.size && part.size != size
puts "BinaryBlobPart #{part.id}: #{part.size} -> #{size}"
part.update_attribute(:size, size)
end
total_size + size
end
# binary_blobs size is allowed to be nil
if bb.size && bb.size != bb_size
puts "BinaryBlob #{bb.id}: #{bb.size} -> #{bb_size}"
bb.update_attribute(:size, bb_size)
end
# clear the binary_blob_parts from memory
bb.send(:clear_association_cache)
end
| 29.967742 | 79 | 0.693219 |
26c14bdf02da6024cb8b8e051834a58034169eab
| 1,031 |
require 'semantic'
module JSLockfiles
class PackageSpecification
attr_reader :lockfile_source, :name, :resolved, :integrity, \
:version_ranges, :version_string, :version, :dev_only, \
:bundled, :optional, :dependencies
def initialize(package_hash)
@lockfile_source = package_hash[:source]
@name = package_hash[:name]
@resolved = package_hash[:resolved]
@integrity = package_hash[:integrity]
@version_ranges = package_hash[:version_ranges]
@version_string = package_hash[:version]
@version = Semantic::Version.new @version_string
@dependencies = package_hash[:dependencies].map { |d|
[ d[:name], d[:version], d[:resolved] ]
}
@dev_only = package_hash[:dev_only]
if @dev_only.nil?
@dev_only = false
end
@bundled = package_hash[:bundled]
if @bundled.nil?
@bundled = false
end
@optional = package_hash[:optional]
if @optional.nil?
@optional = false
end
end
end
end
| 29.457143 | 65 | 0.640155 |
acf31318ab5be90f09b9c8c68d3e1a5965fec7a5
| 522 |
ΠΠ»Π°Π²Π° ΠΊΠΎΠ½ΡΡΠΎΠ»ΡΠ½ΠΎ-Π΄ΠΈΡΡΠΈΠΏΠ»ΠΈΠ½Π°ΡΠ½ΠΎΠ³ΠΎ ΠΊΠΎΠΌΠΈΡΠ΅ΡΠ° Π Π€Π‘ ΠΡΡΡΡ ΠΡΠΈΠ³ΠΎΡΡΠ½ ΡΠΎΠΎΠ±ΡΠΈΠ», ΡΡΠΎ "ΠΡΠ±Π°Π½Ρ" Π±ΡΠ» ΠΎΡΡΡΠ°ΡΠΎΠ²Π°Π½ Π½Π° 500 ΡΡΡΡΡ ΡΡΠ±Π»Π΅ΠΉ, ΠΏΠ΅ΡΠ΅Π΄Π°Π΅Ρ ΠΊΠΎΡΡΠ΅ΡΠΏΠΎΠ½Π΄Π΅Π½Ρ "Π‘Π" Π€ΠΈΠ»ΠΈΠΏΠΏ PAPENKOV ΠΎΡ ΠΠΎΠΌΠ° Π€ΡΡΠ±ΠΎΠ»Π°.
Π’Π°ΠΊΠΈΠ΅ ΡΠ°Π½ΠΊΡΠΈΠΈ Π² ΠΎΡΠ½ΠΎΡΠ΅Π½ΠΈΠΈ ΠΡΠ°ΡΠ½ΠΎΠ΄Π°ΡΡΠΊΠΎΠ³ΠΎ ΠΊΠ»ΡΠ±Π° Π±ΡΠ»ΠΈ ΠΏΡΠΈΠΌΠ΅Π½Π΅Π½Ρ Π΄Π»Ρ ΡΠΆΠΈΠ³Π°Π½ΠΈΡ Π² ΠΠ°Π³Π΅ΡΡΠ°Π½Π΅ ΡΠ»Π°Π³ Π±ΠΎΠ»Π΅Π»ΡΡΠΈΠΊΠΎΠ² Π½Π° ΡΡΠΈΠ±ΡΠ½Π°Ρ
Π²ΠΎ Π²ΡΠ΅ΠΌΡ Π΄ΠΎΠΌΠ°ΡΠ½Π΅Π³ΠΎ ΠΌΠ°ΡΡΠ° 14-Π³ΠΎ ΡΡΡΠ° ΠΏΡΠΎΡΠΈΠ² "ΠΠ½ΠΆΠΈ".
ΠΠ° Π²ΡΡΡΠ΅ΡΠ΅ Π±ΡΠ»ΠΈ ΠΏΡΠ΅Π΄ΡΡΠ°Π²ΠΈΡΠ΅Π»ΠΈ ΠΎΠ±ΠΎΠΈΡ
ΠΊΠ»ΡΠ±ΠΎΠ², ΡΠ΅Π»ΠΎΠ²Π΅ΠΊ ΠΈΠ· Π Π€ΠΠ.
ΠΡ ΠΈΠ·ΡΡΠ°Π»ΠΈ Π²ΡΠ΅ ΠΈΠΌΠ΅ΡΡΠΈΠ΅ΡΡ ΠΌΠ°ΡΠ΅ΡΠΈΠ°Π»Ρ.
"ΠΡΠ±Π°Π½Ρ" Π±ΡΠ» ΠΎΡΡΡΠ°ΡΠΎΠ²Π°Π½ Π½Π° 500 ΡΡΡΡΡ ΡΡΠ±Π»Π΅ΠΉ Π·Π° Π½Π΅Π·Π°ΠΊΠΎΠ½Π½ΠΎΠ΅ ΠΏΠΎΠ²Π΅Π΄Π΅Π½ΠΈΠ΅ Π·ΡΠΈΡΠ΅Π»Π΅ΠΉ.
| 87 | 179 | 0.827586 |
0334ab9c598631258c9f017782cd2b6d5f7c4dd6
| 58 |
class Folder < ApplicationRecord
has_many :images
end
| 14.5 | 32 | 0.775862 |
615bebbb81ca155e29664dcaa15309907401fdff
| 667 |
##
# This part of the module defines the generators related with numbers
module Cobaya::Generators
##
# A generator that creates random numbers
#
# :reek:BooleanParameter
class NumGen
def initialize(limit, neg = true)
@limit = limit
@neg = neg
end
def generate
new_num = rand @limit
if @neg && rand < 0.5
-new_num
else
new_num
end
end
end
##
# Returns an integer generator
#
# :reek:UtilityFunction
def int(max_int)
NumGen.new max_int
end
##
# Returns a float generator
#
# :reek:UtilityFunction
def float(max_float)
NumGen.new max_float.to_f
end
end
| 16.268293 | 69 | 0.622189 |
1a1fe5c86f162d364791ba42ef5b6dedc302fcd6
| 250 |
# Don't forget! This file needs to be 'required' in its spec file
# See README.md for instructions on how to do this
def fizzbuzz(int)
if int % 15 == 0
"FizzBuzz"
elsif int % 5 == 0
"Buzz"
elsif int % 3 == 0
"Fizz"
end
end
| 17.857143 | 65 | 0.604 |
334471634a63f7d5e78e1a5485792e84edd5b9c7
| 1,195 |
class DiscordSlowmodeBot < Formula
desc "Discord bot for finer control over channel slowmode functionality"
homepage "https://github.com/jfoster/discord-slowmode-bot"
url "https://github.com/jfoster/discord-slowmode-bot/archive/v0.2.0.tar.gz"
sha256 "3f940e859df9c4d049ab0797d0486abfcad4739c0419e7c71c915f34a9b2fa93"
license "MIT"
revision 5
head "https://github.com/jfoster/discord-slowmode-bot.git"
livecheck do
url :url
strategy :github_latest
end
bottle do
root_url "https://github.com/jfoster/homebrew-tap/releases/download/discord-slowmode-bot-0.2.0_5"
sha256 cellar: :any_skip_relocation, big_sur: "2add46a8ec2dfd6ca53c2a9a3b9fe2a3a854d7ffbc061272ecf7f36cd1d24f3d"
sha256 cellar: :any_skip_relocation, catalina: "873cd39902bd5a94963f7596294c38d5c7c928927bd55cf562139f26bf640b27"
end
depends_on "go" => :build
def install
ldflags = "-s -w -X main.version=#{version}"
system "go", "build", *std_go_args, "-ldflags", ldflags, "./cmd/discord-slowmode-bot"
end
test do
version_output = shell_output("#{bin}/discord-slowmode-bot --version")
assert_match "discord-slowmode-bot version #{version}", version_output
end
end
| 36.212121 | 117 | 0.759833 |
e2364830734e40a01d6a869237b096a5aa7af30a
| 2,235 |
# frozen_string_literal: true
lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'active_campaign/version'
Gem::Specification.new do |spec|
spec.name = 'active_campaign'
spec.version = ActiveCampaign::VERSION
spec.authors = ['Mikael Henriksson']
spec.email = ['[email protected]']
spec.description = 'A simple ruby wrapper for the ActiveCampaign API'
spec.summary = 'See http://www.activecampaign.com/api/overview.php for more information'
spec.homepage = 'https://github.com/mhenrixon/active_campaign'
spec.license = 'MIT'
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = 'https://rubygems.org'
spec.metadata['homepage_uri'] = spec.homepage
spec.metadata['source_code_uri'] = 'https://github.com/mhenrixon/rubocop-mhenrixon'
spec.metadata['changelog_uri'] = 'https://github.com/mhenrixon/rubocop-mhenrixon'
else
raise 'RubyGems 2.0 or newer is required to protect against ' \
'public gem pushes.'
end
spec.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_dependency 'activesupport', '>= 4.0', '< 8.0'
spec.add_dependency 'faraday', '>= 1.0', '< 3.0'
spec.add_dependency 'oj', '>= 3.0', '< 4.0'
spec.add_development_dependency 'codeclimate-test-reporter', '~> 1.0'
spec.add_development_dependency 'factory_bot'
spec.add_development_dependency 'gem-release', '~> 2.1'
spec.add_development_dependency 'pry', '~> 0.12'
spec.add_development_dependency 'rake', '~> 13.0'
spec.add_development_dependency 'reek', '~> 5.6'
spec.add_development_dependency 'rspec', '~> 3.9'
spec.add_development_dependency 'rspec-json_expectations', '~> 2.2'
spec.add_development_dependency 'rubocop-mhenrixon', '~> 0.80.0'
spec.add_development_dependency 'simplecov', '~> 0.18'
spec.add_development_dependency 'simplecov-material'
spec.add_development_dependency 'vcr', '~> 5.0'
spec.add_development_dependency 'webmock', '~> 3.8'
end
| 44.7 | 96 | 0.694855 |
08603a0a41562746a35a573466ae51e8cdfd6490
| 3,063 |
class Grant
include Her::JsonApi::Model
use_api CDB
collection_path "/api/grants"
belongs_to :director, foreign_key: :director_uid, class_name: "Person"
belongs_to :codirector, foreign_key: :codirector_uid, class_name: "Person"
belongs_to :grant_type, foreign_key: :grant_type_code
belongs_to :country, foreign_key: :country_code
belongs_to :institution, foreign_key: :institution_code
belongs_to :second_country, foreign_key: :second_country_code, class_name: "Country"
belongs_to :second_institution, foreign_key: :second_institution_code, class_name: "Institution"
has_many :projects
accepts_nested_attributes_for :projects
sends_nested_attributes_for :projects
# temporary while we are not yet sending jsonapi data back to core properly
include_root_in_json true
parse_root_in_json false
def self.new_with_defaults(attributes={})
Grant.new({
name: "",
year: Date.today.year + 1,
title: "",
description: "",
field: "",
application_id: nil,
grant_type_code: "",
country_code: "",
second_country_code: "",
institution_code: "",
show_second_institution: false,
second_institution_code: "",
institution_name: "",
second_institution_name: "",
begin_date: "",
end_date: "",
extension: "",
duration: "",
expected_value: "",
approved_at: nil,
approved_by_uid: nil,
director_uid: nil,
codirector_uid: nil,
projects: [],
scientific_tags: "",
admin_tags: ""
}.merge(attributes))
end
def approved?
approved_at.present?
end
def approve!(user=nil)
self.approved_at ||= Time.now
self.approved_by_uid ||= user.uid if user
end
## Duration and extension
#
def expected_end_date
if end_date
expected_end_date = Date.parse(end_date)
elsif begin_date && duration
expected_end_date = Date.parse(begin_date) + (duration * 12).to_i.months
expected_end_date += extension.months if extended?
end
expected_end_date
end
def countries
[country, second_country].compact
end
def institutions
[institution, second_institution].compact
end
def any_institution?
institution || second_institution
end
def country_name
country.name if country.present?
end
def second_country_name
second_country.name if second_country.present?
end
def institution_name
institution.name if institution.present?
end
def second_institution_name
second_institution.name if second_institution.present?
end
def project_word
case grant_type_code
when "asi", "csc"
"course"
when "cas"
"laboratory"
else
"project"
end
end
def build_project
project = Project.new_with_defaults({
grant_id: id,
slug: year,
description: description,
begin_date: begin_date,
end_date: end_date
})
projects << project
project
end
def grant_type_short_name
grant_type.short_name if grant_type
end
end
| 23.561538 | 98 | 0.687888 |
790e7ac9801befd8f2aeeae91ac9a6822eebfb1f
| 1,286 |
require 'simplereactor'
if ARGV[0]
SimpleReactor.use_engine( ARGV[0].to_sym )
end
require 'socket'
server = TCPServer.new("0.0.0.0", 9949)
buffer = ''
puts <<ETXT
Type some text and press after each line. The reactor is attached to
STDIN and also port 9949, where it listens for any connection and responds with
a basic HTTP response containing whatever has been typed to that point. These
two dramatically different IO streams are being handled simultaneously. Type
to exit, or wait one minute, and a timer will fire which causes the
reactor to stop and the program to exit.
ETXT
SimpleReactor::Reactor.run do |reactor|
reactor.attach(server, :read) do |monitor|
conn = monitor.io.accept
conn.gets # Pull all of the incoming data, even though it is not used in this example
conn.write "HTTP/1.1 200 OK\r\nContent-Length:#{buffer.length}\r\nContent-Type:text/plain\r\nConnection:close\r\n\r\n#{buffer}"
conn.close
end
characters_received = 0
reactor.attach(STDIN, :read) do |monitor|
stdin = monitor.io
characters_received += 1
data = stdin.getc # Pull a character at a time, just for illustration purposes
unless data
reactor.stop
else
buffer << data
end
end
reactor.add_timer(60) do
reactor.stop
end
end
| 27.956522 | 131 | 0.727838 |
4a472d3822515d3912e4a9e516ac7dac01f740c5
| 4,677 |
# frozen_string_literal: true
describe ::Portus::Background::GarbageCollector do
let(:old_tag) { (APP_CONFIG["delete"]["garbage_collector"]["older_than"].to_i + 10).days.ago }
let(:recent_tag) { (APP_CONFIG["delete"]["garbage_collector"]["older_than"].to_i - 10).days.ago }
before do
APP_CONFIG["delete"]["garbage_collector"]["enabled"] = true
end
it "returns the proper value for sleep_value" do
expect(subject.sleep_value).to eq 60
end
it "should never be disabled after being enabled" do
expect(subject.disable?).to be_falsey
end
it "returns the proper value for to_s" do
expect(subject.to_s).to eq "Garbage collector"
end
describe "#enabled?" do
it "is marked as enabled" do
expect(subject.enabled?).to be_truthy
end
it "is marked as disabled" do
APP_CONFIG["delete"]["garbage_collector"]["enabled"] = false
expect(subject.enabled?).to be_falsey
end
end
describe "#work?" do
it "returns false if the feature is disabled entirely" do
APP_CONFIG["delete"]["garbage_collector"]["enabled"] = false
expect(subject.work?).to be_falsey
end
it "returns false if there are no tags matching the given expectations" do
allow_any_instance_of(::Portus::Background::GarbageCollector).to(
receive(:tags_to_be_collected).and_return([])
)
expect(subject.work?).to be_falsey
end
it "returns true if there are tags available to be updated" do
allow_any_instance_of(::Portus::Background::GarbageCollector).to(
receive(:tags_to_be_collected).and_return(["tag"])
)
expect(subject.work?).to be_truthy
end
end
describe "#tags_to_be_collected" do
let!(:registry) { create(:registry, hostname: "registry.test.lan") }
let!(:user) { create(:admin) }
let!(:repository) { create(:repository, namespace: registry.global_namespace, name: "repo") }
it "returns an empty collection if there are no tags" do
tags = subject.send(:tags_to_be_collected)
expect(tags).to be_empty
end
it "exists a tag but it's considered recent" do
create(:tag, name: "tag", repository: repository, updated_at: recent_tag)
tags = subject.send(:tags_to_be_collected)
expect(tags).to be_empty
end
it "ignores tags which are marked" do
create(:tag, name: "tag", repository: repository, updated_at: old_tag, marked: true)
tags = subject.send(:tags_to_be_collected)
expect(tags).to be_empty
end
it "exists a tag which is older than expected" do
create(:tag, name: "tag", repository: repository, updated_at: old_tag)
tags = subject.send(:tags_to_be_collected)
expect(tags.size).to eq 1
end
it "exists a tag which is older than expected but the name does not match" do
APP_CONFIG["delete"]["garbage_collector"]["tag"] = "build-\d+"
create(:tag, name: "tag", repository: repository, updated_at: old_tag)
tags = subject.send(:tags_to_be_collected)
expect(tags.size).to eq 0
end
it "exists a tag which is older and with a proper name" do
APP_CONFIG["delete"]["garbage_collector"]["tag"] = "^build-\\d+$"
create(:tag, name: "build-1234", repository: repository, updated_at: old_tag)
tags = subject.send(:tags_to_be_collected)
expect(tags.size).to eq 1
end
end
describe "#execute!" do
let!(:registry) { create(:registry, hostname: "registry.test.lan") }
let!(:repository) { create(:repository, namespace: registry.global_namespace, name: "repo") }
before { User.create_portus_user! }
it "removes tags" do
allow_any_instance_of(Tag).to(receive(:fetch_digest).and_return("1234"))
allow_any_instance_of(::Portus::RegistryClient).to(receive(:delete).and_return(true))
create(:tag, name: "tag", digest: "1234", repository: repository, updated_at: old_tag)
expect do
subject.execute!
end.to(change { Tag.all.count }.from(1).to(0))
end
it "skips tags which could not be removed for whatever reason" do
allow_any_instance_of(Tag).to(
receive(:fetch_digest) { |tag| tag.digest == "wrong" ? "" : tag.digest }
)
allow_any_instance_of(::Portus::RegistryClient).to(receive(:delete).and_return(true))
expect(Rails.logger).to(receive(:warn).with("Could not remove <strong>tag2</strong> tag"))
create(:tag, name: "tag1", digest: "1234", repository: repository, updated_at: old_tag)
create(:tag, name: "tag2", digest: "wrong", repository: repository, updated_at: old_tag)
expect { subject.execute! }.to(change { Tag.all.count }.from(2).to(1))
end
end
end
| 35.976923 | 99 | 0.67415 |
91790db4dfd5b097d23920144728860a2ea7baa6
| 844 |
cask "feed-the-beast" do
version "202204211116,ac2e189d70"
sha256 "fc604844c399c16febd29b5f81ac6ef0d54502687f964292c8ea33b15564d804"
url "https://apps.modpacks.ch/FTBApp/release/#{version.csv.first}-#{version.csv.second}-release/FTBA_macos_#{version.csv.first}-#{version.csv.second}-release.dmg",
verified: "apps.modpacks.ch/FTBApp/"
name "Feed the Beast"
desc "Minecraft mod downloader and manager"
homepage "https://www.feed-the-beast.com/"
livecheck do
url "https://www.feed-the-beast.com/app_release.xml"
regex(/FTBA[._-]macos[._-](\d+)[._-](\h+)[._-]release\.dmg/i)
strategy :page_match do |page, regex|
page.scan(regex).map { |match| "#{match[0]},#{match[1]}" }
end
end
app "FTBApp.app"
zap trash: "~/Library/Application Support/ftblauncher"
caveats do
depends_on_java
end
end
| 31.259259 | 165 | 0.697867 |
bf5e00f209af8f65c45fb01e3a127a5033496d4f
| 5,104 |
require 'more_core_extensions/core_ext/hash'
require "topological_inventory/openshift/logging"
require "topological_inventory/openshift/connection"
require "topological_inventory/openshift/operations/core/authentication_retriever"
require "topological_inventory/openshift/operations/core/topology_api_client"
require "topological_inventory-api-client"
module TopologicalInventory
module Openshift
module Operations
module Core
class ServiceCatalogClient
include Logging
include TopologyApiClient
attr_accessor :connection_manager, :source_id, :task_id, :identity
def initialize(source_id, task_id, identity = nil)
self.identity = identity
self.source_id = source_id
self.task_id = task_id
self.connection_manager = TopologicalInventory::Openshift::Connection.new
end
def sources_api_client
@sources_api_client ||= begin
api_client = SourcesApiClient::ApiClient.new
api_client.default_headers.merge!(identity) if identity.present?
SourcesApiClient::DefaultApi.new(api_client)
end
end
def order_service(plan_name, service_offering_name, additional_parameters)
payload = build_payload(plan_name, service_offering_name, additional_parameters)
servicecatalog_connection.create_service_instance(payload)
end
def wait_for_provision_complete(name, namespace)
field_selector = "involvedObject.kind=ServiceInstance,involvedObject.name=#{name}"
watch = kubernetes_connection.watch_events(:namespace => namespace, :field_selector => field_selector)
watch.each do |notice|
event = notice.object
logger.info("#{event.involvedObject.name}: message [#{event.message}] reason [#{event.reason}]")
context = {:reason => event.reason, :message => event.message}
update_task(task_id, :state => "running", :status => "ok", :context => context)
next unless %w[ProvisionedSuccessfully ProvisionCallFailed].include?(event.reason)
service_instance = servicecatalog_connection.get_service_instance(name, namespace)
return service_instance, event.reason, event.message
end
end
def authentication
@authentication ||= fetch_authentication
end
def default_endpoint
@default_endpoint ||= fetch_default_endpoint
end
private
def build_payload(service_plan_name, service_offering_name, order_parameters)
# We need to not send empty strings in case the parameter is generated
# More details are explained in the comment in the OpenShift web catalog
# https://github.com/openshift/origin-web-catalog/blob/4c5cb3ee1ae0061ed28fc6190a0f8fff71771122/src/components/order-service/order-service.controller.ts#L442
safe_params = order_parameters["service_parameters"].delete_blanks
{
:metadata => {
:name => "#{service_offering_name}-#{SecureRandom.uuid}",
:namespace => order_parameters["provider_control_parameters"]["namespace"]
},
:spec => {
:clusterServiceClassExternalName => service_offering_name,
:clusterServicePlanExternalName => service_plan_name,
:parameters => safe_params
}
}
end
def kubernetes_connection
raw_connect("kubernetes")
end
def servicecatalog_connection
raw_connect("servicecatalog")
end
def raw_connect(service)
raise "Unable to find a default endpoint for source [#{source_id}]" if default_endpoint.nil?
raise "Unable to find an authentication for source [#{source_id}]" if authentication.nil?
Thread.current["#{service}_connection"] ||= begin
connection_manager.connect(
service, :host => default_endpoint.host, :token => authentication.password, :verify_ssl => verify_ssl_mode
)
end
end
def verify_ssl_mode
default_endpoint.verify_ssl ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
end
def fetch_default_endpoint
endpoints = sources_api_client.list_source_endpoints(source_id)&.data || []
endpoints.find(&:default)
end
def fetch_authentication
endpoint = default_endpoint
return if endpoint.nil?
endpoint_authentications = sources_api_client.list_endpoint_authentications(endpoint.id.to_s).data || []
return if endpoint_authentications.empty?
auth_id = endpoint_authentications.first.id
AuthenticationRetriever.new(auth_id, identity).process
end
end
end
end
end
end
| 39.565891 | 169 | 0.642633 |
f8a9ed5ff3e609554c554e0f5d6c8b282d6489e9
| 204 |
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class DictionaryScopeTest < ActiveSupport::TestCase
# Replace this with your real tests.
def test_truth
assert true
end
end
| 22.666667 | 68 | 0.754902 |
62c41db4dddbbce331b9fb0885ff1cf623a2db0e
| 1,607 |
class Tectonic < Formula
desc "Modernized, complete, self-contained TeX/LaTeX engine"
homepage "https://tectonic-typesetting.github.io/"
url "https://github.com/tectonic-typesetting/tectonic/archive/v0.1.11.tar.gz"
sha256 "e700dc691dfd092adfe098b716992136343ddfac5eaabb1e8cfae4e63f8454c7"
revision 2
bottle do
root_url "https://linuxbrew.bintray.com/bottles"
cellar :any
sha256 "a862b7c4cbe355b1c3c86aa6601e757e50f51f4e205b29edece526428b09ebcd" => :mojave
sha256 "8820a091d0bfcd31ad2bc5b8c8d9f0a29160a47497d00f03bc332e8c0bfe509c" => :high_sierra
sha256 "76005a41861cee9fd834d46d84f33c2f8a09f887770e29e569d64b1bb8110d49" => :sierra
sha256 "e23fde15175709fbb1b779169cb66c9edadb0c67d8c708229637b4e342e3867d" => :x86_64_linux
end
depends_on "pkg-config" => :build
depends_on "rust" => :build
depends_on "freetype"
depends_on "graphite2"
depends_on "harfbuzz"
depends_on "icu4c"
depends_on "libpng"
depends_on "openssl"
def install
ENV.cxx11
ENV["MACOSX_DEPLOYMENT_TARGET"] = MacOS.version # needed for CLT-only builds
# Ensure that the `openssl` crate picks up the intended library.
# https://crates.io/crates/openssl#manual-configuration
ENV["OPENSSL_DIR"] = Formula["openssl"].opt_prefix
system "cargo", "install", "--root", prefix, "--path", "."
pkgshare.install "tests"
end
test do
system bin/"tectonic", "-o", testpath, pkgshare/"tests/xenia/paper.tex"
assert_predicate testpath/"paper.pdf", :exist?, "Failed to create paper.pdf"
assert_match "PDF document", shell_output("file paper.pdf")
end
end
| 36.522727 | 94 | 0.750467 |
bf09a08d1e3f3fdedcef36145ac6ade574f7e93f
| 2,028 |
class Moarvm < Formula
desc "Virtual machine for NQP and Rakudo Perl 6"
homepage "https://moarvm.org"
# NOTE: Please keep these values in sync with nqp & rakudo when updating.
url "https://github.com/MoarVM/MoarVM/releases/download/2021.09/MoarVM-2021.09.tar.gz"
sha256 "9d233e62ac8e4d4580359a794f88f4d26edad54781d915f96b31464439a32cba"
license "Artistic-2.0"
revision 1
livecheck do
url "https://github.com/MoarVM/MoarVM.git"
regex(/^v?(\d+(?:\.\d+)+)$/i)
end
bottle do
sha256 arm64_big_sur: "c5f2d2d7bacda98e06029b38d5826b4efaebe5729f2d70dc282bd13c787692d3"
sha256 big_sur: "73e1c8c6913dbd4517220b0be439ad11fdb416db6bb8ec361b36b857b645f38b"
sha256 catalina: "7dd7acdb735036d925082e907816000d4765f1549c20208ab7cba7395601dcbf"
sha256 mojave: "7f1875146667613ec2095e804ea74112c6d7a764e9136b945a30521823348b66"
sha256 x86_64_linux: "cec5650e9efbeee55091f9445124c0696c36c536584e2cbb125aa9654f0c0b58" # linuxbrew-core
end
depends_on "libatomic_ops"
depends_on "libffi"
depends_on "libtommath"
depends_on "libuv"
conflicts_with "rakudo-star", because: "rakudo-star currently ships with moarvm included"
resource "nqp" do
url "https://github.com/Raku/nqp/releases/download/2021.09/nqp-2021.09.tar.gz"
sha256 "7f296eecb3417e28a08372642247124ca2413b595f30e959a0c9938a625c82d8"
end
def install
libffi = Formula["libffi"]
ENV.prepend "CPPFLAGS", "-I#{libffi.opt_lib}/libffi-#{libffi.version}/include"
configure_args = %W[
--has-libatomic_ops
--has-libffi
--has-libtommath
--has-libuv
--optimize
--prefix=#{prefix}
]
system "perl", "Configure.pl", *configure_args
system "make", "realclean"
system "make"
system "make", "install"
end
test do
testpath.install resource("nqp")
out = Dir.chdir("src/vm/moar/stage0") do
shell_output("#{bin}/moar nqp.moarvm -e 'for (0,1,2,3,4,5,6,7,8,9) { print($_) }'")
end
assert_equal "0123456789", out
end
end
| 33.8 | 109 | 0.719921 |
18fe1f646e8fadaef62897dcd2e62e692294e52f
| 178 |
#!/usr/bin/env ruby
$LOAD_PATH.unshift ::File.expand_path(::File.dirname(__FILE__) + "/lib")
require "github-trello/server"
use Rack::ShowExceptions
run GithubTrello::Server.new
| 29.666667 | 72 | 0.764045 |
ff3aa66b6fc96462879ba7870fb267f6c4a1d5bd
| 180 |
class Jobler::PageRender
def initialize(args)
@job = args.fetch(:job)
@name = args.fetch(:name)
end
def body
@job.results.find_by!(name: @name).result
end
end
| 16.363636 | 45 | 0.65 |
38ab89935d1439bc0f9781a5973e83725b79c3aa
| 1,303 |
# frozen_string_literal: true
require_relative "lib/simplepush/version"
Gem::Specification.new do |spec|
spec.name = "simplepush"
spec.version = Simplepush::VERSION
spec.authors = ["Christopher Oezbek"]
spec.email = ["[email protected]"]
spec.summary = "Ruby SimplePush.io API client (unofficial)"
spec.description = "Httparty wrapper for SimplePush.io"
spec.homepage = "https://github.com/coezbek/simplepush"
spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")
spec.metadata["allowed_push_host"] = "https://rubygems.org"
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = spec.homepage
spec.metadata["changelog_uri"] = "https://github.com/coezbek/simplepush/README.md#Changelog"
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path(__dir__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
# Runtime dependencies
spec.add_dependency "httparty"
end
| 37.228571 | 94 | 0.686109 |
ed70f529b594a697eee579d06028d22443f52539
| 304 |
require 'spec_helper'
describe "Api/Rake/Ops", :capybara => true do
describe "GET /api/rake/ops/set_do.json" do
#it "works!" do
# cred = basic_auth("test_one")
# get '/api/rake/ops/set_do.json', nil, {'HTTP_AUTHORIZATION' => cred}
# response.status.should be(200)
#end
end
end
| 27.636364 | 75 | 0.644737 |
edfe8aa933205924608c79a97e71ab304b079ddd
| 2,618 |
require 'forwardable'
require 'rubygems'
gem 'oauth', '~> 0.3.6'
require 'oauth'
gem 'hashie', '~> 0.1.3'
require 'hashie'
gem 'httparty', '~> 0.4.3'
require 'httparty'
module Twitter
class TwitterError < StandardError
attr_reader :data
def initialize(data)
@data = data
super
end
end
class RateLimitExceeded < TwitterError; end
class Unauthorized < TwitterError; end
class General < TwitterError; end
class Unavailable < StandardError; end
class InformTwitter < StandardError; end
class NotFound < StandardError; end
def self.firehose
response = HTTParty.get('http://twitter.com/statuses/public_timeline.json', :format => :json)
response.map { |tweet| Hashie::Mash.new(tweet) }
end
def self.user(id)
response = HTTParty.get("http://twitter.com/users/show/#{id}.json", :format => :json)
Hashie::Mash.new(response)
end
def self.status(id)
response = HTTParty.get("http://twitter.com/statuses/show/#{id}.json", :format => :json)
Hashie::Mash.new(response)
end
def self.friend_ids(id)
HTTParty.get("http://twitter.com/friends/ids/#{id}.json", :format => :json)
end
def self.follower_ids(id)
HTTParty.get("http://twitter.com/followers/ids/#{id}.json", :format => :json)
end
def self.timeline(id, options={})
response = HTTParty.get("http://twitter.com/statuses/user_timeline/#{id}.json", :query => options, :format => :json)
response.map{|tweet| Hashie::Mash.new tweet}
end
# :per_page = max number of statues to get at once
# :page = which page of tweets you wish to get
def self.list_timeline(list_owner_username, slug, query = {})
response = HTTParty.get("http://api.twitter.com/1/#{list_owner_username}/lists/#{slug}/statuses.json", :query => query, :format => :json)
response.map{|tweet| Hashie::Mash.new tweet}
end
end
module Hashie
class Mash
# Converts all of the keys to strings, optionally formatting key name
def rubyify_keys!
keys.each{|k|
v = delete(k)
new_key = k.to_s.underscore
self[new_key] = v
v.rubyify_keys! if v.is_a?(Hash)
v.each{|p| p.rubyify_keys! if p.is_a?(Hash)} if v.is_a?(Array)
}
self
end
end
end
directory = File.expand_path(File.dirname(__FILE__))
require File.join(directory, 'twitter', 'oauth')
require File.join(directory, 'twitter', 'httpauth')
require File.join(directory, 'twitter', 'request')
require File.join(directory, 'twitter', 'base')
require File.join(directory, 'twitter', 'search')
require File.join(directory, 'twitter', 'trends')
| 27.851064 | 141 | 0.667303 |
03b8b86e960116de28155aaf248d4a31de35b72d
| 475 |
require 'dotenv'
require 'stripe'
require 'stripe_migrant'
Dotenv.load
target_key = ENV['STRIPE_NEW_SK']
source_key = ENV['STRIPE_OLD_SK']
migrator = StripeMigrant::Migrator.new(source_key: source_key, target_key: target_key)
# migrate customers
puts 'Migrating Customers'
customers = migrator.get_customers(api_key: source_key)
puts "customers retrieved: #{customers.count}"
migrator.update_customers(
api_key: target_key,
customers: customers,
read_only: true
)
| 21.590909 | 86 | 0.787368 |
39ed003ad27cbbed540c91a85602890b3aa83015
| 990 |
require 'spree_core'
require 'spree/sample'
module SpreeSample
class Engine < Rails::Engine
engine_name 'spree_sample'
# Needs to be here so we can access it inside the tests
def self.load_samples
Spree::Sample.load_sample("payment_methods")
Spree::Sample.load_sample("tax_categories")
Spree::Sample.load_sample("tax_rates")
Spree::Sample.load_sample("shipping_categories")
Spree::Sample.load_sample("shipping_methods")
Spree::Sample.load_sample("products")
Spree::Sample.load_sample("taxons")
Spree::Sample.load_sample("option_values")
Spree::Sample.load_sample("product_option_types")
Spree::Sample.load_sample("product_properties")
Spree::Sample.load_sample("prototypes")
Spree::Sample.load_sample("variants")
Spree::Sample.load_sample("stock")
Spree::Sample.load_sample("assets")
Spree::Sample.load_sample("orders")
Spree::Sample.load_sample("payments")
end
end
end
| 31.935484 | 59 | 0.707071 |
87c5f75711575e750ea7ab968dd964dd3df377c2
| 1,465 |
Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Configure static asset server for tests with Cache-Control for performance
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
# config.action_mailer.delivery_method = :test
# Raise exception on mass assignment protection for Active Record models
# config.active_record.mass_assignment_sanitizer = :strict
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
config.eager_load = false
end
| 39.594595 | 84 | 0.782935 |
79053020948a2040589ba24f99a41d331eb63883
| 159 |
require 'instagram'
Instagram.configure do |config|
config.client_id = ENV['INSTAGRAM_CLIENT_ID']
config.access_token = ENV['INSTAGRAM_ACCESS_TOKEN']
end
| 22.714286 | 53 | 0.786164 |
1c0ef3552c0f00c12cd362181d329f484d4f01d6
| 448 |
require 'facets/binding/local_variables'
require 'test/unit'
class TC_Binding_Local_Variables < Test::Unit::TestCase
def setup
a = 1
b = 2
x = "hello"
@bind = binding
end
unless RUBY_VERSION > "1.9"
def test_local_variables
assert_equal( ["a","b","x"], @bind.local_variables )
end
else
def test_local_variables
assert_equal( [:a,:b,:x], @bind.local_variables )
end
end
end
| 17.92 | 60 | 0.622768 |
01f24a318ae90c5e003f0af6b758cc93f32ed276
| 270 |
# frozen_string_literal: true
class CreateIdeas < ActiveRecord::Migration[5.2]
def change
create_table :ideas do |t|
t.text :body
t.references :topic, foreign_key: true
t.references :user, foreign_key: true
t.timestamps
end
end
end
| 19.285714 | 48 | 0.677778 |
799ade2dabb1d069b781b69202d652aed79c4b76
| 52,872 |
class User < ActiveRecord::Base
include ActsAsSpammable::User
include ActsAsElasticModel
# include ActsAsUUIDable
before_validation :set_uuid
def set_uuid
self.uuid ||= SecureRandom.uuid
self.uuid = uuid.downcase
true
end
acts_as_voter
acts_as_spammable fields: [ :description ],
comment_type: "signup"
# If the user has this role, has_role? will always return true
JEDI_MASTER_ROLE = 'admin'
devise :database_authenticatable, :registerable, :suspendable,
:recoverable, :rememberable, :confirmable, :validatable,
:encryptable, :lockable, :encryptor => :restful_authentication_sha1
handle_asynchronously :send_devise_notification
# set user.skip_email_validation = true if you want to, um, skip email validation before creating+saving
attr_accessor :skip_email_validation
attr_accessor :skip_registration_email
# licensing extras
attr_accessor :make_observation_licenses_same
attr_accessor :make_photo_licenses_same
attr_accessor :make_sound_licenses_same
attr_accessor :html
attr_accessor :pi_consent
# Email notification preferences
preference :comment_email_notification, :boolean, default: true
preference :identification_email_notification, :boolean, default: true
preference :message_email_notification, :boolean, default: true
preference :no_email, :boolean, default: false
preference :project_invitation_email_notification, :boolean, default: true
preference :mention_email_notification, :boolean, default: true
preference :project_journal_post_email_notification, :boolean, default: true
preference :project_curator_change_email_notification, :boolean, default: true
preference :project_added_your_observation_email_notification, :boolean, default: true
preference :taxon_change_email_notification, :boolean, default: true
preference :user_observation_email_notification, :boolean, default: true
preference :taxon_or_place_observation_email_notification, :boolean, default: true
preference :lists_by_login_sort, :string, :default => "id"
preference :lists_by_login_order, :string, :default => "asc"
preference :per_page, :integer, :default => 30
preference :gbif_sharing, :boolean, :default => true
preference :observation_license, :string
preference :photo_license, :string
preference :sound_license, :string
preference :automatic_taxonomic_changes, :boolean, :default => true
preference :receive_mentions, :boolean, :default => true
preference :observations_view, :string
preference :observations_search_subview, :string
preference :observations_search_map_type, :string, default: "terrain"
preference :community_taxa, :boolean, :default => true
PREFERRED_OBSERVATION_FIELDS_BY_ANYONE = "anyone"
PREFERRED_OBSERVATION_FIELDS_BY_CURATORS = "curators"
PREFERRED_OBSERVATION_FIELDS_BY_OBSERVER = "observer"
preference :observation_fields_by, :string, :default => PREFERRED_OBSERVATION_FIELDS_BY_ANYONE
PROJECT_ADDITION_BY_ANY = "any"
PROJECT_ADDITION_BY_JOINED = "joined"
PROJECT_ADDITION_BY_NONE = "none"
preference :project_addition_by, :string, default: PROJECT_ADDITION_BY_ANY
preference :location_details, :boolean, default: false
preference :redundant_identification_notifications, :boolean, default: true
preference :skip_coarer_id_modal, default: false
preference :hide_observe_onboarding, default: false
preference :hide_follow_onboarding, default: false
preference :hide_activity_onboarding, default: false
preference :hide_getting_started_onboarding, default: false
preference :hide_updates_by_you_onboarding, default: false
preference :hide_comments_onboarding, default: false
preference :hide_following_onboarding, default: false
preference :taxon_page_place_id, :integer
preference :hide_obs_show_annotations, default: false
preference :hide_obs_show_projects, default: false
preference :hide_obs_show_tags, default: false
preference :hide_obs_show_observation_fields, default: false
preference :hide_obs_show_identifiers, default: false
preference :hide_obs_show_copyright, default: false
preference :hide_obs_show_quality_metrics, default: false
preference :hide_obs_show_expanded_cid, default: true
preference :common_names, :boolean, default: true
preference :scientific_name_first, :boolean, default: false
preference :no_place, :boolean, default: false
preference :medialess_obs_maps, :boolean, default: false
preference :captive_obs_maps, :boolean, default: false
preference :forum_topics_on_dashboard, :boolean, default: true
preference :monthly_supporter_badge, :boolean, default: false
preference :map_tile_test, :boolean, default: false
preference :no_site, :boolean, default: false
preference :no_tracking, :boolean, default: false
preference :identify_image_size, :string, default: nil
preference :identify_side_bar, :boolean, default: false
preference :lifelist_nav_view, :string
preference :lifelist_details_view, :string
preference :edit_observations_sort, :string, default: "desc"
preference :edit_observations_order, :string, default: "created_at"
preference :lifelist_tree_mode, :string
preference :taxon_photos_query, :string
NOTIFICATION_PREFERENCES = %w(
comment_email_notification
identification_email_notification
mention_email_notification
message_email_notification
project_journal_post_email_notification
project_added_your_observation_email_notification
project_curator_change_email_notification
taxon_change_email_notification
user_observation_email_notification
taxon_or_place_observation_email_notification
)
has_many :provider_authorizations, :dependent => :delete_all
has_one :flickr_identity, :dependent => :delete
# has_one :picasa_identity, :dependent => :delete
has_one :soundcloud_identity, :dependent => :delete
has_many :observations, :dependent => :destroy
has_many :deleted_observations
has_many :deleted_photos
has_many :deleted_sounds
has_many :flags_as_flagger, inverse_of: :user, class_name: "Flag"
has_many :flags_as_flaggable_user, inverse_of: :flaggable_user,
class_name: "Flag", foreign_key: "flaggable_user_id", dependent: :nullify
has_many :friendships, dependent: :destroy
has_many :friendships_as_friend, class_name: "Friendship",
foreign_key: "friend_id", inverse_of: :friend, dependent: :destroy
def followees
User.where( "friendships.user_id = ?", id ).
joins( "JOIN friendships ON friendships.friend_id = users.id" ).
where( "friendships.following" ).
where( "users.suspended_at IS NULL" )
end
def followers
User.where( "friendships.friend_id = ?", id ).
joins( "JOIN friendships ON friendships.user_id = users.id" ).
where( "friendships.following" ).
where( "users.suspended_at IS NULL" )
end
has_many :lists, :dependent => :destroy
has_many :identifications, :dependent => :destroy
has_many :identifications_for_others,
-> { where("identifications.user_id != observations.user_id AND identifications.current = true").
joins(:observation) }, :class_name => "Identification"
has_many :photos, :dependent => :destroy
has_many :sounds, dependent: :destroy
has_many :posts #, :dependent => :destroy
has_many :journal_posts, :class_name => "Post", :as => :parent, :dependent => :destroy
has_many :trips, -> { where("posts.type = 'Trip'") }, :class_name => "Post", :foreign_key => "user_id"
has_many :taxon_links, :dependent => :nullify
has_many :comments, :dependent => :destroy
has_many :projects
has_many :project_users, :dependent => :destroy
has_many :project_user_invitations, :dependent => :nullify
has_many :project_user_invitations_received, :dependent => :delete_all, :class_name => "ProjectUserInvitation"
has_many :listed_taxa, :dependent => :nullify
has_many :invites, :dependent => :nullify
has_many :quality_metrics, :dependent => :destroy
has_many :sources, :dependent => :nullify
has_many :places, :dependent => :nullify
has_many :messages, :dependent => :destroy
has_many :delivered_messages, -> { where("messages.from_user_id != messages.user_id") }, :class_name => "Message", :foreign_key => "from_user_id"
has_many :guides, :dependent => :destroy, :inverse_of => :user
has_many :observation_fields, :dependent => :nullify, :inverse_of => :user
has_many :observation_field_values, :dependent => :nullify, :inverse_of => :user
has_many :updated_observation_field_values, :dependent => :nullify, :inverse_of => :updater, :foreign_key => "updater_id", :class_name => "ObservationFieldValue"
has_many :guide_users, :inverse_of => :user, :dependent => :delete_all
has_many :editing_guides, :through => :guide_users, :source => :guide
has_many :created_guide_sections, :class_name => "GuideSection", :foreign_key => "creator_id", :inverse_of => :creator, :dependent => :nullify
has_many :updated_guide_sections, :class_name => "GuideSection", :foreign_key => "updater_id", :inverse_of => :updater, :dependent => :nullify
has_many :atlases, :inverse_of => :user, :dependent => :nullify
has_many :user_blocks, inverse_of: :user, dependent: :destroy
has_many :user_blocks_as_blocked_user, class_name: "UserBlock", foreign_key: "blocked_user_id", inverse_of: :blocked_user, dependent: :destroy
has_many :user_mutes, inverse_of: :user, dependent: :destroy
has_many :user_mutes_as_muted_user, class_name: "UserMute", foreign_key: "muted_user_id", inverse_of: :muted_user, dependent: :destroy
has_many :taxa, foreign_key: "creator_id", inverse_of: :creator
has_many :taxon_curators, inverse_of: :user, dependent: :destroy
has_many :taxon_changes, inverse_of: :user
has_many :taxon_framework_relationships
has_many :taxon_names, foreign_key: "creator_id", inverse_of: :creator
has_many :annotations, dependent: :destroy
has_many :saved_locations, inverse_of: :user, dependent: :destroy
has_many :user_privileges, inverse_of: :user, dependent: :delete_all
has_one :user_parent, dependent: :destroy, inverse_of: :user
has_many :parentages, class_name: "UserParent", foreign_key: "parent_user_id", inverse_of: :parent_user
has_many :moderator_actions, inverse_of: :user
has_many :moderator_notes, inverse_of: :user
has_many :moderator_notes_as_subject, class_name: "ModeratorNote",
foreign_key: "subject_user_id", inverse_of: :subject_user,
dependent: :destroy
file_options = {
processors: [:deanimator],
styles: {
original: "2048x2048>",
large: "500x500>",
medium: "300x300>",
thumb: "48x48#",
mini: "16x16#"
}
}
if CONFIG.usingS3
has_attached_file :icon, file_options.merge(
storage: :s3,
s3_credentials: "#{Rails.root}/config/s3.yml",
s3_protocol: CONFIG.s3_protocol || "https",
s3_host_alias: CONFIG.s3_host || CONFIG.s3_bucket,
s3_region: CONFIG.s3_region,
bucket: CONFIG.s3_bucket,
path: "/attachments/users/icons/:id/:style.:icon_type_extension",
default_url: ":root_url/attachment_defaults/users/icons/defaults/:style.png",
url: ":s3_alias_url"
)
invalidate_cloudfront_caches :icon, "attachments/users/icons/:id/*"
else
has_attached_file :icon, file_options.merge(
path: ":rails_root/public/attachments/:class/:attachment/:id-:style.:icon_type_extension",
url: "/attachments/:class/:attachment/:id-:style.:icon_type_extension",
default_url: "/attachment_defaults/:class/:attachment/defaults/:style.png"
)
end
# Roles
has_and_belongs_to_many :roles, -> { uniq }
belongs_to :curator_sponsor, class_name: "User"
belongs_to :suspended_by_user, class_name: "User"
has_subscribers
has_many :subscriptions, :dependent => :delete_all
has_many :flow_tasks
has_many :project_observations, dependent: :nullify
belongs_to :site, :inverse_of => :users
has_many :site_admins, inverse_of: :user
belongs_to :place, :inverse_of => :users
belongs_to :search_place, inverse_of: :search_users, class_name: "Place"
before_validation :download_remote_icon, :if => :icon_url_provided?
before_validation :strip_name, :strip_login
before_validation :set_time_zone
before_save :allow_some_licenses
before_save :get_lat_lon_from_ip_if_last_ip_changed
before_save :check_suspended_by_user
before_save :remove_email_from_name
before_save :set_pi_consent_at
before_save :set_locale
after_save :update_observation_licenses
after_save :update_photo_licenses
after_save :update_sound_licenses
after_save :update_observation_sites_later
after_save :destroy_messages_by_suspended_user
after_save :revoke_access_tokens_by_suspended_user
after_save :restore_access_tokens_by_suspended_user
after_update :set_observations_taxa_if_pref_changed
after_update :update_photo_properties
after_create :set_uri
after_destroy :create_deleted_user
after_destroy :remove_oauth_access_tokens
after_destroy :destroy_project_rules
after_destroy :reindex_faved_observations_after_destroy_later
validates_presence_of :icon_url, :if => :icon_url_provided?, :message => 'is invalid or inaccessible'
validates_attachment_content_type :icon, :content_type => [/jpe?g/i, /png/i, /gif/i],
:message => "must be JPG, PNG, or GIF"
validates_presence_of :login
MIN_LOGIN_SIZE = 3
MAX_LOGIN_SIZE = 40
DEFAULT_LOGIN = "naturalist"
# Regexes from restful_authentication
LOGIN_PATTERN = "[A-Za-z][\\\w\\\-_]+"
login_regex = /\A#{ LOGIN_PATTERN }\z/ # ASCII, strict
validates_length_of :login, within: MIN_LOGIN_SIZE..MAX_LOGIN_SIZE
validates_uniqueness_of :login
validates_format_of :login, with: login_regex, message: :must_begin_with_a_letter
validates_exclusion_of :login, in: %w(password new edit create update delete destroy)
validates_exclusion_of :password, in: %w(password)
validates_length_of :name, maximum: 100, allow_blank: true
validates_format_of :email, with: Devise.email_regexp,
message: :must_look_like_an_email_address, allow_blank: true
validates_length_of :email, within: 6..100, allow_blank: true
validates_length_of :time_zone, minimum: 3, allow_nil: true
validate :validate_email_pattern, on: :create
validate :validate_email_domain_exists, on: :create
scope :order_by, Proc.new { |sort_by, sort_dir|
sort_dir ||= 'DESC'
order("? ?", sort_by, sort_dir)
}
scope :curators, -> { joins(:roles).where("roles.name IN ('curator', 'admin')") }
scope :admins, -> { joins(:roles).where("roles.name = 'admin'") }
scope :active, -> { where("suspended_at IS NULL") }
def validate_email_pattern
return if CONFIG.banned_emails.blank?
return if self.email.blank?
failed = false
CONFIG.banned_emails.each do |banned_suffix|
next if failed
if self.email.match(/#{banned_suffix}$/)
errors.add( :email, :domain_is_not_supported )
failed = true
end
end
end
# As noted at
# https://stackoverflow.com/questions/39721917/check-if-email-domain-is-valid,
# this approach is probably going to have some false positives... but probably
# not many
def validate_email_domain_exists
return true if Rails.env.test? && CONFIG.user_email_domain_exists_validation != :enabled
return true if self.email.blank?
domain = email.split( "@" )[1].strip
dns_response = begin
r = nil
Timeout::timeout( 5 ) do
Resolv::DNS.open do |dns|
r = dns.getresources( domain, Resolv::DNS::Resource::IN::MX )
end
end
r
rescue Timeout::Error
begin
r = nil
Timeout::timeout( 5 ) do
Resolv::DNS.open do |dns|
r = dns.getresources( domain, Resolv::DNS::Resource::IN::A )
end
end
r
rescue Timeout::Error
r = nil
end
end
if dns_response.blank?
errors.add( :email, :domain_is_not_supported )
end
true
end
# only validate_presence_of email if user hasn't auth'd via a 3rd-party provider
# you can also force skipping email validation by setting u.skip_email_validation=true before you save
# (this option is necessary because the User is created before the associated ProviderAuthorization)
# This is not a normal validation b/c email validation happens in Devise, which looks for this method
def email_required?
!(skip_email_validation || provider_authorizations.count > 0)
end
def icon_url_provided?
!self.icon.present? && !self.icon_url.blank?
end
def user_icon_url
return nil if icon.blank?
"#{FakeView.asset_url(icon.url(:thumb))}".gsub(/([^\:])\/\//, '\\1/')
end
def medium_user_icon_url
return nil if icon.blank?
"#{FakeView.asset_url(icon.url(:medium))}".gsub(/([^\:])\/\//, '\\1/')
end
def original_user_icon_url
return nil if icon.blank?
"#{FakeView.asset_url(icon.url)}".gsub(/([^\:])\/\//, '\\1/')
end
def active?
!suspended?
end
# This is a dangerous override in that it doesn't call super, thereby
# ignoring the results of all the devise modules like confirmable. We do
# this b/c we want all users to be able to sign in, even if unconfirmed, but
# not if suspended.
def active_for_authentication?
active? && ( birthday.blank? || birthday < 13.years.ago || !UserParent.where( "user_id = ? AND donorbox_donor_id IS NULL", id ).exists? )
end
def download_remote_icon
io = open(URI.parse(self.icon_url))
Timeout::timeout(10) do
self.icon = (io.base_uri.path.split('/').last.blank? ? nil : io)
end
true
rescue => e # catch url errors with validations instead of exceptions (Errno::ENOENT, OpenURI::HTTPError, etc...)
Rails.logger.error "[ERROR #{Time.now}] Failed to download_remote_icon for #{id}: #{e}"
true
end
def strip_name
return true if name.blank?
self.name = FakeView.strip_tags( name ).to_s
self.name = name.gsub(/[\s\n\t]+/, ' ').strip
true
end
def strip_login
return true if login.blank?
self.login = login.strip
true
end
def allow_some_licenses
self.preferred_observation_license = Shared::LicenseModule.normalize_license_code( preferred_observation_license )
self.preferred_photo_license = Shared::LicenseModule.normalize_license_code( preferred_photo_license )
self.preferred_sound_license = Shared::LicenseModule.normalize_license_code( preferred_sound_license )
unless preferred_observation_license.blank? || Observation::LICENSE_CODES.include?( preferred_observation_license )
self.preferred_observation_license = nil
end
unless preferred_photo_license.blank? || Observation::LICENSE_CODES.include?( preferred_photo_license )
self.preferred_photo_license = nil
end
unless preferred_sound_license.blank? || Observation::LICENSE_CODES.include?( preferred_sound_license )
self.preferred_sound_license = nil
end
true
end
# add a provider_authorization to this user.
# auth_info is the omniauth info from rack.
def add_provider_auth(auth_info)
pa = self.provider_authorizations.build
pa.assign_auth_info(auth_info)
pa.auth_info = auth_info
pa.save
pa
end
# test to see if this user has authorized with the given provider
# argument is one of: 'facebook', 'twitter', 'google', 'yahoo'
# returns either nil or the appropriate ProviderAuthorization
def has_provider_auth(provider)
provider = provider.downcase
provider_authorizations.detect do |p|
p.provider_name.match(provider) || p.provider_uid.match(provider)
end
end
def login=(value)
write_attribute :login, (value ? value.to_s.downcase : nil)
end
def email=(value)
write_attribute :email, (value ? value.to_s.downcase : nil)
end
# Role related methods
# Checks if a user has a role; returns true if they don't but
# are admin. Admins are supreme beings
def has_role?(role)
role_list ||= roles.map(&:name)
role_list.include?(role.to_s) || role_list.include?(User::JEDI_MASTER_ROLE)
end
# Everything below here was added for iNaturalist
# TODO: named_scope
def recent_observations(num = 5)
observations.order("created_at DESC").limit(num)
end
# TODO: named_scope
def friends_observations(limit = 5)
obs = []
friends.each do |friend|
obs << friend.observations.order("created_at DESC").limit(limit)
end
obs.flatten
end
# TODO: named_scope / roles plugin
def is_curator?
has_role?(:curator)
end
def is_admin?
has_role?(:admin)
end
alias :admin? :is_admin?
def is_site_admin_of?( site )
return true if is_admin?
return false unless site && site.is_a?( Site )
!!site_admins.detect{ |sa| sa.site_id == site.id }
end
def to_s
"<User #{self.id}: #{self.login}>"
end
def friends_with?(user)
friends.exists?(user)
end
def picasa_client
return nil unless (pa = has_provider_auth('google'))
@picasa_client ||= Picasa.new(pa.token)
end
# returns a koala object to make (authenticated) facebook api calls
# e.g. @facebook_api.get_object('me')
# see koala docs for available methods: https://github.com/arsduo/koala
def facebook_api
return nil unless facebook_identity
@facebook_api ||= Koala::Facebook::API.new(facebook_identity.token)
end
# returns nil or the facebook ProviderAuthorization
def facebook_identity
@facebook_identity ||= has_provider_auth('facebook')
end
def facebook_token
facebook_identity.try(:token)
end
def picasa_identity
@picasa_identity ||= has_provider_auth('google_oauth2')
end
# returns nil or the twitter ProviderAuthorization
def twitter_identity
@twitter_identity ||= has_provider_auth('twitter')
end
def api_token
JsonWebToken.encode( user_id: id )
end
def orcid
provider_authorizations.
detect{ |pa| pa.provider_name == "orcid" }.try( :provider_uid )
end
def update_observation_licenses
return true unless [true, "1", "true"].include?(@make_observation_licenses_same)
Observation.where( user_id: id ).
update_all( license: preferred_observation_license, updated_at: Time.now )
index_observations_later
true
end
def update_photo_licenses
return true unless [true, "1", "true"].include?(@make_photo_licenses_same)
number = Photo.license_number_for_code(preferred_photo_license)
return true unless number
Photo.where( "user_id = ? AND type != 'GoogleStreetViewPhoto'", id ).
update_all( license: number, updated_at: Time.now )
index_observations_later
true
end
def update_sound_licenses
return true unless [true, "1", "true"].include?(@make_sound_licenses_same)
number = Photo.license_number_for_code(preferred_sound_license)
return true unless number
Sound.where( user_id: id ).update_all( license: number, updated_at: Time.now )
index_observations_later
true
end
def update_observation_sites_later
delay(
priority: USER_INTEGRITY_PRIORITY,
unique_hash: { "User::update_observation_sites": id },
queue: "throttled"
).update_observation_sites if site_id_changed?
end
def update_observation_sites
observations.update_all( site_id: site_id, updated_at: Time.now )
# update ES-indexed observations in place with update_by_query as the site_id
# will not affect any other attributes that necessitate a full reindex
try_and_try_again( Elasticsearch::Transport::Transport::Errors::Conflict, sleep: 1, tries: 10 ) do
Observation.__elasticsearch__.client.update_by_query(
index: Observation.index_name,
refresh: Rails.env.test?,
body: {
query: {
term: {
"user.id": id
}
},
script: {
source: "
if ( ctx._source.site_id != params.site_id ) {
ctx._source.site_id = params.site_id;
} else { ctx.op = 'noop' }",
params: {
site_id: site_id
}
}
}
)
end
end
def index_observations_later
delay(
priority: USER_INTEGRITY_PRIORITY,
unique_hash: { "User::index_observations_later": id },
queue: "throttled"
).index_observations
end
def index_observations
Observation.elastic_index!(ids: Observation.by(self).pluck(:id), wait_for_index_refresh: true)
end
def merge(reject)
raise "Can't merge a user with itself" if reject.id == id
reject.friendships.where(friend_id: id).each{ |f| f.destroy }
merge_has_many_associations(reject)
reject.delay( priority: USER_PRIORITY, unique_hash: { "User::sane_destroy": reject.id } ).sane_destroy
User.delay( priority: USER_INTEGRITY_PRIORITY ).merge_cleanup( id )
end
def self.merge_cleanup( user_id )
return unless user = User.find_by_id( user_id )
start = Time.now
Observation.elastic_index!(
scope: Observation.by( user_id ),
wait_for_index_refresh: true
)
Observation.elastic_index!(
scope: Observation.joins( :identifications ).
where( "identifications.user_id = ?", user_id ).
where( "observations.last_indexed_at < ?", start ),
wait_for_index_refresh: true
)
Identification.elastic_index!(
scope: Identification.where( user_id: user_id ),
wait_for_index_refresh: true
)
User.update_identifications_counter_cache( user.id )
User.update_observations_counter_cache( user.id )
User.update_species_counter_cache( user.id )
user.reload
user.elastic_index!
Project.elastic_index!(
ids: ProjectUser.where( user_id: user.id ).pluck(:project_id),
wait_for_index_refresh: true
)
end
def set_locale
self.locale = I18n.locale if locale.blank?
true
end
def set_time_zone
self.time_zone = nil if time_zone.blank?
true
end
def set_uri
if uri.blank?
User.where(id: id).update_all(uri: FakeView.user_url(id))
end
true
end
def get_lat_lon_from_ip
return true if last_ip.nil?
latitude = nil
longitude = nil
lat_lon_acc_admin_level = nil
geoip_response = INatAPIService.geoip_lookup({ ip: last_ip })
if geoip_response && geoip_response.results
# don't set any location if the country is unknown
if geoip_response.results.country
ll = geoip_response.results.ll
latitude = ll[0]
longitude = ll[1]
if geoip_response.results.city
# also probably know the county
lat_lon_acc_admin_level = 2
elsif geoip_response.results.region
# also probably know the state
lat_lon_acc_admin_level = 1
else
# probably just know the country
lat_lon_acc_admin_level = 0
end
end
end
self.latitude = latitude
self.longitude = longitude
self.lat_lon_acc_admin_level = lat_lon_acc_admin_level
end
def get_lat_lon_from_ip_if_last_ip_changed
return true if last_ip.nil?
if last_ip_changed? || latitude.nil?
get_lat_lon_from_ip
end
end
def check_suspended_by_user
return if suspended?
self.suspended_by_user_id = nil
end
def published_name
name.blank? ? login : name
end
def self.query(params={})
scope = self.all
if params[:sort_by] && params[:sort_dir]
scope.order(params[:sort_by], params[:sort_dir])
elsif params[:sort_by]
params.order(query[:sort_by])
end
scope
end
def self.find_for_authentication(conditions = {})
s = conditions[:email].to_s.downcase
where("lower(login) = ?", s).first || where("lower(email) = ?", s).first
end
# http://stackoverflow.com/questions/6724494
def self.authenticate(login, password)
user = User.find_for_authentication(:email => login)
return nil if user.blank?
user.valid_password?(password) && user.active? ? user : nil
end
# create a user using 3rd party provider credentials (via omniauth)
# note that this bypasses validation and immediately activates the new user
# see https://github.com/intridea/omniauth/wiki/Auth-Hash-Schema for details of auth_info data
def self.create_from_omniauth(auth_info)
email = auth_info["info"].try(:[], "email")
email ||= auth_info["extra"].try(:[], "user_hash").try(:[], "email")
# see if there's an existing inat user with this email. if so, just link the accounts and return the existing user.
if !email.blank? && u = User.find_by_email(email)
u.add_provider_auth(auth_info)
return u
end
auth_info_name = auth_info["info"]["nickname"]
auth_info_name = auth_info["info"]["first_name"] if auth_info_name.blank?
auth_info_name = auth_info["info"]["name"] if auth_info_name.blank?
auth_info_name = User.remove_email_from_string( auth_info_name )
autogen_login = User.suggest_login(auth_info_name)
autogen_login = User.suggest_login( DEFAULT_LOGIN ) if autogen_login.blank?
autogen_pw = SecureRandom.hex(6) # autogenerate a random password (or else validation fails)
icon_url = auth_info["info"]["image"]
# Don't bother if the icon URL looks like the default Google user icon
icon_url = nil if icon_url =~ /4252rscbv5M/
u = User.new(
:login => autogen_login,
:email => email,
:name => auth_info["info"]["name"],
:password => autogen_pw,
:password_confirmation => autogen_pw,
:icon_url => icon_url
)
u.skip_email_validation = true
u.skip_confirmation!
user_saved = begin
u.save
rescue PG::Error, ActiveRecord::RecordNotUnique => e
raise e unless e.message =~ /duplicate key value violates unique constraint/
false
end
unless user_saved
suggestion = User.suggest_login(u.login)
Rails.logger.info "[INFO #{Time.now}] unique violation on #{u.login}, suggested login: #{suggestion}"
u.update_attributes(:login => suggestion)
end
u.add_provider_auth(auth_info)
u
end
# given a requested login, will try to find existing users with that login
# and suggest handle2, handle3, handle4, etc if the login's taken
# to prevent namespace clashes (e.g. i register with twitter @joe but
# there's already an inat user where login=joe, so it suggest joe2)
def self.suggest_login(requested_login)
requested_login = requested_login.to_s
requested_login = DEFAULT_LOGIN if requested_login.blank?
requested_login = I18n.transliterate( requested_login ).sub( /^\d*/, "" ).gsub( /\?+/, "" )
requested_login = if requested_login.blank?
DEFAULT_LOGIN
else
requested_login.gsub( /\W/, "_" ).downcase
end
suggested_login = requested_login
if suggested_login.size > MAX_LOGIN_SIZE
suggested_login = suggested_login[0..MAX_LOGIN_SIZE/2]
end
if suggested_login =~ /^#{DEFAULT_LOGIN}\d+?/
while suggested_login.to_s.size < MIN_LOGIN_SIZE || User.find_by_login( suggested_login )
suggested_login = "#{requested_login}#{rand( User.maximum(:id) * 2 )}"
end
else
# if the name is semi-unique, try to append integers, so kueda would get
# kueda2 and not kueda34097348976 off the bat
appendix = 1
while suggested_login.to_s.size < MIN_LOGIN_SIZE || User.find_by_login(suggested_login)
suggested_login = "#{requested_login}#{appendix}"
appendix += 1
end
end
(MIN_LOGIN_SIZE..MAX_LOGIN_SIZE).include?(suggested_login.size) ? suggested_login : nil
end
# Destroying a user triggers a giant, slow, costly cascade of deletions that
# all occur within a transaction. This method tries to circumvent some of
# that madness by assigning communal assets to new users and pre-destroying
# some associates
def sane_destroy(options = {})
start_log_timer "sane_destroy user #{id}"
taxon_ids = []
if response = INatAPIService.get("/observations/taxonomy", {user_id: id})
taxon_ids = response.results.map{|a| a["id"]}
end
project_ids = self.project_ids
# delete lists without triggering most of the callbacks
lists.where("type = 'List' OR type IS NULL").find_each do |l|
l.listed_taxa.find_each do |lt|
lt.skip_sync_with_parent = true
lt.skip_update_cache_columns = true
lt.destroy
end
l.destroy
end
User.preload_associations(self, [ :stored_preferences, :roles, :flags ])
# delete observations without onerous callbacks
observations.includes([
{ user: :stored_preferences },
:votes_for,
:flags,
:stored_preferences,
:observation_photos,
:comments,
:annotations,
{ identifications: [
:taxon,
:user,
:flags
] },
:project_observations,
:project_invitations,
:quality_metrics,
:observation_field_values,
:observation_sounds,
:observation_reviews,
{ listed_taxa: :list },
:tags,
:taxon,
:quality_metrics,
:sounds
]).find_each(batch_size: 100) do |o|
o.skip_refresh_check_lists = true
o.skip_identifications = true
o.bulk_delete = true
o.comments.each{ |c| c.bulk_delete = true }
o.annotations.each{ |a| a.bulk_delete = true }
o.destroy
end
identification_observation_ids = Identification.where(user_id: id).
select(:observation_id).distinct.pluck(:observation_id)
comment_observation_ids = Comment.where(user_id: id, parent_type: "Observation").
select(:parent_id).distinct.pluck(:parent_id)
annotation_observation_ids = Annotation.where(user_id: id, resource_type: "Observation").
select(:resource_id).distinct.pluck(:resource_id)
unique_obs_ids = ( identification_observation_ids + comment_observation_ids +
annotation_observation_ids ).uniq
identifications.includes([
:observation,
:taxon,
:user,
:flags
]).find_each(batch_size: 100) do |i|
i.observation.skip_indexing = true
i.observation.bulk_delete = true
i.bulk_delete = true
i.destroy
end
identification_observation_ids.in_groups_of(100, false) do |obs_ids|
Observation.where(id: obs_ids).includes(
{ user: :stored_preferences },
:votes_for,
:flags,
:taxon,
{ photos: :flags },
{ identifications: [ :taxon, { user: :flags } ] },
:quality_metrics
).each do |o|
Identification.update_categories_for_observation( o, { skip_reload: true, skip_indexing: true } )
o.update_stats
end
Identification.elastic_index!(
scope: Identification.where(observation_id: obs_ids),
wait_for_index_refresh: true
)
end
comments.find_each(batch_size: 100) do |c|
c.bulk_delete = true
c.destroy
end
annotations.includes(:votes_for).find_each(batch_size: 100) do |a|
a.votes_for.each{ |v| v.bulk_delete = true }
a.bulk_delete = true
a.destroy
end
# transition ownership of projects with observations, delete the rest
Project.where(:user_id => id).find_each do |p|
if p.observations.exists?
if manager = p.project_users.managers.where("user_id != ?", id).first
p.user = manager.user
manager.role_will_change!
manager.save
else
pu = ProjectUser.create(:user => User.admins.first, :project => p)
p.user = pu.user
end
p.save
else
p.destroy
end
end
Observation.elastic_index!(ids: unique_obs_ids, wait_for_index_refresh: true )
# delete the user
destroy
# refresh check lists with relevant taxa
taxon_ids.in_groups_of(100) do |group|
CheckList.delay(:priority => OPTIONAL_PRIORITY, :queue => "slow").refresh(:taxa => group.compact)
end
end_log_timer
end
#
# Wipes all the data related to a user, within reason (can't do backups).
# Only for extreme cases and compliance with privacy regulations. Do not
# expose in the UI.
#
def self.forget( user_id, options = {} )
if user_id.blank?
raise "User ID cannot be blank"
end
if user = User.find_by_id( user_id )
puts "Destroying user (this could take a while)"
user.sane_destroy
end
puts "Updating flags created by user..."
Flag.where( user_id: user_id ).update_all( user_id: -1 )
deleted_observations = DeletedObservation.where( user_id: user_id )
puts "Deleting #{deleted_observations.count} DeletedObservations"
deleted_observations.delete_all
unless options[:skip_aws]
s3_config = YAML.load_file( File.join( Rails.root, "config", "s3.yml") )
s3_client = ::Aws::S3::Client.new(
access_key_id: s3_config["access_key_id"],
secret_access_key: s3_config["secret_access_key"],
region: CONFIG.s3_region
)
cf_client = ::Aws::CloudFront::Client.new(
access_key_id: s3_config["access_key_id"],
secret_access_key: s3_config["secret_access_key"],
region: CONFIG.s3_region
)
deleted_photos = DeletedPhoto.where( user_id: user_id )
puts "Deleting #{deleted_photos.count} DeletedPhotos and associated records from s3"
deleted_photos.find_each do |dp|
images = s3_client.list_objects( bucket: CONFIG.s3_bucket, prefix: "photos/#{ dp.photo_id }/" ).contents
puts "\tPhoto #{dp.photo_id}, removing #{images.size} images from S3"
if images.any?
s3_client.delete_objects( bucket: CONFIG.s3_bucket, delete: { objects: images.map{|s| { key: s.key } } } )
end
dp.destroy
end
# delete user profile pic form s3
user_images = s3_client.list_objects( bucket: CONFIG.s3_bucket, prefix: "attachments/users/icons/#{user_id}/" ).contents
if user_images.any?
puts "Deleting profile pic from S3"
s3_client.delete_objects( bucket: CONFIG.s3_bucket, delete: { objects: user_images.map{|s| { key: s.key } } } )
end
# This might cause problems with multiple simultaneous invalidations. FWIW,
# CloudFront is supposed to expire things in 24 hours by default
if options[:cloudfront_distribution_id]
paths = deleted_photos.compact.map{|dp| "/photos/#{ dp.photo_id }/*" }
if user_images.any?
paths << "attachments/users/icons/#{user_id}/*"
end
cf_client.create_invalidation(
distribution_id: options[:cloudfront_distribution_id],
invalidation_batch: {
paths: {
quantity: paths.size,
items: paths
},
caller_reference: "#{paths[0]}/#{Time.now.to_i}"
}
)
end
deleted_sounds = DeletedSound.where( user_id: user_id )
puts "Deleting #{deleted_sounds.count} DeletedSounds and associated records from s3"
deleted_sounds.find_each do |ds|
sounds = s3_client.list_objects( bucket: CONFIG.s3_bucket, prefix: "sounds/#{ ds.sound_id }." ).contents
puts "\tSound #{ds.sound_id}, removing #{sounds.size} sounds from S3"
if sounds.any?
s3_client.delete_objects( bucket: CONFIG.s3_bucket, delete: { objects: sounds.map{|s| { key: s.key } } } )
end
ds.destroy
end
end
# Delete from PandionES where user_id:user_id
if options[:logstash_es_host]
logstash_es_client = Elasticsearch::Client.new(
host: options[:logstash_es_host],
)
puts "Deleting logstash records"
begin
logstash_es_client.delete_by_query(
index: "logstash-*",
body: {
query: {
term: {
user_id: user_id
}
}
}
)
rescue Faraday::TimeoutError, Net::ReadTimeout
retry
end
else
puts "Logstash ES host not configured. You may have to manually remove log entries for this user."
end
puts "Deleting DeletedUser"
DeletedUser.where( user_id: user_id ).delete_all
# Trigger sync on all staging servers
puts
puts "Ensure all staging servers get synced"
puts
end
def create_deleted_user
DeletedUser.create(
:user_id => id,
:login => login,
:email => email,
:user_created_at => created_at,
:user_updated_at => updated_at,
:observations_count => observations_count
)
true
end
def remove_oauth_access_tokens
return true unless frozen?
Doorkeeper::AccessToken.where( resource_owner_id: id ).delete_all
true
end
def destroy_project_rules
ProjectObservationRule.where(
operand_type: "User",
operand_id: id
).destroy_all
end
def self.reindex_faved_observations_after_destroy( user_id )
while true
obs = Observation.elastic_search(
_source: [:id],
limit: 200,
where: {
nested: {
path: "votes",
query: {
bool: {
filter: {
term: {
"votes.user_id": user_id
}
}
}
}
}
}
).results.results
break if obs.blank?
Observation.elastic_index!( ids: obs.map(&:id), wait_for_index_refresh: true )
end
end
def reindex_faved_observations_after_destroy_later
User.delay.reindex_faved_observations_after_destroy( id )
true
end
def generate_csv(path, columns, options = {})
of_names = ObservationField.joins(observation_field_values: :observation).
where("observations.user_id = ?", id).
select("DISTINCT observation_fields.name").
map{|of| "field:#{of.normalized_name}"}
columns += of_names
columns -= %w(user_id user_login)
CSV.open(path, 'w') do |csv|
csv << columns
self.observations.includes(:taxon, {:observation_field_values => :observation_field}).find_each do |observation|
csv << columns.map{|c| observation.send(c) rescue nil}
end
end
end
def destroy_messages_by_suspended_user
return true unless suspended?
Message.inbox.unread.where(:from_user_id => id).destroy_all
true
end
def revoke_access_tokens_by_suspended_user
return true unless suspended?
Doorkeeper::AccessToken.where( resource_owner_id: id ).each(&:revoke)
true
end
def restore_access_tokens_by_suspended_user
return true if suspended?
if suspended_at_changed?
# This is not an ideal solution because there are reasons to revoke a
# token that are not related to suspension, like trying to deal with a
# oauth app that's behaving badly for some reason, or a user's token is
# stolen and someone else is using it, but I'm hoping those are rare
# situations that we can deal with by deleting tokens
Doorkeeper::AccessToken.where( resource_owner_id: id ).update_all( revoked_at: nil )
end
true
end
def set_observations_taxa_if_pref_changed
if prefers_community_taxa_changed? && !id.blank?
Observation.delay( priority: USER_INTEGRITY_PRIORITY ).set_observations_taxa_for_user( id )
end
true
end
def update_photo_properties
changes = {}
changes[:native_username] = login if login_changed?
changes[:native_realname] = name if name_changed?
unless changes.blank?
delay( priority: USER_INTEGRITY_PRIORITY ).update_photos_with_changes( changes )
end
true
end
def update_photos_with_changes( changes )
return if changes.blank?
photos.update_all( changes )
end
def recent_notifications(options={})
return [] if CONFIG.has_subscribers == :disabled
options[:filters] = options[:filters] ? options[:filters].dup : [ ]
options[:inverse_filters] = options[:inverse_filters] ? options[:inverse_filters].dup : [ ]
options[:per_page] ||= 10
if options[:unviewed]
options[:inverse_filters] << { term: { viewed_subscriber_ids: id } }
elsif options[:viewed]
options[:filters] << { term: { viewed_subscriber_ids: id } }
end
options[:filters] << { term: { subscriber_ids: id } }
ops = {
filters: options[:filters],
inverse_filters: options[:inverse_filters],
per_page: options[:per_page],
sort: { id: :desc }
}
UpdateAction.elastic_paginate(
filters: options[:filters],
inverse_filters: options[:inverse_filters],
per_page: options[:per_page],
sort: { id: :desc })
end
def blocked_by?( user )
user_blocks_as_blocked_user.where( user_id: user ).exists?
end
def self.default_json_options
{
only: [
:id,
:login,
:name,
:created,
:observations_count,
:identifications_count
],
methods: [
:user_icon_url,
:medium_user_icon_url,
:original_user_icon_url
]
}
end
def self.active_ids(at_time = Time.now)
date_range = (at_time - 30.days)..at_time
classes = [ Identification, Observation, Comment, Post ]
# get the unique user_ids that created instances of any of these
# classes within the last 30 days, then get the union (with .inject(:|))
# of the array of arrays.
user_ids = classes.collect{ |klass|
klass.select("DISTINCT(user_id)").where(created_at: date_range).
collect{ |i| i.user_id }
}.inject(:|)
end
def self.header_cache_key_for(user, options = {})
user_id = user.is_a?(User) ? user.id : user
user_id ||= "signed_on"
site_name = options[:site].try(:name) || options[:site_name]
site_name ||= user.site.try(:name) if user.is_a?(User)
version = ApplicationController::HEADER_VERSION
"header_cache_key_for_#{user_id}_on_#{site_name}_#{I18n.locale}_#{version}"
end
def self.update_identifications_counter_cache(user_id)
return unless user = User.find_by_id(user_id)
new_fields_result = Observation.elastic_search(
filters: [
{ term: { non_owner_identifier_user_ids: user_id } }
],
size: 0,
track_total_hits: true
)
count = (new_fields_result && new_fields_result.response) ?
new_fields_result.response.hits.total.value : 0
User.where(id: user_id).update_all(identifications_count: count)
end
def self.update_observations_counter_cache(user_id)
return unless user = User.find_by_id( user_id )
result = Observation.elastic_search(
filters: [
{ bool: { must: [
{ term: { "user.id": user_id } },
] } }
],
size: 0,
track_total_hits: true
)
count = (result && result.response) ? result.response.hits.total.value : 0
User.where( id: user_id ).update_all( observations_count: count )
user.reload
user.elastic_index!
end
def self.update_species_counter_cache( user, options={ } )
unless user.is_a?( User )
u = User.find_by_id( user )
u ||= User.find_by_login( user )
user = u
end
return unless user
count = INatAPIService.observations_species_counts( user_id: user.id, per_page: 0 ).total_results rescue 0
unless user.species_count == count
User.where( id: user.id ).update_all( species_count: count )
unless options[:skip_indexing]
user.reload
user.elastic_index!
end
end
end
def to_plain_s
"User #{login}"
end
def subscribed_to?(resource)
subscriptions.where(resource: resource).exists?
end
def recent_observation_fields
ObservationField.recently_used_by(self).limit(10)
end
def test_groups_array
test_groups.to_s.split( "|" )
end
def in_test_group?( group )
test_groups_array.include?( group)
end
def flagged_with( flag, options = {} )
evaluate_new_flag_for_spam( flag )
elastic_index!
Observation.elastic_index!( scope: Observation.by( id ), delay: true )
Identification.elastic_index!( scope: Identification.where( user_id: id ), delay: true )
Project.elastic_index!( scope: Project.where( user_id: id ), delay: true )
end
def personal_lists
lists.not_flagged_as_spam.
where("type = 'List' OR type IS NULL")
end
def privileged_with?( privilege )
user_privileges.where( privilege: privilege ).where( "revoked_at IS NULL" ).exists?
end
# Apparently some people, and maybe some third-party auth providers, sometimes
# stick the email in the name field... which is not ok
def remove_email_from_name
self.name = User.remove_email_from_string( self.name )
true
end
def self.remove_email_from_string( s )
return s if s.blank?
email_pattern = /#{Devise.email_regexp.to_s.gsub("\\A" , "").gsub( "\\z", "" )}/
s.gsub( email_pattern, "" )
end
def set_pi_consent_at
if pi_consent
self.pi_consent_at = Time.now
end
true
end
def donor?
donorbox_donor_id.to_i > 0
end
def display_donor_since
return nil unless prefers_monthly_supporter_badge?
donorbox_plan_status == "active" &&
donorbox_plan_type == "monthly" &&
donorbox_plan_started_at
end
# given an array of taxa, return the taxa and ancestors that were not observed
# before the given date. Note that this method does not check if the taxa were observed
# by this user on this date
def taxa_unobserved_before_date( date, taxa = [] )
return [] if taxa.empty?
taxa_plus_ancestor_ids = ( taxa.map( &:id ) + taxa.map( &:ancestor_ids ).flatten ).uniq
taxon_counts = Observation.elastic_search(
size: 0,
filters: [
{ term: { "user.id": id } },
{ terms: { "taxon.ancestor_ids": taxa_plus_ancestor_ids } },
{ range: { "observed_on_details.date": { lt: date.to_s } } }
],
aggregate: {
distinct_taxa: {
terms: {
field: "taxon.ancestor_ids",
include: taxa_plus_ancestor_ids,
size: taxa_plus_ancestor_ids.length
}
}
}
).response.aggregations rescue nil
return [] if taxon_counts.blank?
previous_observed_taxon_ids = taxon_counts.distinct_taxa.buckets.map{ |b| b["key"] }
Taxon.where( id: taxa_plus_ancestor_ids - previous_observed_taxon_ids )
end
# this method will look at all this users photos and create separate delayed jobs
# for each photo that should be moved to the other bucket
def self.enqueue_photo_bucket_moving_jobs( user )
return unless LocalPhoto.odp_s3_bucket_enabled?
unless user.is_a?( User )
u = User.find_by_id( user )
u ||= User.find_by_login( user )
user = u
end
LocalPhoto.where( user_id: user.id ).select( :id, :license, :original_url, :user_id ).includes( :user ).each do |photo|
if photo.photo_bucket_should_be_changed?
LocalPhoto.delay(
queue: "photos",
unique_hash: { "LocalPhoto::change_photo_bucket_if_needed": photo.id }
).change_photo_bucket_if_needed( photo.id )
end
end
# return nil so this isn't returning all results of the above query
nil
end
# Iterates over recently created accounts of unknown spammer status, zero
# obs or ids, and a description with a link. Attempts to run them past
# akismet three times, which seems to catch most spammers
def self.check_recent_probable_spammers( limit = 100 )
spammers = []
num_checks = {}
User.order( "id desc" ).limit( limit ).
where( "spammer is null " ).
where( "created_at < ? ", 12.hours.ago ). # half day grace period
where( "description is not null and description != '' and description ilike '%http%'" ).
where( "observations_count = 0 and identifications_count = 0" ).
pluck(:id).
in_groups_of( 10 ) do |ids|
puts
puts "BATCH #{ids[0]}"
puts
3.times do |i|
batch = User.where( "id IN (?)", ids )
puts "Try #{i}"
batch.each do |u|
next if spammers.include?( u.login )
num_checks[u.login] ||= 0
puts "#{u}, checked #{num_checks[u.login]} times already"
num_checks[u.login] += 1
u.description_will_change!
u.check_for_spam
puts "\tu.akismet_response: #{u.akismet_response}"
u.reload
if u.spammer == true
puts "\tSPAM"
spammers << u.login
end
sleep 1
end
sleep 10
end
end
end
def self.ip_address_is_often_suspended( ip )
return false if ip.blank?
count_suspended = User.where( last_ip: ip ).where( "suspended_at IS NOT NULL" ).count
count_active = User.where( last_ip: ip ).where( "suspended_at IS NULL" ).count
total = count_suspended + count_active
return false if total < 3
return count_suspended.to_f / ( count_suspended + count_active ).to_f >= 0.9
end
end
| 35.508395 | 163 | 0.690441 |
1ca2bd5960a49b10a25153be2887bc9c16c6bd9e
| 1,421 |
require 'csv'
require File.join(Rails.root, "app", "reports", "hbx_reports", "ivl_enrollment_report")
# The idea behind this report is to get a list of all ivl enrollments which are currently in EA.
# This report can be executed in two ways they are
# First way is by passing desired purchase dates. Steps to follow
# 1) You need to pull a list of enrollments from glue with this script on a text file(bundle exec rails r script/queries/print_all_policy_ids.rb > all_glue_policies.txt -e production)
# 2) Place that file into the Enroll Root directory.
# 3) Run the below rake task
# RAILS_ENV=production bundle exec rake hbx_reports:ivl_enrollment_report purchase_date_start='06/01/2018' purchase_date_end='06/10/2018'
# Another way is by running daily and it will give enrollment details of past 30 days. Steps to follow
# 1) You need to pull a list of enrollments from glue with this script on a text file(bundle exec rails r script/queries/print_all_policy_ids.rb > all_glue_policies.txt -e production)
# 2) Place that file into the Enroll Root directory.
# 3) Run the below rake task
# RAILS_ENV=production bundle exec rake hbx_reports:ivl_enrollment_report
#Errors are logged into logger file. For any errors please do check this file "log/ivl_enrollment_report_error.log"
namespace :hbx_reports do
desc "IVL Enrollment Recon Report"
IvlEnrollmentReport.define_task :ivl_enrollment_report => :environment
end
| 64.590909 | 183 | 0.794511 |
288949f26f11558a45a7f49a8063097fc4d0bd46
| 870 |
class ApplicationHelper::Toolbar::ContainerBuildCenter < ApplicationHelper::Toolbar::Basic
button_group('container_build_vmdb', [
select(
:container_build_vmdb_choice,
nil,
t = N_('Configuration'),
t,
:items => [
button(
:container_build_scan,
'fa fa-search fa-lg',
N_('Perform SmartState Analysis on this item'),
N_('Perform SmartState Analysis'),
:confirm => N_("Perform SmartState Analysis on this item?")),
]
),
])
button_group('container_build_policy', [
select(
:container_build_policy_choice,
nil,
t = N_('Policy'),
t,
:items => [
button(
:container_build_tag,
'pficon pficon-edit fa-lg',
N_('Edit Tags for this Container Build'),
N_('Edit Tags')),
]
),
])
end
| 25.588235 | 90 | 0.565517 |
0366685452650b9d4a4e9f96ba8e421657a486cf
| 178 |
# frozen_string_literal: true
class UserController < ApplicationController
before_action :apply_rparam
def current_user
end
def index
render plain: nil
end
end
| 12.714286 | 44 | 0.764045 |
38a8e7297537c59cd38101d35412eb1958a64c68
| 1,818 |
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/classes', __FILE__)
# erfc is the complementary error function
describe "Math.erfc" do
it "returns a float" do
Math.erf(1).should be_kind_of(Float)
end
it "returns the complimentary error function of the argument" do
Math.erfc(0).should be_close(1.0, TOLERANCE)
Math.erfc(1).should be_close(0.157299207050285, TOLERANCE)
Math.erfc(-1).should be_close(1.84270079294971, TOLERANCE)
Math.erfc(0.5).should be_close(0.479500122186953, TOLERANCE)
Math.erfc(-0.5).should be_close(1.52049987781305, TOLERANCE)
Math.erfc(10000).should be_close(0.0, TOLERANCE)
Math.erfc(-10000).should be_close(2.0, TOLERANCE)
Math.erfc(0.00000000000001).should be_close(0.999999999999989, TOLERANCE)
Math.erfc(-0.00000000000001).should be_close(1.00000000000001, TOLERANCE)
end
ruby_version_is ""..."1.9" do
it "raises an ArgumentError if the argument cannot be coerced with Float()" do
lambda { Math.erfc("test") }.should raise_error(ArgumentError)
end
end
ruby_version_is "1.9" do
it "raises a TypeError if the argument cannot be coerced with Float()" do
lambda { Math.erfc("test") }.should raise_error(TypeError)
end
end
it "returns NaN given NaN" do
Math.erfc(nan_value).nan?.should be_true
end
it "raises a TypeError if the argument is nil" do
lambda { Math.erfc(nil) }.should raise_error(TypeError)
end
it "accepts any argument that can be coerced with Float()" do
Math.erfc(MathSpecs::Float.new).should be_close(0.157299207050285, TOLERANCE)
end
end
describe "Math#erfc" do
it "is accessible as a private instance method" do
IncludesMath.new.send(:erf, 3.1415).should be_close(0.999991118444483, TOLERANCE)
end
end
| 34.961538 | 85 | 0.725523 |
ed93bf78cd89911e522d45911dc1048624d3d1bd
| 1,898 |
# frozen_string_literal: true
# Catalog extension for configuring display fields that pull from locale-specific Solr fields
module MultilingualLocaleAwareField
def lang_config
@lang_config ||= {
'ar' => ['ar-Arab', default: (sorted_locales(Settings.acceptable_bcp47_codes, '-Arab') + %w[none]).uniq],
'en' => ['en', default: (sorted_locales(Settings.acceptable_bcp47_codes, '-Latn') + %w[none]).uniq]
}.with_indifferent_access
end
def multilingual_locale_aware_field(field_prefix, suffix = 'ssim')
{
pattern: "#{field_prefix}.%<lang>s_#{suffix}",
values: lambda do |field_config, document, view_context|
pref_langs, options = lang_config[I18n.locale]
values = Array.wrap(pref_langs).flatten.map do |lang|
subfield_config = field_config.merge(field: format(field_config.pattern, lang: lang), values: nil)
Blacklight::FieldRetriever.new(document, subfield_config, view_context).fetch
end
if values.none?(&:any?)
values = Array.wrap(options[:default]).flatten.map do |lang|
subfield_config = field_config.merge(field: format(field_config.pattern, lang: lang), values: nil)
Blacklight::FieldRetriever.new(document, subfield_config, view_context).fetch
end
end
if values.none?(&:any?)
subfield_config = field_config.merge(field: "#{field_prefix}_#{suffix}", values: nil)
values = [Blacklight::FieldRetriever.new(document, subfield_config, view_context).fetch]
end
if field_config.first
values.find(&:any?)
else
values.flatten
end
end
}
end
private
def sorted_locales(locales, sort_by)
locales.sort_by.with_index do |locale, index|
if locale.include?(sort_by)
index - locales.length
else
index
end
end
end
end
| 33.892857 | 111 | 0.659642 |
39ae51891b6c3de646b718a63753ad2cd39cd905
| 330 |
require 'test_helper'
class StaticPagesControllerTest < ActionController::TestCase
test "should get home" do
get :home
assert_response :success
end
test "should get about" do
get :about
assert_response :success
end
test "should get license" do
get :license
assert_response :success
end
end
| 16.5 | 60 | 0.715152 |
1ce0f5339da59fdea22e1ce8d02a136563ec4ef9
| 2,879 |
module Scram
# Model to represent a Holder's permission policy
class Policy
include Mongoid::Document
embeds_many :targets, class_name: "Scram::Target"
validates_presence_of :name
# @return [String] Name for this Policy. Purely for organizational purposes.
field :name, type: String
# @return [String] What model this Policy applies to. Will be nil if this Policy is not bound to a model.
field :context, type: String
# @return [Integer] Priority to allow this policy to override another conflicting {Scram::Policy} opinion.
field :priority, type: Integer, default: 0
# Helper method to easily tell if this policy is bound to a model
# @note Unnecessary since we can just call model.nil?, but it is helpful nonetheless
# @return [Boolean] True if this Policy is bound to a model, false otherwise
def model?
return !model.nil?
end
# Attempts to constantize and get a model
# @return [Object, nil] An object, likely a {::Mongoid::Document}, that this policy is bound to. nil if there is none.
def model
begin
return Module.const_get(context)
rescue # NameError if context as a constant doesn't exist, TypeError if context nil
return nil
end
end
# Checks if a {Scram::Holder} can perform some action on an object by checking targets
# @param holder [Scram::Holder] The actor
# @param action [String] What the user is trying to do to obj
# @param obj [Object] The receiver of the action
# @return [Symbol] This policy's opinion on an action and object. :allow and :deny mean this policy has a target who explicitly defines
# its opinion, while :abstain means that none of the targets are applicable to the action, and so has no opinion.
def can? holder, action, obj
obj = obj.to_s if obj.is_a? Symbol
action = action.to_s
# Abstain if policy doesn't apply to the obj
if obj.is_a? String # String permissions
return :abstain if self.model? # abstain if policy doesn't handle strings
else # Model permissions
return :abstain if !self.model? # abstain if policy doesn't handle models
if obj.is_a?(Class) # Passed in a class, need to check based off the passed in model's name
return :abstain if self.context != obj.to_s # abstain if policy doesn't handle these types of models
else # Passed in an instance of a model, need to check based off the instance's class's name
return :abstain if self.context != obj.class.name
end
end
# Checks targets in priority order for explicit allow or deny.
targets.order_by([[:priority, :desc]]).each do |target|
opinion = target.can?(holder, action, obj)
return opinion if %i[allow deny].include? opinion
end
return :abstain
end
end
end
| 42.338235 | 139 | 0.681834 |
aba3e71f2745671ec95360d3414b7cccf5aebfd3
| 461 |
require 'test_helper'
class User::PostsControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get user_posts_index_url
assert_response :success
end
test "should get new" do
get user_posts_new_url
assert_response :success
end
test "should get show" do
get user_posts_show_url
assert_response :success
end
test "should get edit" do
get user_posts_edit_url
assert_response :success
end
end
| 18.44 | 65 | 0.741866 |
1c12b27d6f39799ae42aa735ba5f2ca85f7bbc6c
| 1,777 |
require 'rails_helper'
describe "Toggle Bool Builder", type: :feature do
context "when using inside another resource" do
before do
load_resources(true) do
ActiveAdmin.register(Invoice)
ActiveAdmin.register(Category) do
show do
attributes_table do
row :id
end
table_for resource.invoices do
toggle_bool_column :active
end
end
end
end
end
it "generates the correct url" do
@category = Category.create(name: "International")
@invoice = create_invoice(active: true, category: @category)
visit admin_category_path(@category)
switch = find("span.toggle-bool-switch")
expect(switch["data-url"]).to eq("/admin/invoices/#{@invoice.id}")
end
end
context "shows corresponding switch" do
before do
register_index(Invoice) do
toggle_bool_column :active
end
end
context "with true value" do
before do
@invoice = create_invoice(active: true)
visit admin_invoices_path
end
it "generates the correct resource url" do
switch = find("#toggle-invoice-#{@invoice.id}-active")
expect(switch["data-url"]).to eq("/admin/invoices/#{@invoice.id}")
end
it "switch is on" do
switch = find("#toggle-invoice-#{@invoice.id}-active")
expect(switch[:class]).to include("on")
end
end
context "with false value" do
before do
@invoice = create_invoice(active: false)
visit admin_invoices_path
end
it "switch is off" do
switch = find("#toggle-invoice-#{@invoice.id}-active")
expect(switch[:class]).not_to include("on")
end
end
end
end
| 26.132353 | 74 | 0.606078 |
61cc284901d1f1a63f391bf208b0a494a22a56f4
| 595 |
class HomeController < ApplicationController
def index
@last_games = Game.order('games.created_at desc').includes(:user, :color).limit(15)
unless user_manager?
@last_games = @last_games.to_show_to_anyone
end
@last_comments = Comment.order('comments.created_at desc').includes(:game, :user).limit(15)
unless user_manager?
@last_comments = @last_comments.where('games.competition != 1').references(:game)
end
@last_video_games = Game.order('games.video_at desc').where('LENGTH(games.video_url) > 0')
end
def ping
render layout: false
end
end
| 29.75 | 95 | 0.709244 |
2607f52d01f3ac30b03e4b883a649b29d3457501
| 680 |
require "rspec"
RSpec.configure do |config|
config.expect_with :rspec do |c|
c.syntax = :expect
end
config.filter_run focus: true
config.run_all_when_everything_filtered = true
end
RSpec::Matchers.define :render_html do |html|
diffable
match do |markdown|
@expected = html.strip
instance = Middleman::HashiCorp::RedcarpetHTML.new
instance.middleman_app = middleman_app
parser = Redcarpet::Markdown.new(instance)
@actual = parser.render(markdown).strip
@expected == @actual
end
end
# The default middleman application server.
#
# @return [Middleman::Application]
def middleman_app
@app ||= Middleman::Application.server.inst
end
| 20 | 54 | 0.729412 |
bb3cf643740d04e2a424c47c65789461c92e3b63
| 3,745 |
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2017, Google Inc. All Rights Reserved.
#
# License:: 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.
#
# This example prints all ad unit names as a tree.
require 'ad_manager_api'
def get_ad_unit_hierarchy(ad_manager)
# Get the NetworkService and InventoryService.
network_service = ad_manager.service(:NetworkService, API_VERSION)
inventory_service = ad_manager.service(:InventoryService, API_VERSION)
# Set the parent ad unit's ID for all children ad units to be fetched from.
current_network = network_service.get_current_network()
root_ad_unit_id = current_network[:effective_root_ad_unit_id].to_i
# Create a statement to select only the root ad unit by ID.
root_ad_unit_statement = ad_manager.new_statement_builder do |sb|
sb.where = 'id = :id'
sb.with_bind_variable('id', root_ad_unit_id)
sb.limit = 1
end
# Make a request for the root ad unit
response = inventory_service.get_ad_units_by_statement(
root_ad_unit_statement.to_statement()
)
root_ad_unit = response[:results].first
# Create a statement to select all ad units.
statement = ad_manager.new_statement_builder()
# Get all ad units in order to construct the hierarchy later.
all_ad_units = []
page = {:total_result_set_size => 0}
begin
page = inventory_service.get_ad_units_by_statement(
statement.to_statement()
)
unless page[:results].nil?
all_ad_units += page[:results]
end
statement.offset += statement.limit
end while statement.offset < page[:total_result_set_size]
# Make call to helper functions for displaying ad unit hierarchy.
display_ad_unit_hierarchy(root_ad_unit, all_ad_units)
end
def display_ad_unit_hierarchy(root_ad_unit, ad_unit_list)
parent_id_to_children_map = {}
ad_unit_list.each do |ad_unit|
unless ad_unit[:parent_id].nil?
(parent_id_to_children_map[ad_unit[:parent_id]] ||= []) << ad_unit
end
end
display_hierarchy(root_ad_unit, parent_id_to_children_map)
end
def display_hierarchy(root, parent_id_to_children_map, depth=0)
indent_string = '%s+--' % ([' '] * depth).join('|')
puts '%s%s (%s)' % [indent_string, root[:name], root[:id]]
parent_id_to_children_map.fetch(root[:id], []).each do |child|
display_hierarchy(child, parent_id_to_children_map, depth+1)
end
end
if __FILE__ == $0
API_VERSION = :v201805
# Get AdManagerApi instance and load configuration from ~/ad_manager_api.yml.
ad_manager = AdManagerApi::Api.new
# To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
# the configuration file or provide your own logger:
# ad_manager.logger = Logger.new('ad_manager_xml.log')
begin
get_ad_unit_hierarchy(ad_manager)
# HTTP errors.
rescue AdsCommon::Errors::HttpError => e
puts "HTTP Error: %s" % e
# API errors.
rescue AdManagerApi::Errors::ApiException => e
puts "Message: %s" % e.message
puts 'Errors:'
e.errors.each_with_index do |error, index|
puts "\tError [%d]:" % (index + 1)
error.each do |field, value|
puts "\t\t%s: %s" % [field, value]
end
end
end
end
| 33.141593 | 79 | 0.711615 |
d50464f48346e01a57108cff81a10b413d68fc80
| 1,960 |
# -*- encoding: utf-8 -*-
# stub: devise 4.2.0 ruby lib
Gem::Specification.new do |s|
s.name = "devise".freeze
s.version = "4.2.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Jos\u00E9 Valim".freeze, "Carlos Ant\u00F4nio".freeze]
s.date = "2016-07-01"
s.description = "Flexible authentication solution for Rails with Warden".freeze
s.email = "[email protected]".freeze
s.homepage = "https://github.com/plataformatec/devise".freeze
s.licenses = ["MIT".freeze]
s.required_ruby_version = Gem::Requirement.new(">= 2.1.0".freeze)
s.rubygems_version = "2.6.10".freeze
s.summary = "Flexible authentication solution for Rails with Warden".freeze
s.installed_by_version = "2.6.10" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<warden>.freeze, ["~> 1.2.3"])
s.add_runtime_dependency(%q<orm_adapter>.freeze, ["~> 0.1"])
s.add_runtime_dependency(%q<bcrypt>.freeze, ["~> 3.0"])
s.add_runtime_dependency(%q<railties>.freeze, ["< 5.1", ">= 4.1.0"])
s.add_runtime_dependency(%q<responders>.freeze, [">= 0"])
else
s.add_dependency(%q<warden>.freeze, ["~> 1.2.3"])
s.add_dependency(%q<orm_adapter>.freeze, ["~> 0.1"])
s.add_dependency(%q<bcrypt>.freeze, ["~> 3.0"])
s.add_dependency(%q<railties>.freeze, ["< 5.1", ">= 4.1.0"])
s.add_dependency(%q<responders>.freeze, [">= 0"])
end
else
s.add_dependency(%q<warden>.freeze, ["~> 1.2.3"])
s.add_dependency(%q<orm_adapter>.freeze, ["~> 0.1"])
s.add_dependency(%q<bcrypt>.freeze, ["~> 3.0"])
s.add_dependency(%q<railties>.freeze, ["< 5.1", ">= 4.1.0"])
s.add_dependency(%q<responders>.freeze, [">= 0"])
end
end
| 42.608696 | 112 | 0.65051 |
e80b42de825e124e0a1e445f72104c15e64fbb69
| 607 |
# frozen_string_literal: true
require 'test_helper'
class InvitesControllerTest < ActionDispatch::IntegrationTest
test 'should get accept invite to account' do
invite = create :invite
get accept_invite_url(invite.token)
assert_response :redirect
assert_redirected_to account_url(invite.account)
end
test 'should get accept invite to board' do
invite = create :invite
board = create :board, account: invite.account
invite.update board: board
get accept_invite_url(invite.token)
assert_response :redirect
assert_redirected_to board_url(invite.board)
end
end
| 27.590909 | 61 | 0.762768 |
08feb502fe6df9f348c3c8292e86c3665d0b319c
| 1,137 |
require 'tilt/template'
require 'coffee_script'
module Tilt
# CoffeeScript template implementation. See:
# http://coffeescript.org/
#
# CoffeeScript templates do not support object scopes, locals, or yield.
class CoffeeScriptTemplate < Template
self.default_mime_type = 'application/javascript'
@@default_bare = false
def self.default_bare
@@default_bare
end
def self.default_bare=(value)
@@default_bare = value
end
# DEPRECATED
def self.default_no_wrap
@@default_bare
end
# DEPRECATED
def self.default_no_wrap=(value)
@@default_bare = value
end
def self.literate?
false
end
def prepare
if !options.key?(:bare) and !options.key?(:no_wrap)
options[:bare] = self.class.default_bare
end
options[:literate] ||= self.class.literate?
end
def evaluate(scope, locals, &block)
@output ||= CoffeeScript.compile(data, options)
end
def allows_script?
false
end
end
class CoffeeScriptLiterateTemplate < CoffeeScriptTemplate
def self.literate?
true
end
end
end
| 19.271186 | 74 | 0.659631 |
01f36e4c15731b8cf15682f0bcc959d45ecd5f4d
| 7,608 |
require 'rest_in_peace'
describe RESTinPeace do
let(:extended_class) do
Class.new do
include RESTinPeace
attr_writer :relation
rest_in_peace do
attributes do
read :id, :name, :relation
write :my_array, :my_hash, :array_with_hash, :overridden_attribute, :description
end
end
def overridden_attribute
'something else'
end
def self_defined_method
puts 'yolo'
end
end
end
let(:my_array) { %w(element) }
let(:name) { 'test' }
let(:my_hash) { { element1: 'yolo' } }
let(:array_with_hash) { [my_hash.dup] }
let(:overridden_attribute) { 'initial value' }
let(:description) { 'old description' }
let(:attributes) do
{
id: 1,
name: name,
relation: { id: 1234 },
my_array: my_array,
my_hash: my_hash,
array_with_hash: array_with_hash,
overridden_attribute: overridden_attribute,
description: description,
}
end
let(:instance) { extended_class.new(attributes) }
describe '::api' do
subject { extended_class }
specify { expect(subject).to respond_to(:api).with(0).arguments }
end
describe '::rest_in_peace' do
subject { extended_class }
specify { expect(subject).to respond_to(:rest_in_peace).with(0).arguments }
let(:definition_proxy) { object_double(RESTinPeace::DefinitionProxy) }
it 'evaluates the given block inside the definition proxy' do
allow(RESTinPeace::DefinitionProxy).to receive(:new).with(subject).and_return(definition_proxy)
expect(definition_proxy).to receive(:instance_eval) do |&block|
expect(block).to be_instance_of(Proc)
end
subject.rest_in_peace { }
end
end
describe '::rip_registry' do
subject { extended_class }
specify { expect(extended_class).to respond_to(:rip_registry) }
specify { expect(extended_class.rip_registry).to eq(collection: [], resource: []) }
end
describe '::rip_attributes' do
subject { extended_class }
specify { expect(extended_class).to respond_to(:rip_attributes) }
specify do
expect(extended_class.rip_attributes).to eq(
read: [:id, :name, :relation, :my_array, :my_hash, :array_with_hash, :overridden_attribute, :description],
write: [:my_array, :my_hash, :array_with_hash, :overridden_attribute, :description])
end
end
describe '::rip_namespace' do
subject { extended_class }
specify { expect(subject).to respond_to(:rip_namespace) }
specify { expect(subject).to respond_to(:rip_namespace=) }
it 'allows setting the namespace' do
expect { subject.rip_namespace = :blubb }.
to change { subject.rip_namespace }.from(nil).to(:blubb)
end
end
describe '#api' do
subject { instance }
specify { expect(subject).to respond_to(:api).with(0).arguments }
end
describe '#to_h' do
subject { instance.to_h }
specify { expect(subject).to eq(attributes.merge(overridden_attribute: 'something else')) }
end
describe '#payload' do
subject { instance }
specify { expect(subject).to respond_to(:payload).with(0).arguments }
context 'without a namspace defined' do
it 'adds id by default' do
expect(subject.payload).to include(id: 1)
end
context 'overridden getter' do
before do
subject.overridden_attribute = 'new value'
end
specify { expect(subject.payload).to include(overridden_attribute: 'something else') }
end
context 'self defined methods' do
specify { expect(subject).to respond_to(:self_defined_method) }
specify { expect(subject.payload).to_not include(:self_defined_method) }
end
context 'hash' do
before do
subject.my_hash = { element1: 'swag' }
end
specify { expect(subject.payload[:my_hash]).to eq(element1: 'swag') }
end
context 'with objects assigned' do
let(:new_hash) { double('OtherClass') }
before do
subject.my_hash = new_hash
end
it 'deeply calls payload' do
expect(new_hash).to receive(:payload).and_return({})
subject.payload
end
end
context 'all write attributes' do
specify do
expect(subject.payload(false)).to eq(
id: 1,
my_array: ['element'],
my_hash: { element1: 'yolo' },
array_with_hash: [{ element1: 'yolo' }],
overridden_attribute: 'something else',
description: 'old description'
)
end
end
context 'changes only' do
specify do
expect(subject.payload(true)).to eq(
id: 1,
my_array: ['element'],
my_hash: { element1: 'yolo' },
array_with_hash: [{ element1: 'yolo' }],
overridden_attribute: 'something else',
description: 'old description'
)
end
end
end
context 'with a namespace defined' do
let(:extended_class) do
Class.new do
include RESTinPeace
rest_in_peace do
attributes do
read :id, :relation
write :name, :description
end
namespace_attributes_with :blubb
end
end
end
before do
subject.name = 'new value'
end
specify { expect(subject.payload).to eq(id: 1, blubb: { id: 1, name: 'new value', description: 'old description' }) }
end
end
describe '#initialize' do
subject { instance }
context 'read only attribute' do
specify { expect { subject }.to_not raise_error }
specify { expect(subject.name).to eq('test') }
end
context 'write attribute' do
context 'via rip defined attribute' do
it 'uses the setter' do
expect_any_instance_of(extended_class).to receive(:my_array=)
subject
end
end
context 'self defined attribute' do
it 'uses the setter' do
expect_any_instance_of(extended_class).to receive(:relation=)
subject
end
end
end
context 'unknown params' do
let(:attributes) { { name: 'test42', email: '[email protected]' } }
specify { expect(subject.name).to eq('test42') }
specify { expect { subject.email }.to raise_error(NoMethodError) }
end
context 'not given param' do
let(:attributes) { {} }
specify { expect(subject.name).to eq(nil) }
end
context 'read only param' do
let(:attributes) { { id: 123 } }
specify { expect(subject.id).to eq(123) }
end
end
describe '#update_attributes' do
let(:new_attributes) { { name: 'yoloswag', my_array: ['yoloswag'] } }
subject { instance }
specify do
expect { subject.update_attributes(new_attributes) }.
to change(instance, :my_array).from(attributes[:my_array]).to(new_attributes[:my_array])
end
specify do
expect { subject.update_attributes(new_attributes) }.
to_not change(instance, :name).from(attributes[:name])
end
end
describe '#changed?' do
subject { instance }
context 'a new instance' do
it { is_expected.to be_changed }
end
context 'a modified instance' do
before do
instance.description = 'new value'
end
it { is_expected.to be_changed }
end
context 'a saved instance' do
before do
instance.description = 'new value'
instance.clear_changes
end
it { is_expected.to_not be_changed }
end
end
end
| 27.970588 | 123 | 0.619217 |
edf6d2676831c0af71c41611176da0211b90f17e
| 1,761 |
module Selenium
module WebDriver
module Chrome
# @api private
class Bridge < Remote::Bridge
def initialize(opts = {})
http_client = opts.delete(:http_client)
switches = opts.delete(:switches)
native_events = opts.delete(:native_events)
verbose = opts.delete(:verbose)
unless opts.empty?
raise ArgumentError, "unknown option#{'s' if opts.size != 1}: #{opts.inspect}"
end
caps = Remote::Capabilities.chrome
if switches
unless switches.kind_of? Array
raise ArgumentError, ":switches must be an Array of Strings"
end
caps.merge! 'chrome.switches' => switches.map { |e| e.to_s }
end
caps.merge! 'chrome.binary' => Chrome.path if Chrome.path
caps.merge! 'chrome.nativeEvents' => true if native_events
caps.merge! 'chrome.verbose' => true if verbose
@service = Service.default_service
@service.start
remote_opts = {
:url => @service.uri,
:desired_capabilities => caps
}
remote_opts.merge!(:http_client => http_client) if http_client
super(remote_opts)
end
def browser
:chrome
end
def driver_extensions
[
DriverExtensions::TakesScreenshot,
DriverExtensions::HasInputDevices
]
end
def capabilities
@capabilities ||= Remote::Capabilities.chrome
end
def quit
super
ensure
@service.stop
end
end # Bridge
end # Chrome
end # WebDriver
end # Selenium
| 25.157143 | 90 | 0.54117 |
e8811022bc6c8e53c09c20d68cc3fb0f29098177
| 1,194 |
Pod::Spec.new do |s|
s.name = "CTAssetsPickerController"
s.version = "1.3.0"
s.summary = "iOS control that allows picking multiple photos and videos from user's photo library."
s.description = <<-DESC
CTAssetsPickerController is an iOS controller that allows picking
multiple photos and videos from user's photo library.
The usage and look-and-feel just similar to UIImagePickerController.
It uses **ARC** and requires **AssetsLibrary** framework.
DESC
s.homepage = "https://github.com/chiunam/CTAssetsPickerController"
s.screenshots = "https://raw.github.com/chiunam/CTAssetsPickerController/master/Screenshot.png"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "Clement T" => "[email protected]" }
s.platform = :ios, '6.0'
s.source = { :git => "https://github.com/chiunam/CTAssetsPickerController.git", :tag => "v1.3.0" }
s.source_files = "CTAssetsPickerController/*.{h,m}"
s.resource = "CTAssetsPickerController/Images.xcassets/*/*.png"
s.framework = "AssetsLibrary"
s.requires_arc = true
end
| 49.75 | 106 | 0.631491 |
1caba64cc1cac6bf6ebcd31ab0c0966e23fc79dd
| 2,841 |
class Traefik < Formula
desc "Modern reverse proxy"
homepage "https://traefik.io/"
url "https://github.com/containous/traefik/releases/download/v2.2.3/traefik-v2.2.3.src.tar.gz"
version "2.2.3"
sha256 "2b3af9921d4ef5925999da4627084e692a81275bac7f8338ef8663e797d009d5"
license "MIT"
head "https://github.com/containous/traefik.git"
bottle do
cellar :any_skip_relocation
sha256 "64226109fad17f25d737f7a017bc6b6c4527702039665a821d3d1f86d157f1ed" => :catalina
sha256 "6cdc6c737cc7a69de55ddaaf0898ed0c2dc655210b239dd9602503766e556fbf" => :mojave
sha256 "9a50c613e4bff6713a59183dcc0754ab5ebefa0eb432a7187bb18edbd051872d" => :high_sierra
end
depends_on "go" => :build
depends_on "go-bindata" => :build
def install
system "go", "generate"
system "go", "build",
"-ldflags", "-s -w -X github.com/containous/traefik/v2/pkg/version.Version=#{version}",
"-trimpath", "-o", bin/"traefik", "./cmd/traefik"
prefix.install_metafiles
end
plist_options :manual => "traefik"
def plist
<<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<false/>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_bin}/traefik</string>
<string>--configfile=#{etc/"traefik/traefik.toml"}</string>
</array>
<key>EnvironmentVariables</key>
<dict>
</dict>
<key>RunAtLoad</key>
<true/>
<key>WorkingDirectory</key>
<string>#{var}</string>
<key>StandardErrorPath</key>
<string>#{var}/log/traefik.log</string>
<key>StandardOutPath</key>
<string>#{var}/log/traefik.log</string>
</dict>
</plist>
EOS
end
test do
ui_port = free_port
http_port = free_port
(testpath/"traefik.toml").write <<~EOS
[entryPoints]
[entryPoints.http]
address = ":#{http_port}"
[entryPoints.traefik]
address = ":#{ui_port}"
[api]
insecure = true
dashboard = true
EOS
begin
pid = fork do
exec bin/"traefik", "--configfile=#{testpath}/traefik.toml"
end
sleep 5
cmd_ui = "curl -sIm3 -XGET http://127.0.0.1:#{http_port}/"
assert_match /404 Not Found/m, shell_output(cmd_ui)
sleep 1
cmd_ui = "curl -sIm3 -XGET http://127.0.0.1:#{ui_port}/dashboard/"
assert_match /200 OK/m, shell_output(cmd_ui)
ensure
Process.kill(9, pid)
Process.wait(pid)
end
assert_match version.to_s, shell_output("#{bin}/traefik version 2>&1")
end
end
| 30.223404 | 108 | 0.613164 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.