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
|
---|---|---|---|---|---|
183e6668717bd707ac014b01b94a3c0e1e47f744 | 86 | module React
module Tags
module Rails
VERSION = "3.0.1"
end
end
end
| 10.75 | 23 | 0.593023 |
391469b647f554c8b46abbdbb3138fbaecc4f72b | 444 | class Staff::ChangePasswordForm
include ActiveModel::Model
attr_accessor :object, :current_password, :new_password, :new_password_confirmation
validates :new_password, presence: true, confirmation: true
validate do
errors.add(:current_password, :wrong) unless Staff::Authenticator.new(object).authenticate(current_password)
end
def save
if valid?
object.password = new_password
object.save!
end
end
end
| 24.666667 | 112 | 0.754505 |
7a167aa267d42a8abd0274e6f99982bd460f6fd1 | 799 | class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
protect_from_forgery with: :exception
around_action :set_time_zone
if !Rails.env.development?
rescue_from ActionView::MissingTemplate do |exception|
render file: "public/404.html", status: :not_found, layout: false
end
end
def after_sign_in_path_for(resource)
if resource.admin?
admins_dashboard_path
else
dashboard_path
end
end
private
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:bot_field])
end
def set_time_zone
if current_user && current_user.time_zone.present?
Time.use_zone(current_user.time_zone) { yield }
else
yield
end
end
end
| 23.5 | 72 | 0.740926 |
389fd2e7fbd666e1e27866d89d330fb433b6a8c7 | 484 | # frozen_string_literal: true
describe MarkdownController do
context 'POST' do
before :each do
@input = 'input'
end
let :submit do
post :explanation, params: { preview_input: @input }
end
context 'staff' do
before :each do
when_current_user_is :staff
end
it 'passes preview input parameter through as an instance variable' do
submit
expect(assigns[:preview_input]).to eql @input
end
end
end
end
| 22 | 76 | 0.640496 |
d53561046e8f4dc43723a469f369034201305c0a | 4,104 | # frozen_string_literal: true
require "erb"
require "cgi"
require "fileutils"
require "digest/sha1"
require "time"
# Ensure we are using a compatible version of SimpleCov
major, minor, patch = SimpleCov::VERSION.scan(/\d+/).first(3).map(&:to_i)
if major < 0 || minor < 9 || patch < 0
raise "The version of SimpleCov you are using is too old. "\
"Please update with `gem install simplecov` or `bundle update simplecov`"
end
module SimpleCov
module Formatter
class HTMLFormatter
def format(result)
Dir[File.join(File.dirname(__FILE__), "../public/*")].each do |path|
FileUtils.cp_r(path, asset_output_path)
end
File.open(File.join(output_path, "index.html"), "wb") do |file|
file.puts template("layout").result(binding)
end
puts output_message(result)
end
def output_message(result)
"Coverage report generated for #{result.command_name} to #{output_path}. #{result.covered_lines} / #{result.total_lines} LOC (#{result.covered_percent.round(2)}%) covered."
end
# Check if branchable results supported or not
# Try used here to escape exceptions
def branchable_result?
SimpleCov.branch_coverage?
end
def line_status?(source_file, line)
if branchable_result? && source_file.line_with_missed_branch?(line.number)
"missed-branch"
else
line.status
end
end
private
# Returns the an erb instance for the template of given name
def template(name)
ERB.new(File.read(File.join(File.dirname(__FILE__), "../views/", "#{name}.erb")))
end
def output_path
SimpleCov.coverage_path
end
def asset_output_path
return @asset_output_path if defined?(@asset_output_path) && @asset_output_path
@asset_output_path = File.join(output_path, "assets", SimpleCov::Formatter::HTMLFormatter::VERSION)
FileUtils.mkdir_p(@asset_output_path)
@asset_output_path
end
def assets_path(name)
File.join("./assets", SimpleCov::Formatter::HTMLFormatter::VERSION, name)
end
# Returns the html for the given source_file
def formatted_source_file(source_file)
template("source_file").result(binding)
rescue Encoding::CompatibilityError => e
puts "Encoding problems with file #{source_file.filename}. Simplecov/ERB can't handle non ASCII characters in filenames. Error: #{e.message}."
end
# Returns a table containing the given source files
def formatted_file_list(title, source_files)
title_id = title.gsub(/^[^a-zA-Z]+/, "").gsub(/[^a-zA-Z0-9\-\_]/, "")
# Silence a warning by using the following variable to assign to itself:
# "warning: possibly useless use of a variable in void context"
# The variable is used by ERB via binding.
title_id = title_id
template("file_list").result(binding)
end
def coverage_css_class(covered_percent)
if covered_percent > 90
"green"
elsif covered_percent > 80
"yellow"
else
"red"
end
end
def strength_css_class(covered_strength)
if covered_strength > 1
"green"
elsif covered_strength == 1
"yellow"
else
"red"
end
end
# Return a (kind of) unique id for the source file given. Uses SHA1 on path for the id
def id(source_file)
Digest::SHA1.hexdigest(source_file.filename)
end
def timeago(time)
"<abbr class=\"timeago\" title=\"#{time.iso8601}\">#{time.iso8601}</abbr>"
end
def shortened_filename(source_file)
source_file.filename.sub(SimpleCov.root, ".").gsub(/^\.\//, "")
end
def link_to_source_file(source_file)
%(<a href="##{id source_file}" class="src_link" title="#{shortened_filename source_file}">#{shortened_filename source_file}</a>)
end
end
end
end
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__)))
require "simplecov-html/version"
| 31.569231 | 180 | 0.643762 |
79ea2e2ea47be31b347be6f022dc84a887bc5142 | 1,754 | # frozen_string_literal: true
# This creates and queues reminder emails for in-progress drafts
class WorkReminderGenerator
# Sends the day's reminders about open drafts, using default values for the notification
# interval unless the caller overrides the defaults with custom values. Intended to be run daily
# by a cron job, but the optional manual override for notification interval is useful in case a
# human has to manually call the method to send dropped notifications, e.g. in the event that
# something goes awry with the cron job on a particular day. For example, if the cron job got
# wedged 2 days ago, you could call this method with the the default values plus 2.
# @note Intervals are specified in days.
def self.send_draft_reminders
first_interval = Settings.notifications.first_draft_reminder.first_interval
subsequent_interval = Settings.notifications.first_draft_reminder.subsequent_interval
eligible_works(first_interval, subsequent_interval).each do |state, scope|
scope.find_each do |work_version|
mailer = WorksMailer.with(work_version: work_version)
case state
when :first_draft
mailer.first_draft_reminder_email.deliver_later
when :version_draft
mailer.new_version_reminder_email.deliver_later
end
end
end
end
private_class_method def self.eligible_works(first_interval, subsequent_interval)
%i[first_draft version_draft].index_with do |state|
WorkVersion.with_state(state)
.where('(((CURRENT_DATE - CAST(created_at AS DATE)) - :first_interval) % :subsequent_interval) = 0',
first_interval: first_interval, subsequent_interval: subsequent_interval)
end
end
end
| 46.157895 | 117 | 0.748575 |
28339c6fd30458051d0b871f9c57a69b647e0cd0 | 5,799 | require 'test_helper'
class TagsControllerTest < ActionController::TestCase
include AuthenticatedTestHelper
fixtures :all
def setup
login_as Factory(:user, person: Factory(:person))
end
test 'handles invalid tag id' do
id = 9999
get :show, params: { id: id }
assert_not_nil flash[:error]
assert_redirected_to all_anns_path
end
test 'doesnt try and show cellranges and descriptions' do
p = Factory :person
df = Factory :data_file, policy: Factory(:public_policy)
exp = Factory :expertise, value: 'exp', source: p.user, annotatable: p
Factory :tool, value: exp.value, source: p.user, annotatable: p
Factory :tag, value: exp.value, source: p.user, annotatable: df
cell_range = cell_ranges(:cell_range_1)
Factory :annotation, value: exp.value, source: p.user, annotatable: cell_range
sf = Factory :studied_factor
Factory :annotation, attribute_name: 'description', value: exp.value, source: p.user, annotatable: sf
get :show, params: { id: exp.value }
assert_response :success
assert_select 'div.list_items_container' do
assert_select 'a[href=?]', person_path(p), text: p.name, count: 1
assert_select 'a[href=?]', data_file_path(df), text: df.title, count: 1
end
end
test 'show for sample_type_tag' do
st = Factory(:simple_sample_type, contributor: User.current_user.person, tags: 'fish, peas')
assert_equal 2, st.tags.count
assert st.can_view?
ann = st.annotations.first.value
get :show, params: { id: ann }
assert_response :success
assert objects = assigns(:tagged_objects)
assert_includes objects, st
end
test 'show for expertise tag' do
p = Factory :person
exp = Factory :expertise, value: 'golf', source: p.user, annotatable: p
get :show, params: { id: exp.value }
assert_response :success
assert_select 'div#notice_flash', text: /1 item tagged with 'golf'/, count: 1
assert_select 'div.list_items_container' do
assert_select 'a[href=?]', person_path(p), text: p.name, count: 1
end
end
test 'show for tools tag' do
p = Factory :person
tool = Factory :tool, value: 'spade', source: p.user, annotatable: p
get :show, params: { id: tool.value }
assert_response :success
assert_select 'div.list_items_container' do
assert_select 'a[href=?]', person_path(p), text: p.name, count: 1
end
end
test 'show for general tag' do
df = Factory :data_file, policy: Factory(:public_policy)
private_df = Factory :data_file, policy: Factory(:private_policy)
tag = Factory :tag, value: 'a tag', source: User.current_user, annotatable: df
get :show, params: { id: tag.value }
assert_response :success
assert_select 'div.list_items_container' do
assert_select 'a', text: df.title, count: 1
assert_select 'a', text: private_df.title, count: 0
end
end
test 'index' do
p = Factory :person
df = Factory :data_file, contributor: p
df2 = Factory :data_file, contributor: p
p2 = Factory :person
tool = Factory :tool, value: 'fork', source: p.user, annotatable: p
exp = Factory :expertise, value: 'fishing', source: p.user, annotatable: p
tag = Factory :tag, value: 'twinkle', source: p.user, annotatable: df
# to make sure tags only appear once
tag2 = Factory :tag, value: tag.value, source: p2.user, annotatable: df2
# to make sure only tools, tags and expertise are included
bogus = Factory :tag, value: 'frog', source: p.user, annotatable: df, attribute_name: 'bogus'
login_as p.user
get :index
assert_response :success
assert_select 'div#super_tag_cloud a[href=?]', show_ann_path(tag.value), text: 'twinkle', count: 1
assert_select 'div#super_tag_cloud a[href=?]', show_ann_path(tool.value), text: 'fork', count: 1
assert_select 'div#super_tag_cloud a[href=?]', show_ann_path(exp.value), text: 'fishing', count: 1
# this shouldn't show up because its not a tag,tool or expertise attribute
assert_select 'div#super_tag_cloud a[href=?]', show_ann_path(bogus.value), text: 'frog', count: 0
end
test 'dont show duplicates for same tag for expertise and tools' do
p = Factory :person
tool = Factory :tool, value: 'xxxxx', source: p.user, annotatable: p
exp = Factory :expertise, value: 'xxxxx', source: p.user, annotatable: p
login_as p.user
get :index
assert_response :success
get :show, params: { id: tool.value }
assert_response :success
assert_select 'div.list_items_container' do
assert_select 'a', text: p.name, count: 1
end
end
test 'latest with no attributes defined' do
AnnotationAttribute.destroy_all
assert_empty AnnotationAttribute.all
get :latest, format: 'json'
assert_response :success
assert_empty JSON.parse(@response.body)
end
test 'latest' do
p = Factory :person
df = Factory :data_file, contributor: p
tag = Factory :tag, value: 'twinkle', source: p.user, annotatable: df
get :latest, format: 'json'
assert_response :success
assert_includes JSON.parse(@response.body), 'twinkle'
end
test 'can query' do
p = Factory :person
df = Factory :data_file, contributor: p
tag = Factory :tag, value: 'twinkle', source: p.user, annotatable: df
get :query, params: { format: 'json', query: 'twi' }
assert_response :success
assert_includes JSON.parse(@response.body), 'twinkle'
end
test 'can handle empty response from query' do
p = Factory :person
df = Factory :data_file, contributor: p
tag = Factory :tag, value: 'twinkle', source: p.user, annotatable: df
get :query, params: { format: 'json', query: 'zzzxxxyyyqqq' }
assert_response :success
assert_empty JSON.parse(@response.body)
end
end
| 33.327586 | 105 | 0.685635 |
1d9607955d8550ad16a05074e8b50aeb815324eb | 1,166 | module ElasticsearchDslBuilder
module DSL
module Search
module Queries
class HasChild < Query
def initialize(child_type = nil)
@type = :has_child
child_type(child_type)
super()
end
def child_type(child_type)
raise ArgumentError, 'child_type must be a String' unless child_type.instance_of?(String)
@child_type = child_type
self
end
def query(query)
raise ArgumentError, 'query must extend type Queries::Query' unless query.is_a?(Query)
@nested_query = query.to_hash
self
end
def inner_hits(inner_hits)
raise ArgumentError, 'inner_hits must be an InnerHits object' unless inner_hits.instance_of?(InnerHits)
@inner_hits = inner_hits.to_hash
self
end
def to_hash
@query = { type: @child_type }
@query.update(query: @nested_query) if @nested_query
@query.update(inner_hits: @inner_hits) if @inner_hits
super
end
end
end
end
end
end
| 27.116279 | 115 | 0.571184 |
ed260bf96ec9e44d37b9a6189fd10e2d4b3b8fd5 | 1,698 | Rails.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
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure static asset server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = "{ '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
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
| 42.45 | 85 | 0.773263 |
5d4da564a3f81aaf43c68ba981791a15b30f2be4 | 766 | class Cms::LayoutsController < ApplicationController
include Cms::BaseFilter
include Cms::CrudFilter
model Cms::Layout
navi_view "cms/main/navi"
before_action :set_tree_navi, only: [:index]
private
def set_crumbs
@crumbs << [t("cms.layout"), action: :index]
end
def fix_params
{ cur_user: @cur_user, cur_site: @cur_site, cur_node: false }
end
public
def index
raise "403" unless @model.allowed?(:read, @cur_user, site: @cur_site, node: @cur_node)
@node_target_options = @model.new.node_target_options
@items = @model.site(@cur_site).
node(@cur_node, params.dig(:s, :target)).
allow(:read, @cur_user).
search(params[:s]).
order_by(filename: 1).
page(params[:page]).per(50)
end
end
| 21.277778 | 90 | 0.665796 |
39e4a6cf5b69012cc09ca15a017fdf7ccddf637e | 335 | class CreatePayments < ActiveRecord::Migration[5.2]
def change
create_table :payments do |t|
t.string :payer_id
t.string :recipient_id
t.string :organization_id
t.integer :conversation_id
t.integer :sum_cents
t.string :sum_currency
t.string :status
t.timestamps
end
end
end
| 20.9375 | 51 | 0.662687 |
08319f6a3cbf55b6fa9750f7de963268c6c6ede4 | 10,861 | # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
require 'date'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# Updates the configuration details of a custom protection rule. Custom protection rules can only be updated if they are not active in a WAAS policy.
# **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.
class Waas::Models::UpdateCustomProtectionRuleDetails
# A user-friendly name for the custom protection rule.
# @return [String]
attr_accessor :display_name
# A description for the custom protection rule.
# @return [String]
attr_accessor :description
# The template text of the custom protection rule. All custom protection rules are expressed in ModSecurity Rule Language.
#
# Additionally, each rule must include two placeholder variables that are updated by the WAF service upon publication of the rule.
#
# `id: {{id_1}}` - This field is populated with a unique rule ID generated by the WAF service which identifies a `SecRule`. More than one `SecRule` can be defined in the `template` field of a CreateCustomSecurityRule call. The value of the first `SecRule` must be `id: {{id_1}}` and the `id` field of each subsequent `SecRule` should increase by one, as shown in the example.
#
# `ctl:ruleEngine={{mode}}` - The action to be taken when the criteria of the `SecRule` are met, either `OFF`, `DETECT` or `BLOCK`. This field is automatically populated with the corresponding value of the `action` field of the `CustomProtectionRuleSetting` schema when the `WafConfig` is updated.
#
# *Example:*
# ```
# SecRule REQUEST_COOKIES \"regex matching SQL injection - part 1/2\" \\
# \"phase:2, \\
# msg:'Detects chained SQL injection attempts 1/2.', \\
# id: {{id_1}}, \\
# ctl:ruleEngine={{mode}}, \\
# deny\"
# SecRule REQUEST_COOKIES \"regex matching SQL injection - part 2/2\" \\
# \"phase:2, \\
# msg:'Detects chained SQL injection attempts 2/2.', \\
# id: {{id_2}}, \\
# ctl:ruleEngine={{mode}}, \\
# deny\"
# ```
#
#
# The example contains two `SecRules` each having distinct regex expression to match the `Cookie` header value during the second input analysis phase.
#
# For more information about custom protection rules, see [Custom Protection Rules](https://docs.cloud.oracle.com/Content/WAF/tasks/customprotectionrules.htm).
#
# For more information about ModSecurity syntax, see [Making Rules: The Basic Syntax](https://www.modsecurity.org/CRS/Documentation/making.html).
#
# For more information about ModSecurity's open source WAF rules, see [Mod Security's OWASP Core Rule Set documentation](https://www.modsecurity.org/CRS/Documentation/index.html).
# @return [String]
attr_accessor :template
# Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace.
# For more information, see [Resource Tags](https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm).
#
# Example: `{\"Department\": \"Finance\"}`
#
# @return [Hash<String, String>]
attr_accessor :freeform_tags
# Defined tags for this resource. Each key is predefined and scoped to a namespace.
# For more information, see [Resource Tags](https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm).
#
# Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`
#
# @return [Hash<String, Hash<String, Object>>]
attr_accessor :defined_tags
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'display_name': :'displayName',
'description': :'description',
'template': :'template',
'freeform_tags': :'freeformTags',
'defined_tags': :'definedTags'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'display_name': :'String',
'description': :'String',
'template': :'String',
'freeform_tags': :'Hash<String, String>',
'defined_tags': :'Hash<String, Hash<String, Object>>'
# rubocop:enable Style/SymbolLiteral
}
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
# @option attributes [String] :display_name The value to assign to the {#display_name} property
# @option attributes [String] :description The value to assign to the {#description} property
# @option attributes [String] :template The value to assign to the {#template} property
# @option attributes [Hash<String, String>] :freeform_tags The value to assign to the {#freeform_tags} property
# @option attributes [Hash<String, Hash<String, Object>>] :defined_tags The value to assign to the {#defined_tags} property
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
self.display_name = attributes[:'displayName'] if attributes[:'displayName']
raise 'You cannot provide both :displayName and :display_name' if attributes.key?(:'displayName') && attributes.key?(:'display_name')
self.display_name = attributes[:'display_name'] if attributes[:'display_name']
self.description = attributes[:'description'] if attributes[:'description']
self.template = attributes[:'template'] if attributes[:'template']
self.freeform_tags = attributes[:'freeformTags'] if attributes[:'freeformTags']
raise 'You cannot provide both :freeformTags and :freeform_tags' if attributes.key?(:'freeformTags') && attributes.key?(:'freeform_tags')
self.freeform_tags = attributes[:'freeform_tags'] if attributes[:'freeform_tags']
self.defined_tags = attributes[:'definedTags'] if attributes[:'definedTags']
raise 'You cannot provide both :definedTags and :defined_tags' if attributes.key?(:'definedTags') && attributes.key?(:'defined_tags')
self.defined_tags = attributes[:'defined_tags'] if attributes[:'defined_tags']
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# Checks equality by comparing each attribute.
# @param [Object] other the other object to be compared
def ==(other)
return true if equal?(other)
self.class == other.class &&
display_name == other.display_name &&
description == other.description &&
template == other.template &&
freeform_tags == other.freeform_tags &&
defined_tags == other.defined_tags
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# @see the `==` method
# @param [Object] other the other object to be compared
def eql?(other)
self == other
end
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[display_name, description, template, freeform_tags, defined_tags].hash
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
public_method("#{key}=").call(
attributes[self.class.attribute_map[key]]
.map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) }
)
end
elsif !attributes[self.class.attribute_map[key]].nil?
public_method("#{key}=").call(
OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]])
)
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = public_method(attr).call
next if value.nil? && !instance_variable_defined?("@#{attr}")
hash[param] = _to_hash(value)
end
hash
end
private
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 44.695473 | 379 | 0.66016 |
1cd1eb6438f8529ed060f073a7bb7ddcb1f08029 | 25,355 | class Array
##
# call-seq:
# ary.uniq! -> ary or nil
# ary.uniq! { |item| ... } -> ary or nil
#
# Removes duplicate elements from +self+.
# Returns <code>nil</code> if no changes are made (that is, no
# duplicates are found).
#
# a = [ "a", "a", "b", "b", "c" ]
# a.uniq! #=> ["a", "b", "c"]
# b = [ "a", "b", "c" ]
# b.uniq! #=> nil
# c = [["student","sam"], ["student","george"], ["teacher","matz"]]
# c.uniq! { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
#
def uniq!(&block)
hash = {}
if block
self.each do |val|
key = block.call(val)
hash[key] = val unless hash.key?(key)
end
result = hash.values
else
hash = {}
self.each do |val|
hash[val] = val
end
result = hash.keys
end
if result.size == self.size
nil
else
self.replace(result)
end
end
##
# call-seq:
# ary.uniq -> new_ary
# ary.uniq { |item| ... } -> new_ary
#
# Returns a new array by removing duplicate values in +self+.
#
# a = [ "a", "a", "b", "b", "c" ]
# a.uniq #=> ["a", "b", "c"]
#
# b = [["student","sam"], ["student","george"], ["teacher","matz"]]
# b.uniq { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
#
def uniq(&block)
ary = self.dup
ary.uniq!(&block)
ary
end
##
# call-seq:
# ary - other_ary -> new_ary
#
# Array Difference---Returns a new array that is a copy of
# the original array, removing any items that also appear in
# <i>other_ary</i>. (If you need set-like behavior, see the
# library class Set.)
#
# [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #=> [ 3, 3, 5 ]
#
def -(elem)
raise TypeError, "can't convert #{elem.class} into Array" unless elem.class == Array
hash = {}
array = []
idx = 0
len = elem.size
while idx < len
hash[elem[idx]] = true
idx += 1
end
idx = 0
len = size
while idx < len
v = self[idx]
array << v unless hash[v]
idx += 1
end
array
end
##
# call-seq:
# ary | other_ary -> new_ary
#
# Set Union---Returns a new array by joining this array with
# <i>other_ary</i>, removing duplicates.
#
# [ "a", "b", "c" ] | [ "c", "d", "a" ]
# #=> [ "a", "b", "c", "d" ]
#
def |(elem)
raise TypeError, "can't convert #{elem.class} into Array" unless elem.class == Array
ary = self + elem
ary.uniq! or ary
end
##
# call-seq:
# ary.union(other_ary,...) -> new_ary
#
# Set Union---Returns a new array by joining this array with
# <i>other_ary</i>, removing duplicates.
#
# ["a", "b", "c"].union(["c", "d", "a"], ["a", "c", "e"])
# #=> ["a", "b", "c", "d", "e"]
#
def union(*args)
ary = self.dup
args.each do |x|
ary.concat(x)
ary.uniq!
end
ary
end
##
# call-seq:
# ary & other_ary -> new_ary
#
# Set Intersection---Returns a new array
# containing elements common to the two arrays, with no duplicates.
#
# [ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ]
#
def &(elem)
raise TypeError, "can't convert #{elem.class} into Array" unless elem.class == Array
hash = {}
array = []
idx = 0
len = elem.size
while idx < len
hash[elem[idx]] = true
idx += 1
end
idx = 0
len = size
while idx < len
v = self[idx]
if hash[v]
array << v
hash.delete v
end
idx += 1
end
array
end
##
# call-seq:
# ary.flatten -> new_ary
# ary.flatten(level) -> new_ary
#
# Returns a new array that is a one-dimensional flattening of this
# array (recursively). That is, for every element that is an array,
# extract its elements into the new array. If the optional
# <i>level</i> argument determines the level of recursion to flatten.
#
# s = [ 1, 2, 3 ] #=> [1, 2, 3]
# t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]]
# a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
# a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# a = [ 1, 2, [3, [4, 5] ] ]
# a.flatten(1) #=> [1, 2, 3, [4, 5]]
#
def flatten(depth=nil)
res = dup
res.flatten! depth
res
end
##
# call-seq:
# ary.flatten! -> ary or nil
# ary.flatten!(level) -> array or nil
#
# Flattens +self+ in place.
# Returns <code>nil</code> if no modifications were made (i.e.,
# <i>ary</i> contains no subarrays.) If the optional <i>level</i>
# argument determines the level of recursion to flatten.
#
# a = [ 1, 2, [3, [4, 5] ] ]
# a.flatten! #=> [1, 2, 3, 4, 5]
# a.flatten! #=> nil
# a #=> [1, 2, 3, 4, 5]
# a = [ 1, 2, [3, [4, 5] ] ]
# a.flatten!(1) #=> [1, 2, 3, [4, 5]]
#
def flatten!(depth=nil)
modified = false
ar = []
idx = 0
len = size
while idx < len
e = self[idx]
if e.is_a?(Array) && (depth.nil? || depth > 0)
ar += e.flatten(depth.nil? ? nil : depth - 1)
modified = true
else
ar << e
end
idx += 1
end
if modified
self.replace(ar)
else
nil
end
end
##
# call-seq:
# ary.compact -> new_ary
#
# Returns a copy of +self+ with all +nil+ elements removed.
#
# [ "a", nil, "b", nil, "c", nil ].compact
# #=> [ "a", "b", "c" ]
#
def compact
result = self.dup
result.compact!
result
end
##
# call-seq:
# ary.compact! -> ary or nil
#
# Removes +nil+ elements from the array.
# Returns +nil+ if no changes were made, otherwise returns
# <i>ary</i>.
#
# [ "a", nil, "b", nil, "c" ].compact! #=> [ "a", "b", "c" ]
# [ "a", "b", "c" ].compact! #=> nil
#
def compact!
result = self.select { |e| !e.nil? }
if result.size == self.size
nil
else
self.replace(result)
end
end
# for efficiency
def reverse_each(&block)
return to_enum :reverse_each unless block
i = self.size - 1
while i>=0
block.call(self[i])
i -= 1
end
self
end
##
# call-seq:
# ary.fetch(index) -> obj
# ary.fetch(index, default) -> obj
# ary.fetch(index) { |index| block } -> obj
#
# Tries to return the element at position +index+, but throws an IndexError
# exception if the referenced +index+ lies outside of the array bounds. This
# error can be prevented by supplying a second argument, which will act as a
# +default+ value.
#
# Alternatively, if a block is given it will only be executed when an
# invalid +index+ is referenced.
#
# Negative values of +index+ count from the end of the array.
#
# a = [ 11, 22, 33, 44 ]
# a.fetch(1) #=> 22
# a.fetch(-1) #=> 44
# a.fetch(4, 'cat') #=> "cat"
# a.fetch(100) { |i| puts "#{i} is out of bounds" }
# #=> "100 is out of bounds"
#
def fetch(n, ifnone=NONE, &block)
warn "block supersedes default value argument" if !n.nil? && ifnone != NONE && block
idx = n
if idx < 0
idx += size
end
if idx < 0 || size <= idx
return block.call(n) if block
if ifnone == NONE
raise IndexError, "index #{n} outside of array bounds: #{-size}...#{size}"
end
return ifnone
end
self[idx]
end
##
# call-seq:
# ary.fill(obj) -> ary
# ary.fill(obj, start [, length]) -> ary
# ary.fill(obj, range ) -> ary
# ary.fill { |index| block } -> ary
# ary.fill(start [, length] ) { |index| block } -> ary
# ary.fill(range) { |index| block } -> ary
#
# The first three forms set the selected elements of +self+ (which
# may be the entire array) to +obj+.
#
# A +start+ of +nil+ is equivalent to zero.
#
# A +length+ of +nil+ is equivalent to the length of the array.
#
# The last three forms fill the array with the value of the given block,
# which is passed the absolute index of each element to be filled.
#
# Negative values of +start+ count from the end of the array, where +-1+ is
# the last element.
#
# a = [ "a", "b", "c", "d" ]
# a.fill("x") #=> ["x", "x", "x", "x"]
# a.fill("w", -1) #=> ["x", "x", "x", "w"]
# a.fill("z", 2, 2) #=> ["x", "x", "z", "z"]
# a.fill("y", 0..1) #=> ["y", "y", "z", "z"]
# a.fill { |i| i*i } #=> [0, 1, 4, 9]
# a.fill(-2) { |i| i*i*i } #=> [0, 1, 8, 27]
# a.fill(1, 2) { |i| i+1 } #=> [0, 2, 3, 27]
# a.fill(0..1) { |i| i+1 } #=> [1, 2, 3, 27]
#
def fill(arg0=nil, arg1=nil, arg2=nil, &block)
if arg0.nil? && arg1.nil? && arg2.nil? && !block
raise ArgumentError, "wrong number of arguments (0 for 1..3)"
end
beg = len = 0
ary = []
if block
if arg0.nil? && arg1.nil? && arg2.nil?
# ary.fill { |index| block } -> ary
beg = 0
len = self.size
elsif !arg0.nil? && arg0.kind_of?(Range)
# ary.fill(range) { |index| block } -> ary
beg = arg0.begin
beg += self.size if beg < 0
len = arg0.end
len += self.size if len < 0
len += 1 unless arg0.exclude_end?
elsif !arg0.nil?
# ary.fill(start [, length] ) { |index| block } -> ary
beg = arg0
beg += self.size if beg < 0
if arg1.nil?
len = self.size
else
len = arg0 + arg1
end
end
else
if !arg0.nil? && arg1.nil? && arg2.nil?
# ary.fill(obj) -> ary
beg = 0
len = self.size
elsif !arg0.nil? && !arg1.nil? && arg1.kind_of?(Range)
# ary.fill(obj, range ) -> ary
beg = arg1.begin
beg += self.size if beg < 0
len = arg1.end
len += self.size if len < 0
len += 1 unless arg1.exclude_end?
elsif !arg0.nil? && !arg1.nil?
# ary.fill(obj, start [, length]) -> ary
beg = arg1
beg += self.size if beg < 0
if arg2.nil?
len = self.size
else
len = beg + arg2
end
end
end
i = beg
if block
while i < len
self[i] = block.call(i)
i += 1
end
else
while i < len
self[i] = arg0
i += 1
end
end
self
end
##
# call-seq:
# ary.rotate(count=1) -> new_ary
#
# Returns a new array by rotating +self+ so that the element at +count+ is
# the first element of the new array.
#
# If +count+ is negative then it rotates in the opposite direction, starting
# from the end of +self+ where +-1+ is the last element.
#
# a = [ "a", "b", "c", "d" ]
# a.rotate #=> ["b", "c", "d", "a"]
# a #=> ["a", "b", "c", "d"]
# a.rotate(2) #=> ["c", "d", "a", "b"]
# a.rotate(-3) #=> ["b", "c", "d", "a"]
def rotate(count=1)
ary = []
len = self.length
if len > 0
idx = (count < 0) ? (len - (~count % len) - 1) : (count % len) # rotate count
len.times do
ary << self[idx]
idx += 1
idx = 0 if idx > len-1
end
end
ary
end
##
# call-seq:
# ary.rotate!(count=1) -> ary
#
# Rotates +self+ in place so that the element at +count+ comes first, and
# returns +self+.
#
# If +count+ is negative then it rotates in the opposite direction, starting
# from the end of the array where +-1+ is the last element.
#
# a = [ "a", "b", "c", "d" ]
# a.rotate! #=> ["b", "c", "d", "a"]
# a #=> ["b", "c", "d", "a"]
# a.rotate!(2) #=> ["d", "a", "b", "c"]
# a.rotate!(-3) #=> ["a", "b", "c", "d"]
def rotate!(count=1)
self.replace(self.rotate(count))
end
##
# call-seq:
# ary.delete_if { |item| block } -> ary
# ary.delete_if -> Enumerator
#
# Deletes every element of +self+ for which block evaluates to +true+.
#
# The array is changed instantly every time the block is called, not after
# the iteration is over.
#
# See also Array#reject!
#
# If no block is given, an Enumerator is returned instead.
#
# scores = [ 97, 42, 75 ]
# scores.delete_if {|score| score < 80 } #=> [97]
def delete_if(&block)
return to_enum :delete_if unless block
idx = 0
while idx < self.size do
if block.call(self[idx])
self.delete_at(idx)
else
idx += 1
end
end
self
end
##
# call-seq:
# ary.reject! { |item| block } -> ary or nil
# ary.reject! -> Enumerator
#
# Equivalent to Array#delete_if, deleting elements from +self+ for which the
# block evaluates to +true+, but returns +nil+ if no changes were made.
#
# The array is changed instantly every time the block is called, not after
# the iteration is over.
#
# See also Enumerable#reject and Array#delete_if.
#
# If no block is given, an Enumerator is returned instead.
def reject!(&block)
return to_enum :reject! unless block
len = self.size
idx = 0
while idx < self.size do
if block.call(self[idx])
self.delete_at(idx)
else
idx += 1
end
end
if self.size == len
nil
else
self
end
end
##
# call-seq:
# ary.insert(index, obj...) -> ary
#
# Inserts the given values before the element with the given +index+.
#
# Negative indices count backwards from the end of the array, where +-1+ is
# the last element.
#
# a = %w{ a b c d }
# a.insert(2, 99) #=> ["a", "b", 99, "c", "d"]
# a.insert(-2, 1, 2, 3) #=> ["a", "b", 99, "c", 1, 2, 3, "d"]
def insert(idx, *args)
idx += self.size + 1 if idx < 0
self[idx, 0] = args
self
end
##
# call-seq:
# ary.bsearch {|x| block } -> elem
#
# By using binary search, finds a value from this array which meets
# the given condition in O(log n) where n is the size of the array.
#
# You can use this method in two use cases: a find-minimum mode and
# a find-any mode. In either case, the elements of the array must be
# monotone (or sorted) with respect to the block.
#
# In find-minimum mode (this is a good choice for typical use case),
# the block must return true or false, and there must be an index i
# (0 <= i <= ary.size) so that:
#
# - the block returns false for any element whose index is less than
# i, and
# - the block returns true for any element whose index is greater
# than or equal to i.
#
# This method returns the i-th element. If i is equal to ary.size,
# it returns nil.
#
# ary = [0, 4, 7, 10, 12]
# ary.bsearch {|x| x >= 4 } #=> 4
# ary.bsearch {|x| x >= 6 } #=> 7
# ary.bsearch {|x| x >= -1 } #=> 0
# ary.bsearch {|x| x >= 100 } #=> nil
#
# In find-any mode (this behaves like libc's bsearch(3)), the block
# must return a number, and there must be two indices i and j
# (0 <= i <= j <= ary.size) so that:
#
# - the block returns a positive number for ary[k] if 0 <= k < i,
# - the block returns zero for ary[k] if i <= k < j, and
# - the block returns a negative number for ary[k] if
# j <= k < ary.size.
#
# Under this condition, this method returns any element whose index
# is within i...j. If i is equal to j (i.e., there is no element
# that satisfies the block), this method returns nil.
#
# ary = [0, 4, 7, 10, 12]
# # try to find v such that 4 <= v < 8
# ary.bsearch {|x| 1 - (x / 4).truncate } #=> 4 or 7
# # try to find v such that 8 <= v < 10
# ary.bsearch {|x| 4 - (x / 2).truncate } #=> nil
#
# You must not mix the two modes at a time; the block must always
# return either true/false, or always return a number. It is
# undefined which value is actually picked up at each iteration.
def bsearch(&block)
return to_enum :bsearch unless block
if idx = bsearch_index(&block)
self[idx]
else
nil
end
end
##
# call-seq:
# ary.bsearch_index {|x| block } -> int or nil
#
# By using binary search, finds an index of a value from this array which
# meets the given condition in O(log n) where n is the size of the array.
#
# It supports two modes, depending on the nature of the block and they are
# exactly the same as in the case of #bsearch method with the only difference
# being that this method returns the index of the element instead of the
# element itself. For more details consult the documentation for #bsearch.
def bsearch_index(&block)
return to_enum :bsearch_index unless block
low = 0
high = size
satisfied = false
while low < high
mid = ((low+high)/2).truncate
res = block.call self[mid]
case res
when 0 # find-any mode: Found!
return mid
when Numeric # find-any mode: Continue...
in_lower_half = res < 0
when true # find-min mode
in_lower_half = true
satisfied = true
when false, nil # find-min mode
in_lower_half = false
else
raise TypeError, 'invalid block result (must be numeric, true, false or nil)'
end
if in_lower_half
high = mid
else
low = mid + 1
end
end
satisfied ? low : nil
end
##
# call-seq:
# ary.delete_if { |item| block } -> ary
# ary.delete_if -> Enumerator
#
# Deletes every element of +self+ for which block evaluates to +true+.
#
# The array is changed instantly every time the block is called, not after
# the iteration is over.
#
# See also Array#reject!
#
# If no block is given, an Enumerator is returned instead.
#
# scores = [ 97, 42, 75 ]
# scores.delete_if {|score| score < 80 } #=> [97]
def delete_if(&block)
return to_enum :delete_if unless block
idx = 0
while idx < self.size do
if block.call(self[idx])
self.delete_at(idx)
else
idx += 1
end
end
self
end
##
# call-seq:
# ary.keep_if { |item| block } -> ary
# ary.keep_if -> Enumerator
#
# Deletes every element of +self+ for which the given block evaluates to
# +false+.
#
# See also Array#select!
#
# If no block is given, an Enumerator is returned instead.
#
# a = [1, 2, 3, 4, 5]
# a.keep_if { |val| val > 3 } #=> [4, 5]
def keep_if(&block)
return to_enum :keep_if unless block
idx = 0
len = self.size
while idx < self.size do
if block.call(self[idx])
idx += 1
else
self.delete_at(idx)
end
end
self
end
##
# call-seq:
# ary.select! {|item| block } -> ary or nil
# ary.select! -> Enumerator
#
# Invokes the given block passing in successive elements from +self+,
# deleting elements for which the block returns a +false+ value.
#
# If changes were made, it will return +self+, otherwise it returns +nil+.
#
# See also Array#keep_if
#
# If no block is given, an Enumerator is returned instead.
def select!(&block)
return to_enum :select! unless block
result = []
idx = 0
len = size
while idx < len
elem = self[idx]
result << elem if block.call(elem)
idx += 1
end
return nil if len == result.size
self.replace(result)
end
##
# call-seq:
# ary.index(val) -> int or nil
# ary.index {|item| block } -> int or nil
#
# Returns the _index_ of the first object in +ary+ such that the object is
# <code>==</code> to +obj+.
#
# If a block is given instead of an argument, returns the _index_ of the
# first object for which the block returns +true+. Returns +nil+ if no
# match is found.
#
# ISO 15.2.12.5.14
def index(val=NONE, &block)
return to_enum(:find_index, val) if !block && val == NONE
if block
idx = 0
len = size
while idx < len
return idx if block.call self[idx]
idx += 1
end
else
return self.__ary_index(val)
end
nil
end
##
# call-seq:
# ary.dig(idx, ...) -> object
#
# Extracts the nested value specified by the sequence of <i>idx</i>
# objects by calling +dig+ at each step, returning +nil+ if any
# intermediate step is +nil+.
#
def dig(idx,*args)
n = self[idx]
if args.size > 0
n&.dig(*args)
else
n
end
end
##
# call-seq:
# ary.permutation { |p| block } -> ary
# ary.permutation -> Enumerator
# ary.permutation(n) { |p| block } -> ary
# ary.permutation(n) -> Enumerator
#
# When invoked with a block, yield all permutations of length +n+ of the
# elements of the array, then return the array itself.
#
# If +n+ is not specified, yield all permutations of all elements.
#
# The implementation makes no guarantees about the order in which the
# permutations are yielded.
#
# If no block is given, an Enumerator is returned instead.
#
# Examples:
#
# a = [1, 2, 3]
# a.permutation.to_a #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
# a.permutation(1).to_a #=> [[1],[2],[3]]
# a.permutation(2).to_a #=> [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]
# a.permutation(3).to_a #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
# a.permutation(0).to_a #=> [[]] # one permutation of length 0
# a.permutation(4).to_a #=> [] # no permutations of length 4
def permutation(n=self.size, &block)
size = self.size
return to_enum(:permutation, n) unless block
return if n > size
if n == 0
yield []
else
i = 0
while i<size
result = [self[i]]
if n-1 > 0
ary = self[0...i] + self[i+1..-1]
ary.permutation(n-1) do |c|
yield result + c
end
else
yield result
end
i += 1
end
end
end
##
# call-seq:
# ary.combination(n) { |c| block } -> ary
# ary.combination(n) -> Enumerator
#
# When invoked with a block, yields all combinations of length +n+ of elements
# from the array and then returns the array itself.
#
# The implementation makes no guarantees about the order in which the
# combinations are yielded.
#
# If no block is given, an Enumerator is returned instead.
#
# Examples:
#
# a = [1, 2, 3, 4]
# a.combination(1).to_a #=> [[1],[2],[3],[4]]
# a.combination(2).to_a #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
# a.combination(3).to_a #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
# a.combination(4).to_a #=> [[1,2,3,4]]
# a.combination(0).to_a #=> [[]] # one combination of length 0
# a.combination(5).to_a #=> [] # no combinations of length 5
def combination(n, &block)
size = self.size
return to_enum(:combination, n) unless block
return if n > size
if n == 0
yield []
elsif n == 1
i = 0
while i<size
yield [self[i]]
i += 1
end
else
i = 0
while i<size
result = [self[i]]
self[i+1..-1].combination(n-1) do |c|
yield result + c
end
i += 1
end
end
end
##
# call-seq:
# ary.transpose -> new_ary
#
# Assumes that self is an array of arrays and transposes the rows and columns.
#
# If the length of the subarrays don't match, an IndexError is raised.
#
# Examples:
#
# a = [[1,2], [3,4], [5,6]]
# a.transpose #=> [[1, 3, 5], [2, 4, 6]]
def transpose
return [] if empty?
column_count = nil
self.each do |row|
raise TypeError unless row.is_a?(Array)
column_count ||= row.size
raise IndexError, 'element size differs' unless column_count == row.size
end
Array.new(column_count) do |column_index|
self.map { |row| row[column_index] }
end
end
##
# call-seq:
# ary.to_h -> Hash
# ary.to_h{|item| ... } -> Hash
#
# Returns the result of interpreting <i>aray</i> as an array of
# <tt>[key, value]</tt> pairs. If a block is given, it should
# return <tt>[key, value]</tt> pairs to construct a hash.
#
# [[:foo, :bar], [1, 2]].to_h
# # => {:foo => :bar, 1 => 2}
# [1, 2].to_h{|x| [x, x*2]}
# # => {1 => 2, 2 => 4}
#
def to_h(&blk)
h = {}
self.each do |v|
v = blk.call(v) if blk
raise TypeError, "wrong element type #{v.class}" unless Array === v
raise ArgumentError, "wrong array length (expected 2, was #{v.length})" unless v.length == 2
h[v[0]] = v[1]
end
h
end
alias append push
alias prepend unshift
end
| 26.887593 | 98 | 0.516348 |
339a8f6a98f306963c85c563ba76b13ec09a4cc8 | 2,687 | cask 'wine-staging' do
version '4.9'
sha256 'd51f6d2ef7fb9cb263b3f2384e7feca49e3f3d763e35881205ff957370092f22'
# dl.winehq.org/wine-builds/macosx was verified as official when first introduced to the cask
url "https://dl.winehq.org/wine-builds/macosx/pool/winehq-staging-#{version}.pkg"
appcast 'https://dl.winehq.org/wine-builds/macosx/download.html'
name 'WineHQ-staging'
homepage 'https://www.wine-staging.com/'
conflicts_with formula: 'wine',
cask: [
'wine-stable',
'wine-devel',
]
depends_on x11: true
pkg "winehq-staging-#{version}.pkg",
choices: [
{
'choiceIdentifier' => 'choice3',
'choiceAttribute' => 'selected',
'attributeSetting' => 1,
},
]
binary "#{appdir}/Wine Staging.app/Contents/Resources/start/bin/appdb"
binary "#{appdir}/Wine Staging.app/Contents/Resources/start/bin/winehelp"
binary "#{appdir}/Wine Staging.app/Contents/Resources/wine/bin/msiexec"
binary "#{appdir}/Wine Staging.app/Contents/Resources/wine/bin/notepad"
binary "#{appdir}/Wine Staging.app/Contents/Resources/wine/bin/regedit"
binary "#{appdir}/Wine Staging.app/Contents/Resources/wine/bin/regsvr32"
binary "#{appdir}/Wine Staging.app/Contents/Resources/wine/bin/wine"
binary "#{appdir}/Wine Staging.app/Contents/Resources/wine/bin/wine64"
binary "#{appdir}/Wine Staging.app/Contents/Resources/wine/bin/wineboot"
binary "#{appdir}/Wine Staging.app/Contents/Resources/wine/bin/winecfg"
binary "#{appdir}/Wine Staging.app/Contents/Resources/wine/bin/wineconsole"
binary "#{appdir}/Wine Staging.app/Contents/Resources/wine/bin/winedbg"
binary "#{appdir}/Wine Staging.app/Contents/Resources/wine/bin/winefile"
binary "#{appdir}/Wine Staging.app/Contents/Resources/wine/bin/winemine"
binary "#{appdir}/Wine Staging.app/Contents/Resources/wine/bin/winepath"
binary "#{appdir}/Wine Staging.app/Contents/Resources/wine/bin/wineserver"
uninstall pkgutil: [
'org.winehq.wine-staging',
'org.winehq.wine-staging-deps',
'org.winehq.wine-staging-deps64',
'org.winehq.wine-staging32',
'org.winehq.wine-staging64',
],
delete: '/Applications/Wine Staging.app'
caveats <<~EOS
#{token} installs support for running 64 bit applications in Wine, which is considered experimental.
If you do not want 64 bit support, you should download and install the #{token} package manually.
EOS
end
| 47.140351 | 104 | 0.651284 |
1a174c6cef1d4546309f24a26f70621a702dadb8 | 1,714 | require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/shared_manager_behavior'
module RosettaQueue
describe ThreadedManager do
before(:each) do
@mutex = mock("Mutex")
@mutex.stub!(:synchronize).and_yield
Mutex.stub!(:new).and_return(@mutex)
Stomp::Connection.stub!(:open).and_return(nil)
@consumer = mock("test_consumer_1", :receive => true, :connection => mock("StompAdapter", :subscribe => true, :unsubscribe => nil, :disconnect => nil),
:unsubscribe => true, :disconnect => true)
Consumer.stub!(:new).and_return(@consumer)
@manager = ThreadedManager.new
@manager.add(@message_handler = mock("message_handler", :destination => "/queue/foo", :option_hash => {}))
end
it_should_behave_like "a consumer manager"
describe "threading" do
before do
@manager.stub!(:join_threads)
@manager.stub!(:monitor_threads)
# we stub brackets because we check a Thread variable
@thread = mock(Thread, :kill => nil, :alive? => true, :[] => false)
Thread.stub!(:new).and_return(@thread)
end
it "should load subscriptions into threads on start" do
during_process {Thread.should_receive(:new).with(:"spec/mocks/mock", @consumer).and_return(@thread)}
end
describe "shutting down" do
def do_process
@manager.start
@manager.stop
end
it "should shut threaded subscriptions down on stop" do
during_process do
@consumer.should_receive(:disconnect)
@thread.should_receive(:kill)
end
end
end
end
end
end
| 32.961538 | 157 | 0.619603 |
62178ab08ffa0c0bf41f886d6c39f7b819ad3ae5 | 767 | # frozen_string_literal: true
require_relative '../../command'
module Rubyists
module Opr
module Commands
class List
# Items subcommand
class Items < Rubyists::Opr::Command
attr_reader :vault
def initialize(vault, options)
@vault = vault
@options = options
end
def execute(input: $stdin, output: $stdout) # rubocop:disable Lint/UnusedMethodArgument
if vault.nil?
warn 'Using vault "Private" since none was given'
@vault = 'Private'
end
# Command logic goes here ...
Opr.with_login { output.puts Vault.find_by_name(vault).items.map(&:title) }
end
end
end
end
end
end
| 25.566667 | 97 | 0.565841 |
18f75f777e7a942943bbf44da9bf7c4497469396 | 792 | require 'spec_helper'
describe TeamsController do
describe 'routing' do
it 'routes to #index' do
expect(get('/teams')).to route_to('teams#index')
end
it 'routes to #new' do
expect(get('/teams/new')).to route_to('teams#new')
end
it 'routes to #show' do
expect(get('/teams/1')).to route_to('teams#show', id: '1')
end
it 'routes to #edit' do
expect(get('/teams/1/edit')).to route_to('teams#edit', id: '1')
end
it 'routes to #create' do
expect(post('/teams')).to route_to('teams#create')
end
it 'routes to #update' do
expect(put('/teams/1')).to route_to('teams#update', id: '1')
end
it 'routes to #destroy' do
expect(delete('/teams/1')).to route_to('teams#destroy', id: '1')
end
end
end
| 23.294118 | 70 | 0.594697 |
1cf4f360d63bd370184a1da6f2a93993caa373b5 | 256 | require 'rubygems'
require 'hpricot'
require 'open-uri'
require 'date'
require 'cgi'
require 'htmlentities'
require 'imdb/imdb'
require 'imdb/imdb_company'
require 'imdb/imdb_movie'
require 'imdb/imdb_name'
require 'imdb/imdb_genre'
require 'imdb/patches'
| 19.692308 | 27 | 0.785156 |
084b059e9c313a2bb63a82ea50f6e090abfae5d8 | 4,812 | # frozen_string_literal: true
require 'webmock/rspec'
# This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = 'spec/examples.txt'
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
# config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
end
| 48.12 | 92 | 0.74335 |
e2fa9b8ce6e6182e9d1d1771953830b207dd6b0d | 5,920 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2019_11_01
module Models
#
# P2SVpnGateway Resource.
#
class P2SVpnGateway < Resource
include MsRestAzure
# @return [SubResource] The VirtualHub to which the gateway belongs.
attr_accessor :virtual_hub
# @return [Array<P2SConnectionConfiguration>] List of all p2s connection
# configurations of the gateway.
attr_accessor :p2sconnection_configurations
# @return [ProvisioningState] The provisioning state of the P2S VPN
# gateway resource. Possible values include: 'Succeeded', 'Updating',
# 'Deleting', 'Failed'
attr_accessor :provisioning_state
# @return [Integer] The scale unit for this p2s vpn gateway.
attr_accessor :vpn_gateway_scale_unit
# @return [SubResource] The VpnServerConfiguration to which the
# p2sVpnGateway is attached to.
attr_accessor :vpn_server_configuration
# @return [VpnClientConnectionHealth] All P2S VPN clients' connection
# health status.
attr_accessor :vpn_client_connection_health
# @return [String] A unique read-only string that changes whenever the
# resource is updated.
attr_accessor :etag
#
# Mapper for P2SVpnGateway class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'P2SVpnGateway',
type: {
name: 'Composite',
class_name: 'P2SVpnGateway',
model_properties: {
id: {
client_side_validation: true,
required: false,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
location: {
client_side_validation: true,
required: false,
serialized_name: 'location',
type: {
name: 'String'
}
},
tags: {
client_side_validation: true,
required: false,
serialized_name: 'tags',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
virtual_hub: {
client_side_validation: true,
required: false,
serialized_name: 'properties.virtualHub',
type: {
name: 'Composite',
class_name: 'SubResource'
}
},
p2sconnection_configurations: {
client_side_validation: true,
required: false,
serialized_name: 'properties.p2SConnectionConfigurations',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'P2SConnectionConfigurationElementType',
type: {
name: 'Composite',
class_name: 'P2SConnectionConfiguration'
}
}
}
},
provisioning_state: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.provisioningState',
type: {
name: 'String'
}
},
vpn_gateway_scale_unit: {
client_side_validation: true,
required: false,
serialized_name: 'properties.vpnGatewayScaleUnit',
type: {
name: 'Number'
}
},
vpn_server_configuration: {
client_side_validation: true,
required: false,
serialized_name: 'properties.vpnServerConfiguration',
type: {
name: 'Composite',
class_name: 'SubResource'
}
},
vpn_client_connection_health: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.vpnClientConnectionHealth',
type: {
name: 'Composite',
class_name: 'VpnClientConnectionHealth'
}
},
etag: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'etag',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 32.173913 | 79 | 0.471453 |
0110d920fd093e344df9e66d77448c4e69d76f17 | 116 | class Therapeutor::Questionnaire::Therapy::PropertyOrder < Therapeutor::Questionnaire::Therapy::PreferenceOrder
end
| 38.666667 | 111 | 0.844828 |
b97b0b03088c7c17e35e497a78ad81eae42d0c75 | 658 | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "engine_example/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "engine_example"
s.version = EngineExample::VERSION
s.authors = ["sue445"]
s.email = ["[email protected]"]
s.homepage = ""
s.summary = ""
s.description = ""
s.license = "MIT"
s.require_paths = ["lib", "engines/admin/lib"]
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"]
s.add_dependency "rails", "~> 5.0.0", ">= 5.0.0.1"
s.add_development_dependency "sqlite3"
end
| 26.32 | 83 | 0.6231 |
38f06b145b65ca4de75e05c0bf1bd6486f5ef636 | 985 | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "em-hiredis/version"
Gem::Specification.new do |s|
s.name = "em-hiredis"
s.version = EventMachine::Hiredis::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Martyn Loughran"]
s.email = ["[email protected]"]
s.homepage = "http://github.com/mloughran/em-hiredis"
s.summary = %q{Eventmachine redis client}
s.description = %q{Eventmachine redis client using hiredis native parser}
s.add_dependency 'eventmachine', '~> 1.2'
s.add_dependency 'hiredis', '~> 0.6.0'
s.add_development_dependency 'em-spec', '~> 0.2.5'
s.add_development_dependency 'rspec', '~> 2.6.0'
s.add_development_dependency 'rake', '< 11.0'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
end
| 36.481481 | 83 | 0.634518 |
0857ba94468455f8039df74340ed528c8f15f5b7 | 4,952 | # Copyright 2017 Google Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/logger'
require 'yaml'
module Google
# A helper class to validate contents coming from YAML files.
class YamlValidator
class << self
def parse(content)
# TODO(nelsonjr): Allow specifying which symbols to restrict it further.
# But it requires inspecting all configuration files for symbol sources,
# such as Enum values. Leaving it as a nice-to-have for the future.
YAML.safe_load(content, allowed_classes)
end
def allowed_classes
ObjectSpace.each_object(Class).select do |klass|
klass < Google::YamlValidator
end.concat([Time, Symbol])
end
end
def validate
Google::LOGGER.debug "Validating #{self.class} '#{@name}'"
check_extraneous_properties
end
def set_variable(value, property)
Google::LOGGER.debug "Setting variable of #{value} to #{self}"
instance_variable_set("@#{property}", value)
end
# Does all validation checking for a particular variable.
# options:
# :default - the default value for this variable if its nil
# :type - the allowed types (single or array) that this value can be
# :item_type - the allowed types that all values in this array should be
# (impllied that type == array)
# :allowed - the allowed values that this non-array variable should be.
# :required - is the variable required? (defaults: false)
def check(variable, **opts)
value = instance_variable_get("@#{variable}")
# Set default value.
if !opts[:default].nil? && value.nil?
instance_variable_set("@#{variable}", opts[:default])
value = instance_variable_get("@#{variable}")
end
# Check if value is required. Print nested path if available.
lineage_path = respond_to?('lineage') ? lineage : ''
raise "#{lineage_path} > Missing '#{variable}'" if value.nil? && opts[:required]
return if value.nil?
# Check type
check_property_value(variable, value, opts[:type]) if opts[:type]
# Check item_type
if value.is_a?(Array)
raise "#{lineage_path} > #{variable} must have item_type on arrays" unless opts[:item_type]
value.each_with_index do |o, index|
check_property_value("#{variable}[#{index}]", o, opts[:item_type])
end
end
# Check if value is allowed
return unless opts[:allowed]
raise "#{value} on #{variable} should be one of #{opts[:allowed]}" \
unless opts[:allowed].include?(value)
end
private
def check_type(name, object, type)
if type == :boolean
return unless [TrueClass, FalseClass].find_index(object.class).nil?
elsif type.is_a? ::Array
return if type.find_index(:boolean) && [TrueClass, FalseClass].find_index(object.class)
return unless type.find_index(object.class).nil?
elsif object.is_a?(type)
return
end
raise "Property '#{name}' is '#{object.class}' instead of '#{type}'"
end
def log_check_type(object)
if object.respond_to?(:name)
Google::LOGGER.debug "Checking object #{object.name}"
else
Google::LOGGER.debug "Checking object #{object}"
end
end
def check_property_value(property, prop_value, type)
Google::LOGGER.debug "Checking '#{property}' on #{object_display_name}"
check_type property, prop_value, type unless type.nil?
prop_value.validate if prop_value.is_a?(Api::Object)
end
def check_extraneous_properties
instance_variables.each do |variable|
var_name = variable.id2name[1..-1]
next if var_name.start_with?('__')
Google::LOGGER.debug "Validating '#{var_name}' on #{object_display_name}"
raise "Extraneous variable '#{var_name}' in #{object_display_name}" \
unless methods.include?(var_name.intern)
end
end
def set_variables(objects, property)
return if objects.nil?
objects.each do |object|
object.set_variable(self, property) if object.respond_to?(:set_variable)
end
end
def ensure_property_does_not_exist(property)
raise "Conflict of property '#{property}' for object '#{self}'" \
unless instance_variable_get("@#{property}").nil?
end
def object_display_name
"#{@name}<#{self.class.name}>"
end
end
end
| 34.873239 | 99 | 0.661753 |
79c7ac62c6c9d54b9942f206f4297671d145a2a6 | 1,301 | require 'test_helper'
class KlarnaModuleTest < Test::Unit::TestCase
include ActiveMerchant::Billing::Integrations
def test_notification_method
Klarna::Notification.expects(:new).with('post_body', authorization_header: 'auth header')
Klarna.notification('post_body', authorization_header: 'auth header')
end
def test_sign_without_discount_rate
fields = {
'purchase_country' => 'SE',
'purchase_currency' => 'SEK',
'locale' => 'sv-se',
'merchant_id' => '1860',
'merchant_terms_uri' => 'http://some-webstore.se?URI=tc',
'merchant_checkout_uri' => 'http://some-webstore.se?URI=checkout',
'merchant_base_uri' => 'http://some-webstore.se?URI=home',
'merchant_confirmation_uri' => 'http://some-webstore.se?URI=confirmation'
}
cart_items = [{:type => 'physical',
:reference => '12345',
:quantity => '1',
:unit_price => '10000'}]
shared_secret = 'example-shared-secret'
calculated_digest = "AB4kuszp2Y4laIP4pfbHTJTPAsR7gFRxh4ml5LEDZxg="
assert_equal calculated_digest, Klarna.sign(fields, cart_items, shared_secret)
end
def test_sign
expected = Digest::SHA256.base64digest('abcdefopq')
assert_equal expected, Klarna.digest('abcdef', 'opq')
end
end
| 33.358974 | 93 | 0.668716 |
6a41724bde0476ce5c848112b1bcd6da12239320 | 1,011 | Spree::Core::Engine.config.to_prepare do
if Spree.user_class
Spree.user_class.class_eval do
include Spree::UserApiAuthentication
include Spree::UserPaymentSource
include Spree::UserReporting
has_and_belongs_to_many :spree_roles,
join_table: 'spree_roles_users',
foreign_key: "user_id",
class_name: "Spree::Role"
has_many :orders, foreign_key: :user_id, class_name: "Spree::Order"
belongs_to :ship_address, class_name: 'Spree::Address'
belongs_to :bill_address, class_name: 'Spree::Address'
# has_spree_role? simply needs to return true or false whether a user has a role or not.
def has_spree_role?(role_in_question)
spree_roles.where(name: role_in_question.to_s).any?
end
def last_incomplete_spree_order
orders.incomplete.order('created_at DESC').first
end
def analytics_id
id
end
end
end
end
| 29.735294 | 94 | 0.644906 |
26a6f42a174b01ce3b06d3113b03eb313546ef41 | 4,409 | require 'telegram/bot/types/compactable'
require 'telegram/bot/types/base'
require 'telegram/bot/types/user'
require 'telegram/bot/types/photo_size'
require 'telegram/bot/types/audio'
require 'telegram/bot/types/document'
require 'telegram/bot/types/mask_position'
require 'telegram/bot/types/sticker'
require 'telegram/bot/types/sticker_set'
require 'telegram/bot/types/video'
require 'telegram/bot/types/voice'
require 'telegram/bot/types/video_note'
require 'telegram/bot/types/contact'
require 'telegram/bot/types/location'
require 'telegram/bot/types/chat_photo'
require 'telegram/bot/types/chat'
require 'telegram/bot/types/message_entity'
require 'telegram/bot/types/venue'
require 'telegram/bot/types/animation'
require 'telegram/bot/types/game'
require 'telegram/bot/types/callback_game'
require 'telegram/bot/types/game_high_score'
require 'telegram/bot/types/invoice'
require 'telegram/bot/types/shipping_address'
require 'telegram/bot/types/order_info'
require 'telegram/bot/types/successful_payment'
require 'telegram/bot/types/poll_option'
require 'telegram/bot/types/poll'
require 'telegram/bot/types/passport_file'
require 'telegram/bot/types/encrypted_passport_element'
require 'telegram/bot/types/encrypted_credentials'
require 'telegram/bot/types/passport_data'
require 'telegram/bot/types/passport_element_error_data_field'
require 'telegram/bot/types/passport_element_error_front_side'
require 'telegram/bot/types/passport_element_error_reverse_side'
require 'telegram/bot/types/passport_element_error_selfie'
require 'telegram/bot/types/passport_element_error_file'
require 'telegram/bot/types/passport_element_error_files'
require 'telegram/bot/types/passport_element_error_translation_file'
require 'telegram/bot/types/passport_element_error_translation_files'
require 'telegram/bot/types/passport_element_error_unspecified'
require 'telegram/bot/types/input_message_content'
require 'telegram/bot/types/input_contact_message_content'
require 'telegram/bot/types/input_location_message_content'
require 'telegram/bot/types/input_text_message_content'
require 'telegram/bot/types/input_venue_message_content'
require 'telegram/bot/types/login_url'
require 'telegram/bot/types/inline_keyboard_button'
require 'telegram/bot/types/inline_keyboard_markup'
require 'telegram/bot/types/inline_query'
require 'telegram/bot/types/inline_query_result_article'
require 'telegram/bot/types/inline_query_result_audio'
require 'telegram/bot/types/inline_query_result_cached_audio'
require 'telegram/bot/types/inline_query_result_cached_document'
require 'telegram/bot/types/inline_query_result_cached_gif'
require 'telegram/bot/types/inline_query_result_cached_mpeg4_gif'
require 'telegram/bot/types/inline_query_result_cached_photo'
require 'telegram/bot/types/inline_query_result_cached_sticker'
require 'telegram/bot/types/inline_query_result_cached_video'
require 'telegram/bot/types/inline_query_result_cached_voice'
require 'telegram/bot/types/inline_query_result_contact'
require 'telegram/bot/types/inline_query_result_game'
require 'telegram/bot/types/inline_query_result_document'
require 'telegram/bot/types/inline_query_result_gif'
require 'telegram/bot/types/inline_query_result_location'
require 'telegram/bot/types/inline_query_result_mpeg4_gif'
require 'telegram/bot/types/inline_query_result_photo'
require 'telegram/bot/types/inline_query_result_venue'
require 'telegram/bot/types/inline_query_result_video'
require 'telegram/bot/types/inline_query_result_voice'
require 'telegram/bot/types/chosen_inline_result'
require 'telegram/bot/types/message'
require 'telegram/bot/types/callback_query'
require 'telegram/bot/types/shipping_query'
require 'telegram/bot/types/pre_checkout_query'
require 'telegram/bot/types/update'
require 'telegram/bot/types/keyboard_button'
require 'telegram/bot/types/reply_keyboard_markup'
require 'telegram/bot/types/reply_keyboard_remove'
require 'telegram/bot/types/force_reply'
require 'telegram/bot/types/file'
require 'telegram/bot/types/labeled_price'
require 'telegram/bot/types/shipping_option'
require 'telegram/bot/types/chat_member'
require 'telegram/bot/types/user_profile_photos'
require 'telegram/bot/types/input_media_photo'
require 'telegram/bot/types/input_media_video'
require 'telegram/bot/types/input_media_animation'
require 'telegram/bot/types/input_media_audio'
require 'telegram/bot/types/input_media_document'
Virtus.finalize
| 47.408602 | 69 | 0.85643 |
39c39597d4de03680995b03b7d9dec3c4409ed3d | 228 | def resource_not_found
{status: 404, error: 'Resource not found' }.to_json
end
def bad_request
{status: 400, error: 'Bad request' }.to_json
end
def server_error
{status: 500, error: 'Internal server error' }.to_json
end
| 19 | 56 | 0.732456 |
7aee4be580a6934c55a01963c3ce583cc81067b2 | 759 | # Configure Rails Environment
ENV["RAILS_ENV"] = "test"
require File.expand_path("../../test/dummy/config/environment.rb", __FILE__)
ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)]
require "rails/test_help"
require 'rails-controller-testing'
# Filter out Minitest backtrace while allowing backtrace from other libraries
# to be shown.
Minitest.backtrace_filter = Minitest::BacktraceFilter.new
# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
# Load fixtures from the engine
if ActiveSupport::TestCase.respond_to?(:fixture_path=)
ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__)
ActiveSupport::TestCase.fixtures :all
end
| 36.142857 | 101 | 0.764163 |
1a0624dda356a227186302d3be7e0821a607e922 | 1,854 | class RelaysController < ApplicationController
before_action :set_relay, only: [:show, :edit, :update, :destroy]
# GET /relays
# GET /relays.json
def index
@relays = Relay.all
end
# GET /relays/1
# GET /relays/1.json
def show
end
# GET /relays/new
def new
@relay = Relay.new
end
# GET /relays/1/edit
def edit
end
# POST /relays
# POST /relays.json
def create
@relay = Relay.new(relay_params)
respond_to do |format|
if @relay.save
format.html { redirect_to @relay, notice: 'Relay was successfully created.' }
format.json { render :show, status: :created, location: @relay }
else
format.html { render :new }
format.json { render json: @relay.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /relays/1
# PATCH/PUT /relays/1.json
def update
respond_to do |format|
if @relay.update(relay_params)
format.html { redirect_to @relay, notice: 'Relay was successfully updated.' }
format.json { render :show, status: :ok, location: @relay }
else
format.html { render :edit }
format.json { render json: @relay.errors, status: :unprocessable_entity }
end
end
end
# DELETE /relays/1
# DELETE /relays/1.json
def destroy
@relay.destroy
respond_to do |format|
format.html { redirect_to relays_url, notice: 'Relay was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_relay
@relay = Relay.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def relay_params
params.require(:relay).permit(:el_socket_id, :name, :pin_num, :pin_id, :is_on)
end
end
| 24.72 | 89 | 0.64671 |
e2ea1a44eb535fe5f5a0e9f70b6682c1f0c88e35 | 10,431 | class Location < ApplicationRecord
self.table_name = 'n3_obce_body'
def self.find_obec(kod_obec)
@obec ||= {}
unless @obec.key?(kod_obec)
@obec[kod_obec] ||=
Location.find_by_sql([
"select naz_obec, kod_obec, kod_okres, point_x, point_y from #{table_name} where kod_obec::integer = ?",
kod_obec.to_i
]).first
end
@obec[kod_obec]
end
def self.naz_obec(kod_obec)
find_obec(kod_obec).try(:naz_obec)
end
def self.naz_obec_with_zkr(kod_obec)
ob = find_obec(kod_obec)
if ob.present?
kod_okres = self.kodOk2names[ob.kod_okres.to_i]&.at(1)
"#{ob.naz_obec} #{kod_okres}"
else
nil
end
end
def naz_obec_with_zkr
kod_okres = Location.kodOk2names[self.kod_okres.to_i]&.at(1)
"#{self.naz_obec} #{kod_okres}"
end
def self.naz_cast(kod_cast)
@naz_cast ||= {}
unless @naz_cast.key?(kod_cast)
@naz_cast[kod_cast] = (
result = Location.connection.select_one(
"select naz_cob, kod_cob from n3_casti_obce_polygony where kod_cob::integer = $1",
'SQL',
[[nil, kod_cast.to_i]]
)
result && result['naz_cob']
)
end
@naz_cast[kod_cast]
end
def self.location_format(kod_ob, kod_cast)
return '' unless kod_ob.present?
ob = find_obec(kod_ob)
return '' unless ob.present?
kod_okres = self.kodOk2names[ob.kod_okres.to_i]&.at(1)
if kod_cast.present?
naz_cast = Location.naz_cast(kod_cast)
"#{ob.naz_obec} #{kod_okres} (#{naz_cast})"
else
"#{ob.naz_obec} #{kod_okres}"
end
end
def parts
Location.connection.select_all(
"select naz_cob, kod_cob from n3_casti_obce_polygony where kod_obec = $1 order by naz_cob",
'SQL',
[[nil, self.kod_obec]]
).to_a
end
def self.okres2zkratka
@okres2zkratka ||= {
'Semily' => 'SM',
'Sokolov' => 'SO',
'Strakonice' => 'ST',
'Karlovy Vary' => 'KV',
'Kladno' => 'KL',
'Tábor' => 'TA',
'Tachov' => 'TC',
'Kolín' => 'KO',
'Teplice' => 'TP',
'Trutnov' => 'TU',
'Liberec' => 'LB',
'Litoměřice' => 'LT',
'Ústí nad Labem' => 'UL',
'Louny' => 'LN',
'Mělník' => 'ME',
'Mladá Boleslav' => 'MB',
'Most' => 'MO',
'Náchod' => 'NA',
'Blansko' => 'BK',
'Brno-venkov' => 'BO',
'Břeclav' => 'BV',
'Zlín' => 'ZL',
'Hodonín' => 'HO',
'Jihlava' => 'JI',
'Kroměříž' => 'KM',
'Prostějov' => 'PV',
'Třebíč' => 'TR',
'Uherské Hradiště' => 'UH',
'Vyškov' => 'VY',
'Znojmo' => 'ZN',
'Žďár nad Sázavou' => 'ZR',
'Jindřichův Hradec' => 'JH',
'Bruntál' => 'BR',
'Frýdek-Místek' => 'FM',
'Karviná' => 'KA',
'Nový Jičín' => 'NJ',
'Jičín' => 'JC',
'Olomouc' => 'OL',
'Opava' => 'OP',
'Ostrava-město' => 'OV',
'Šumperk' => 'SU',
'Vsetín' => 'VS',
'Svitavy' => 'SY',
'Brno-město' => 'BM',
'Ústí nad Orlicí' => 'UO',
'Ostrava' => 'OV',
'Pelhřimov' => 'PE',
'Havlíčkův Brod' => 'HB',
'Jeseník' => 'JE',
'Benešov' => 'BN',
'Beroun' => 'BE',
'Nymburk' => 'NB',
'Pardubice' => 'PA',
'Česká Lípa' => 'CL',
'Písek' => 'PI',
'České Budějovice' => 'CB',
'Plzeň' => 'PM',
'Plzeň-jih' => 'PM',
'Plzeň-sever' => 'PM',
'Plzeň-město' => 'PM',
'Český Krumlov' => 'CK',
'Děčín' => 'DC',
'Domažlice' => 'DO',
'Praha' => 'PH',
'Hlavní město Praha' => 'PH',
'Praha-východ' => 'PY',
'Praha-západ' => 'PZ',
'Prachatice' => 'PT',
'Hradec Králové' => 'HK',
'Cheb' => 'CH',
'Chomutov' => 'CV',
'Příbram' => 'PB',
'Chrudim' => 'CR',
'Rakovník' => 'RA',
'Jablonec nad Nisou' => 'JN',
'Rokycany' => 'RO',
'Rychnov nad Kněžnou' => 'RK',
'Přerov' => 'PR',
'Klatovy' => 'KT',
'Kutná Hora' => 'KH',
}.freeze
end
def self.zkratka2okres
@zkratka2okres ||= (
self.okres2zkratka.each_with_object({}) do |(k, v), acc|
acc[v] = [] unless acc.key?(v)
acc[v] << k
end
)
end
def self.kodOk2names
@kodOk2names ||= {
40169 => ['Benešov' ,'BN'],
40177 => ['Beroun' ,'BE'],
40703 => ['Blansko' ,'BK'],
40738 => ['Břeclav' ,'BV'],
40711 => ['Brno-město' ,'BM'],
40720 => ['Brno-venkov' ,'BO'],
40860 => ['Bruntál' ,'BR'],
40525 => ['Česká Lípa' ,'CL'],
40282 => ['České Budějovice' ,'CB'],
40291 => ['Český Krumlov' ,'CK'],
40428 => ['Cheb' ,'CH'],
40461 => ['Chomutov' ,'CV'],
40614 => ['Chrudim' ,'CR'],
40452 => ['Děčín' ,'DC'],
40355 => ['Domažlice' ,'DO'],
40878 => ['Frýdek-Místek' ,'FM'],
40657 => ['Havlíčkův Brod' ,'HB'],
40746 => ['Hodonín' ,'HO'],
40568 => ['Hradec Králové' ,'HK'],
40533 => ['Jablonec nad Nisou' ,'JN'],
40771 => ['Jeseník' ,'JE'],
40576 => ['Jičín' ,'JC'],
40665 => ['Jihlava' ,'JI'],
40304 => ['Jindřichův Hradec' ,'JH'],
40436 => ['Karlovy Vary' ,'KV'],
40886 => ['Karviná' ,'KA'],
40185 => ['Kladno' ,'KL'],
40363 => ['Klatovy' ,'KT'],
40193 => ['Kolín' ,'KO'],
40827 => ['Kroměříž' ,'KM'],
40207 => ['Kutná Hora' ,'KH'],
40541 => ['Liberec' ,'LB'],
40479 => ['Litoměřice' ,'LT'],
40487 => ['Louny' ,'LN'],
40215 => ['Mělník' ,'ME'],
40223 => ['Mladá Boleslav' ,'MB'],
40495 => ['Most' ,'MO'],
40584 => ['Náchod' ,'NA'],
40894 => ['Nový Jičín' ,'NJ'],
40231 => ['Nymburk' ,'NB'],
40789 => ['Olomouc' ,'OL'],
40908 => ['Opava' ,'OP'],
40916 => ['Ostrava-město' ,'OV'],
40622 => ['Pardubice' ,'PA'],
40673 => ['Pelhřimov' ,'PE'],
40312 => ['Písek' ,'PI'],
40380 => ['Plzeň-jih' ,'PM'],
40371 => ['Plzeň-město' ,'PM'],
40398 => ['Plzeň-sever' ,'PM'],
40321 => ['Prachatice' ,'PT'],
40924 => ['Praha' ,'PH'],
40240 => ['Praha-východ' ,'PY'],
40258 => ['Praha-západ' ,'PZ'],
40801 => ['Přerov' ,'PR'],
40266 => ['Příbram' ,'PB'],
40797 => ['Prostějov' ,'PV'],
40274 => ['Rakovník' ,'RA'],
40401 => ['Rokycany' ,'RO'],
40592 => ['Rychnov nad Kněžnou' ,'RK'],
40550 => ['Semily' ,'SM'],
40444 => ['Sokolov' ,'SO'],
40339 => ['Strakonice' ,'ST'],
40819 => ['Šumperk' ,'SU'],
40631 => ['Svitavy' ,'SY'],
40347 => ['Tábor' ,'TA'],
40410 => ['Tachov' ,'TC'],
40509 => ['Teplice' ,'TP'],
40681 => ['Třebíč' ,'TR'],
40606 => ['Trutnov' ,'TU'],
40835 => ['Uherské Hradiště' ,'UH'],
40517 => ['Ústí nad Labem' ,'UL'],
40649 => ['Ústí nad Orlicí' ,'UO'],
40843 => ['Vsetín' ,'VS'],
40754 => ['Vyškov' ,'VY'],
40690 => ['Žďár nad Sázavou' ,'ZR'],
40851 => ['Zlín' ,'ZL'],
40762 => ['Znojmo' ,'ZN'],
}.freeze
end
# Držkov JH
# Brno BM (Kohoutovice)
def self.guess_lokalizace(str)
md = str.match(/^(.*)\s+(\w\w)(\s*\((.*)\)\s*)?$/)
return [nil, nil] unless md
obec = md[1]
zkr_okres = md[2]
cast = md[4]
# musi sedet nazev obce i zkratka
okres = Location.zkratka2okres[zkr_okres]
locs = Location.where(naz_obec: obec, naz_lau1: okres)
return [nil, nil] if locs.length != 1
loc = locs.first
# jen lokalizace, zadna cast
return [loc.kod_obec, nil] unless cast.present?
part_pair = loc.parts.find do |part|
# part: {"naz_cob"=>"Hoření Paseky", "kod_cob"=>"160563"},
part['naz_cob'] == cast
end
# FIXME: opravdu chceme cele blbe, pokud je blbe jen cast?
#[loc.kod_obec, part_pair && part_pair['kod_cob']]
part_pair.present? ? [loc.kod_obec, part_pair['kod_cob']] : [nil, nil]
end
end
| 37.65704 | 114 | 0.371489 |
18b391f9eee05beb9924b9b18569988e533a11ec | 290 | require File.expand_path('../../../../../spec_helper', __FILE__)
describe "OpenSSL::SSL::SSLContext#tmp_ecdh_callback" do
it "needs to be reviewed for spec completeness"
end
describe "OpenSSL::SSL::SSLContext#tmp_ecdh_callback=" do
it "needs to be reviewed for spec completeness"
end
| 29 | 64 | 0.748276 |
61a7c06607b9cc59ebd1d5cc65593c836a26c3ef | 1,449 |
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "lowruby/version"
Gem::Specification.new do |spec|
spec.name = "lowruby"
spec.version = Lowruby::VERSION
spec.authors = ["gingray"]
spec.email = ["[email protected]"]
spec.summary = %q{low level experiments with ruby}
spec.description = %q{low level experiments with ruby}
spec.homepage = "http://github.com/gingray/lowruby"
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against " \
"public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.extensions = ["ext/lowruby/extconf.rb"]
spec.add_development_dependency "bundler", "~> 1.16"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rake-compiler"
spec.add_development_dependency "rspec", "~> 3.0"
end
| 37.153846 | 96 | 0.667357 |
f804a834a55202ef8e6bc749dc93dd213c7a3ea7 | 991 | module Poly
module GravatarHelper
# Based on http://expo.stimulusreflex.com/demos/gravatar
def user_gravatar(email, options)
return unless %r{[^@]+@[^.]+\..+}.match?(email)
email_md5 = Digest::MD5.hexdigest(email.downcase.strip)
query_params = url_params(options)
@gravatar_image_url = "https://www.gravatar.com/avatar/#{email_md5}#{query_params}"
end
def user_avatar(user)
unless defined?(user.photo)
return user_gravatar(user.email, size: 40)
end
user.photo.attached? ? user.photo : user_gravatar(user.email, size: 40)
end
private
# Based on Gravatar_image_tag gem: mdeering/gravatar_image_tag
def url_params(gravatar_params)
return nil if gravatar_params.keys.size == 0
array = gravatar_params.map { |k, v| "#{k}=#{value_cleaner(v)}" }
"?#{array.join('&')}"
end
def value_cleaner(value)
value = value.to_s
URI.encode_www_form_component(value)
end
end
end
| 29.147059 | 89 | 0.659939 |
6a1ca22c64bbf55b1b3e5d543134d0002999de74 | 1,490 | require 'time'
# A module to gather uptime facts
#
module Facter::Util::Uptime
def self.get_uptime_seconds_unix
uptime_proc_uptime or uptime_sysctl or uptime_kstat or uptime_who_dash_b
end
def self.get_uptime_seconds_win
require 'facter/util/wmi'
last_boot = ""
Facter::Util::WMI.execquery("select * from Win32_OperatingSystem").each do |x|
last_boot = x.LastBootupTime
end
self.compute_uptime(Time.parse(last_boot.split('.').first))
end
private
def self.uptime_proc_uptime
if output = Facter::Util::Resolution.exec("/bin/cat #{uptime_file} 2>/dev/null")
output.chomp.split(" ").first.to_i
end
end
def self.uptime_sysctl
if output = Facter::Util::Resolution.exec("#{uptime_sysctl_cmd} 2>/dev/null")
compute_uptime(Time.at(output.match(/\d+/)[0].to_i))
end
end
def self.uptime_kstat
if output = Facter::Util::Resolution.exec("#{uptime_kstat_cmd} 2>/dev/null")
compute_uptime(Time.at(output.chomp.split(/\s/).last.to_i))
end
end
def self.uptime_who_dash_b
if output = Facter::Util::Resolution.exec("#{uptime_who_cmd} 2>/dev/null")
compute_uptime(Time.parse(output))
end
end
def self.compute_uptime(time)
(Time.now - time).to_i
end
def self.uptime_file
"/proc/uptime"
end
def self.uptime_sysctl_cmd
'sysctl -n kern.boottime'
end
def self.uptime_kstat_cmd
'kstat -p unix:::boot_time'
end
def self.uptime_who_cmd
'who -b'
end
end
| 22.575758 | 84 | 0.689262 |
bbbfed6832923cb41e94d2defe0af74843bf77a4 | 507 | unless Rails.env.test?
# Tell the Rack::Attack Rack middleware to maintain an IP blacklist. We will
# update the blacklist from Grack::Auth#authenticate_user.
Rack::Attack.blacklist('Git HTTP Basic Auth') do |req|
Rack::Attack::Allow2Ban.filter(req.ip, Gitlab.config.rack_attack.git_basic_auth) do
# This block only gets run if the IP was not already banned.
# Return false, meaning that we do not see anything wrong with the
# request at this time
false
end
end
end
| 39 | 87 | 0.717949 |
4a740987fe3d530b0c2e716e0372d79424874ad3 | 16,990 | # frozen_string_literal: true
require 'bolt/pal'
module Bolt
class Outputter
class Human < Bolt::Outputter
COLORS = {
red: "31",
green: "32",
yellow: "33",
cyan: "36"
}.freeze
def print_head; end
def initialize(color, verbose, trace, spin, stream = $stdout)
super
# Plans and without_default_logging() calls can both be nested, so we
# track each of them with a "stack" consisting of an integer.
@plan_depth = 0
@disable_depth = 0
@pinwheel = %w[- \\ | /]
end
def colorize(color, string)
if @color && @stream.isatty
"\033[#{COLORS[color]}m#{string}\033[0m"
else
string
end
end
def start_spin
return unless @spin
@spin = true
@spin_thread = Thread.new do
loop do
sleep(0.1)
@stream.print(colorize(:cyan, @pinwheel.rotate!.first + "\b"))
end
end
end
def stop_spin
return unless @spin
@spin_thread.terminate
@spin = false
@stream.print("\b")
end
def remove_trail(string)
string.sub(/\s\z/, '')
end
def wrap(string, width = 80)
string.gsub(/(.{1,#{width}})(\s+|\Z)/, "\\1\n")
end
def handle_event(event)
case event[:type]
when :enable_default_output
@disable_depth -= 1
when :disable_default_output
@disable_depth += 1
when :message
print_message(event[:message])
end
if enabled?
case event[:type]
when :node_start
print_start(event[:target]) if @verbose
when :node_result
print_result(event[:result]) if @verbose
when :step_start
print_step_start(**event) if plan_logging?
when :step_finish
print_step_finish(**event) if plan_logging?
when :plan_start
print_plan_start(event)
when :plan_finish
print_plan_finish(event)
end
end
end
def enabled?
@disable_depth == 0
end
def plan_logging?
@plan_depth > 0
end
def print_start(target)
@stream.puts(colorize(:green, "Started on #{target.safe_name}..."))
end
def print_result(result)
if result.success?
@stream.puts(colorize(:green, "Finished on #{result.target.safe_name}:"))
else
@stream.puts(colorize(:red, "Failed on #{result.target.safe_name}:"))
end
if result.error_hash
@stream.puts(colorize(:red, remove_trail(indent(2, result.error_hash['msg']))))
end
if result.is_a?(Bolt::ApplyResult) && @verbose
result.resource_logs.each do |log|
# Omit low-level info/debug messages
next if %w[info debug].include?(log['level'])
message = format_log(log)
@stream.puts(indent(2, message))
end
end
# Only print results if there's something other than empty string and hash
if result.value.empty? || (result.value.keys == ['_output'] && !result.message?)
@stream.puts(indent(2, "#{result.action.capitalize} completed successfully with no result"))
else
# Only print messages that have something other than whitespace
if result.message?
@stream.puts(remove_trail(indent(2, result.message)))
end
# Use special handling if the result looks like a command or script result
if result.generic_value.keys == %w[stdout stderr exit_code]
safe_value = result.safe_value
unless safe_value['stdout'].strip.empty?
@stream.puts(indent(2, "STDOUT:"))
@stream.puts(indent(4, safe_value['stdout']))
end
unless safe_value['stderr'].strip.empty?
@stream.puts(indent(2, "STDERR:"))
@stream.puts(indent(4, safe_value['stderr']))
end
elsif result.generic_value.any?
@stream.puts(indent(2, ::JSON.pretty_generate(result.generic_value)))
end
end
end
def format_log(log)
color = case log['level']
when 'warn'
:yellow
when 'err'
:red
end
source = "#{log['source']}: " if log['source']
message = "#{log['level'].capitalize}: #{source}#{log['message']}"
message = colorize(color, message) if color
message
end
def print_step_start(description:, targets:, **_kwargs)
target_str = if targets.length > 5
"#{targets.count} targets"
else
targets.map(&:safe_name).join(', ')
end
@stream.puts(colorize(:green, "Starting: #{description} on #{target_str}"))
end
def print_step_finish(description:, result:, duration:, **_kwargs)
failures = result.error_set.length
plural = failures == 1 ? '' : 's'
message = "Finished: #{description} with #{failures} failure#{plural} in #{duration.round(2)} sec"
@stream.puts(colorize(:green, message))
end
def print_plan_start(event)
@plan_depth += 1
# We use this event to both mark the start of a plan _and_ to enable
# plan logging for `apply`, so only log the message if we were called
# with a plan
if event[:plan]
@stream.puts(colorize(:green, "Starting: plan #{event[:plan]}"))
end
end
def print_plan_finish(event)
@plan_depth -= 1
plan = event[:plan]
duration = event[:duration]
@stream.puts(colorize(:green, "Finished: plan #{plan} in #{duration_to_string(duration)}"))
end
def print_summary(results, elapsed_time = nil)
ok_set = results.ok_set
unless ok_set.empty?
@stream.puts format('Successful on %<size>d target%<plural>s: %<names>s',
size: ok_set.size,
plural: ok_set.size == 1 ? '' : 's',
names: ok_set.targets.map(&:safe_name).join(','))
end
error_set = results.error_set
unless error_set.empty?
@stream.puts colorize(:red,
format('Failed on %<size>d target%<plural>s: %<names>s',
size: error_set.size,
plural: error_set.size == 1 ? '' : 's',
names: error_set.targets.map(&:safe_name).join(',')))
end
total_msg = format('Ran on %<size>d target%<plural>s',
size: results.size,
plural: results.size == 1 ? '' : 's')
total_msg << " in #{duration_to_string(elapsed_time)}" unless elapsed_time.nil?
@stream.puts total_msg
end
def print_table(results, padding_left = 0, padding_right = 3)
# lazy-load expensive gem code
require 'terminal-table'
@stream.puts Terminal::Table.new(
rows: results,
style: {
border_x: '',
border_y: '',
border_i: '',
padding_left: padding_left,
padding_right: padding_right,
border_top: false,
border_bottom: false
}
)
end
def print_tasks(tasks, modulepath)
command = Bolt::Util.powershell? ? 'Get-BoltTask -Task <TASK NAME>' : 'bolt task show <TASK NAME>'
tasks.any? ? print_table(tasks) : print_message('No available tasks')
print_message("\nMODULEPATH:\n#{modulepath.join(File::PATH_SEPARATOR)}\n"\
"\nUse '#{command}' to view "\
"details and parameters for a specific task.")
end
# @param [Hash] task A hash representing the task
def print_task_info(task)
# Building lots of strings...
pretty_params = +""
task_info = +""
usage = if Bolt::Util.powershell?
+"Invoke-BoltTask -Name #{task.name} -Targets <targets>"
else
+"bolt task run #{task.name} --targets <targets>"
end
task.parameters&.each do |k, v|
pretty_params << "- #{k}: #{v['type'] || 'Any'}\n"
pretty_params << " Default: #{v['default'].inspect}\n" if v.key?('default')
pretty_params << " #{v['description']}\n" if v['description']
usage << if v['type'].start_with?("Optional")
" [#{k}=<value>]"
else
" #{k}=<value>"
end
end
if task.supports_noop
usage << Bolt::Util.powershell? ? '[-Noop]' : '[--noop]'
end
task_info << "\n#{task.name}"
task_info << " - #{task.description}" if task.description
task_info << "\n\n"
task_info << "USAGE:\n#{usage}\n\n"
task_info << "PARAMETERS:\n#{pretty_params}\n" unless pretty_params.empty?
task_info << "MODULE:\n"
path = task.files.first['path'].chomp("/tasks/#{task.files.first['name']}")
task_info << if path.start_with?(Bolt::Config::Modulepath::MODULES_PATH)
"built-in module"
else
path
end
@stream.puts(task_info)
end
# @param [Hash] plan A hash representing the plan
def print_plan_info(plan)
# Building lots of strings...
pretty_params = +""
plan_info = +""
usage = if Bolt::Util.powershell?
+"Invoke-BoltPlan -Name #{plan['name']}"
else
+"bolt plan run #{plan['name']}"
end
plan['parameters'].each do |name, p|
pretty_params << "- #{name}: #{p['type']}\n"
pretty_params << " Default: #{p['default_value']}\n" unless p['default_value'].nil?
pretty_params << " #{p['description']}\n" if p['description']
usage << (p.include?('default_value') ? " [#{name}=<value>]" : " #{name}=<value>")
end
plan_info << "\n#{plan['name']}"
plan_info << " - #{plan['description']}" if plan['description']
plan_info << "\n\n"
plan_info << "USAGE:\n#{usage}\n\n"
plan_info << "PARAMETERS:\n#{pretty_params}\n" unless plan['parameters'].empty?
plan_info << "MODULE:\n"
path = plan['module']
plan_info << if path.start_with?(Bolt::Config::Modulepath::MODULES_PATH)
"built-in module"
else
path
end
@stream.puts(plan_info)
end
def print_plans(plans, modulepath)
command = Bolt::Util.powershell? ? 'Get-BoltPlan -Name <PLAN NAME>' : 'bolt plan show <PLAN NAME>'
plans.any? ? print_table(plans) : print_message('No available plans')
print_message("\nMODULEPATH:\n#{modulepath.join(File::PATH_SEPARATOR)}\n"\
"\nUse '#{command}' to view "\
"details and parameters for a specific plan.")
end
def print_topics(topics)
print_message("Available topics are:")
print_message(topics.join("\n"))
print_message("\nUse 'bolt guide <TOPIC>' to view a specific guide.")
end
def print_guide(guide, _topic)
@stream.puts(guide)
end
def print_module_list(module_list)
module_list.each do |path, modules|
if (mod = modules.find { |m| m[:internal_module_group] })
@stream.puts(colorize(:cyan, mod[:internal_module_group]))
else
@stream.puts(colorize(:cyan, path))
end
if modules.empty?
@stream.puts('(no modules installed)')
else
module_info = modules.map do |m|
version = if m[:version].nil?
m[:internal_module_group].nil? ? '(no metadata)' : '(built-in)'
else
m[:version]
end
[m[:name], version]
end
print_table(module_info, 2, 1)
end
@stream.write("\n")
end
end
def print_targets(target_list, inventoryfile)
adhoc = colorize(:yellow, "(Not found in inventory file)")
targets = []
targets += target_list[:inventory].map { |target| [target.name, nil] }
targets += target_list[:adhoc].map { |target| [target.name, adhoc] }
if targets.any?
print_table(targets, 0, 2)
@stream.puts
end
@stream.puts "INVENTORY FILE:"
if File.exist?(inventoryfile)
@stream.puts inventoryfile
else
@stream.puts wrap("Tried to load inventory from #{inventoryfile}, but the file does not exist")
end
@stream.puts "\nTARGET COUNT:"
@stream.puts "#{targets.count} total, #{target_list[:inventory].count} from inventory, "\
"#{target_list[:adhoc].count} adhoc"
end
def print_target_info(targets)
@stream.puts ::JSON.pretty_generate(
"targets": targets.map(&:detail)
)
count = "#{targets.count} target#{'s' unless targets.count == 1}"
@stream.puts colorize(:green, count)
end
def print_groups(groups)
count = "#{groups.count} group#{'s' unless groups.count == 1}"
@stream.puts groups.join("\n")
@stream.puts colorize(:green, count)
end
# @param [Bolt::ResultSet] apply_result A ResultSet object representing the result of a `bolt apply`
def print_apply_result(apply_result, elapsed_time)
print_summary(apply_result, elapsed_time)
end
# @param [Bolt::PlanResult] plan_result A PlanResult object
def print_plan_result(plan_result)
value = plan_result.value
case value
when nil
@stream.puts("Plan completed successfully with no result")
when Bolt::ApplyFailure, Bolt::RunFailure
print_result_set(value.result_set)
when Bolt::ResultSet
print_result_set(value)
else
@stream.puts(::JSON.pretty_generate(plan_result, quirks_mode: true))
end
end
def print_result_set(result_set)
result_set.each { |result| print_result(result) }
print_summary(result_set)
end
def print_puppetfile_result(success, puppetfile, moduledir)
if success
@stream.puts("Successfully synced modules from #{puppetfile} to #{moduledir}")
else
@stream.puts(colorize(:red, "Failed to sync modules from #{puppetfile} to #{moduledir}"))
end
end
def fatal_error(err)
@stream.puts(colorize(:red, err.message))
if err.is_a? Bolt::RunFailure
@stream.puts ::JSON.pretty_generate(err.result_set)
end
if @trace && err.backtrace
err.backtrace.each do |line|
@stream.puts(colorize(:red, "\t#{line}"))
end
end
end
def print_message(message)
@stream.puts(message)
end
def print_error(message)
@stream.puts(colorize(:red, message))
end
def print_prompt(prompt)
@stream.print(colorize(:cyan, indent(4, prompt)))
end
def print_prompt_error(message)
@stream.puts(colorize(:red, indent(4, message)))
end
def print_action_step(step)
first, *remaining = wrap(step, 76).lines
first = indent(2, "→ #{first}")
remaining = remaining.map { |line| indent(4, line) }
step = [first, *remaining, "\n"].join
@stream.puts(step)
end
def print_action_error(error)
# Running everything through 'wrap' messes with newlines. Separating
# into lines and wrapping each individually ensures separate errors are
# distinguishable.
first, *remaining = error.lines
first = colorize(:red, indent(2, "→ #{wrap(first, 76)}"))
wrapped = remaining.map { |l| wrap(l) }
to_print = wrapped.map { |line| colorize(:red, indent(4, line)) }
step = [first, *to_print, "\n"].join
@stream.puts(step)
end
def duration_to_string(duration)
hrs = (duration / 3600).floor
mins = ((duration % 3600) / 60).floor
secs = (duration % 60)
if hrs > 0
"#{hrs} hr, #{mins} min, #{secs.round} sec"
elsif mins > 0
"#{mins} min, #{secs.round} sec"
else
# Include 2 decimal places if the duration is under a minute
"#{secs.round(2)} sec"
end
end
end
end
end
| 33.710317 | 106 | 0.54126 |
1136ba1782af4dbdbf330119bed71760f4b7650d | 151 | class ResetUserLoginTriesCountWorker
include Sidekiq::Worker
def perform(id)
user = User.find(id)
user.reset_login_tries_count!
end
end
| 16.777778 | 36 | 0.754967 |
f838fb463be16be17cc4d44df24fbb067c43cd40 | 7,291 | require "addressable/template"
require "faraday"
require "json"
require "logger"
module Eversign
class FileNotFoundException < Exception
end
class Client
attr_accessor :access_key, :base_uri, :business_id, :token
def initialize()
self.base_uri = Eversign.configuration.api_base || "https://api.eversign.com"
access_key = Eversign.configuration.access_key
if access_key.start_with?("Bearer ")
self.set_oauth_access_token(access_key)
else
self.access_key = access_key
end
self.business_id = Eversign.configuration.business_id
end
def set_oauth_access_token(oauthtoken)
if oauthtoken.startswith("Bearer ")
self.token = oauthtoken
else
self.token = "Bearer " + oauthtoken
end
self.get_businesses()
end
def generate_oauth_authorization_url(options)
check_arguments(["client_id", "state"], options)
template = Addressable::Template.new(Eversign.configuration.oauth_base + "/authorize{?clinet_id,state}")
return template.partial_expand(clinet_id: options["client_id"], state: options["state"]).pattern
end
def request_oauth_token(options)
check_arguments(["client_id", "client_secret", "code", "state"], options)
req = execute_request(:post, "/token", options)
if req.status == 200
response_obj = JSON.parse(req.body)
if response_obj.key?("success")
raise response_obj["message"]
else
return response_obj["access_token"]
end
end
raise "no success"
end
def get_buisnesses
response = execute_request(:get, "/api/business?access_key=#{access_key}")
extract_response(response.body, Eversign::Mappings::Business)
end
def get_all_documents
get_documents("all")
end
def get_completed_documents
get_documents("completed")
end
def get_draft_documents
get_documents("draft")
end
def get_cancelled_documents
get_documents("cancelled")
end
def get_action_required_documents
get_documents("my_action_required")
end
def get_waiting_for_others_documents
get_documents("waiting_for_others")
end
def get_templates
get_documents("templates")
end
def get_archived_templates
get_documents("templates_archived")
end
def get_draft_templates
get_documents("template_draft")
end
def get_document(document_hash)
path = "/api/document?access_key=#{access_key}&business_id=#{business_id}&document_hash=#{document_hash}"
response = execute_request(:get, path)
extract_response(response.body, Eversign::Mappings::Document)
end
def create_document(document, isFromTemplate = false)
if document.files
document.files.each do |file|
if file.is_a? Hash
file.keys.each { |key| file.define_singleton_method(key) { self[key] } }
file.keys.each { |key| file.define_singleton_method("#{key}=") { |v| self[key] = v } }
end
next unless file.file_url
file_response = upload_file(file.file_url)
file.file_url = nil
file.file_id = file_response.file_id
end
end
path = "/api/document?access_key=#{access_key}&business_id=#{business_id}"
data = Eversign::Mappings::Document.representation_for(document, isFromTemplate)
response = execute_request(:post, path, data)
extract_response(response.body, Eversign::Mappings::Document)
end
def create_document_from_template(template)
create_document(template, true)
end
def delete_document(document_hash)
path = "/api/document?access_key=#{access_key}&business_id=#{business_id}&document_hash=#{document_hash}"
delete(path, document_hash)
end
def cancel_document(document_hash)
path = "/api/document?access_key=#{access_key}&business_id=#{business_id}&document_hash=#{document_hash}&cancel=1"
delete(path, document_hash)
end
def download_raw_document_to_path(document_hash, path)
sub_uri = "/api/download_raw_document?access_key=#{access_key}&business_id=#{business_id}&document_hash=#{document_hash}"
download(sub_uri, path)
end
def download_final_document_to_path(document_hash, path, audit_trail = 1)
sub_uri = "/api/download_raw_document?access_key=#{access_key}&business_id=#{business_id}&document_hash=#{document_hash}&audit_trail=#{audit_trail}"
download(sub_uri, path)
end
def upload_file(file_path)
upload = if File.exist?(file_path)
file_path
else
Tempfile.new.tap do |f|
f.write(URI.parse(file_path))
f.close
end
end
payload = { upload: Faraday::UploadIO.new(upload, 'text/plain') }
path = "/api/file?access_key=#{access_key}&business_id=#{business_id}"
response = execute_request(:post, path, payload, true)
extract_response(response.body, Eversign::Mappings::File)
end
def send_reminder_for_document(document_hash, signer_id)
path = "/api/send_reminder?access_key=#{access_key}&business_id=#{business_id}"
response = execute_request(:post, path, { document_hash: document_hash, signer_id: signer_id }.to_json)
eval(response.body)[:success] ? true : extract_response(response.body)
end
private
def append_sdk_id (body)
begin
bodyHash = JSON.parse(body)
bodyHash['client'] = 'ruby-sdk'
return bodyHash.to_json
rescue
return body
end
end
def execute_request(method, path, body = nil, multipart = false)
@faraday ||= Faraday.new(base_uri) do |conn|
conn.headers = {}
conn.headers["User-Agent"] = "Eversign_Ruby_SDK"
conn.headers["Authorization"] = token if token
conn.request :multipart if multipart
conn.adapter :net_http
end
body = append_sdk_id(body)
@faraday.send(method) do |request|
request.url path
request.body = body if body
end
end
def check_arguments(arguments = [], options = {})
arguments.each do |argument|
raise ("Please specify " + argument) unless options.has_key?(argument.to_sym)
end
end
def delete(path, document_hash)
response = execute_request(:delete, path)
eval(response.body)[:success] ? true : extract_response(response.body)
end
def download(sub_uri, path)
response = execute_request(:get, sub_uri)
File.open(path, "wb") { |fp| fp.write(response.body) }
end
def get_documents(doc_type)
path = "/api/document?access_key=#{access_key}&business_id=#{business_id}&type=#{doc_type}"
response = execute_request(:get, path)
extract_response(response.body, Eversign::Mappings::Document)
end
def extract_response(body, mapping = nil)
data = JSON.parse(body)
if data.kind_of?(Array)
mapping.extract_collection(body, nil)
else
if data.key?("success")
Eversign::Mappings::Exception.extract_single(body, nil)
else
mapping.extract_single(body, nil)
end
end
end
end
end
| 31.291845 | 154 | 0.663558 |
1160eaf55311811ae77d7de79f3f7b80a7dbf3d9 | 2,788 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2019_06_13_144947) do
create_table "channels", force: :cascade do |t|
t.string "name"
t.string "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "game_leaderboards", force: :cascade do |t|
t.integer "game_id"
t.integer "leaderboard_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["game_id"], name: "index_game_leaderboards_on_game_id"
t.index ["leaderboard_id"], name: "index_game_leaderboards_on_leaderboard_id"
end
create_table "games", force: :cascade do |t|
t.string "game_type"
t.integer "room_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["room_id"], name: "index_games_on_room_id"
end
create_table "leaderboards", force: :cascade do |t|
t.string "name"
t.string "location"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "rooms", force: :cascade do |t|
t.string "name"
t.integer "required_players"
t.integer "channel_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["channel_id"], name: "index_rooms_on_channel_id"
end
create_table "tick_tack_toes", force: :cascade do |t|
t.integer "points"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "user_channels", force: :cascade do |t|
t.integer "user_id"
t.integer "channel_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["channel_id"], name: "index_user_channels_on_channel_id"
t.index ["user_id"], name: "index_user_channels_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "password"
t.string "location"
t.string "first_name"
t.string "last_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| 34.419753 | 86 | 0.715208 |
793228362228b08481d0f732be98a8267b9a1c81 | 1,316 | class CommentsController < ApplicationController
include ActionVoter
before_action :authenticate_user!
before_action :find_comment, only: [:update, :destroy]
def create
@comment = current_user.comments.new(comment_params)
if @comment.save
@new_comment = Comment.new
if @comment.parent_id.nil?
render 'courses/comments/created'
else
render 'courses/comments/replies/created'
end
else
render json: { error: @comment.errors.full_messages }, status: 500
end
end
def update
if @comment.update(comment_params)
render json: @comment.as_json(only: [:id, :content, :updated_at])
else
render json: { error: @comment.errors.full_messages }, status: 500
end
end
def destroy
if @comment.destroy
render json: @comment.as_json(only: [:id])
else
render json: { error: @comment.errors.full_messages }, status: 500
end
end
def vote
comment = Comment.find(params[:id])
vote_for(comment, params[:upvote])
end
private
def find_comment
@comment = current_user.comments.find(params[:id])
end
def comment_params
params_allowed = [:content]
params_allowed << :course_id << :parent_id if action_name == 'create'
params.require(:comment).permit(params_allowed)
end
end
| 24.37037 | 73 | 0.680091 |
5ddb7ad4aacfa4f8f11b123a41b6fdba7ab12e1d | 1,333 | #
class Egi::Fedcloud::Cloudhound::AppdbAppliance
attr_reader :identifier, :version, :url,
:checksum, :format, :owner,
:published, :mpuri
attr_reader :sites
#
def initialize(element)
Egi::Fedcloud::Cloudhound::Log.debug "[#{self.class}] Initializing with #{element.inspect}"
@identifier = element['identifier']
@version = element['version']
@url = element['url']
@checksum = element['checksum']
@format = element['format']
@owner = element['addedby'] ? element['addedby']['permalink'] : 'unknown'
@published = element['published']
@mpuri = element['mpuri']
# and now the difficult part
@sites = self.class.extract_sites(element['sites'])
end
class << self
#
def extract_sites(element)
return [] if element.blank?
element.collect do |site|
st = {}
st['name'] = site['name']
st['gocdb_link'] = site['url'] ? site['url']['portal'] : 'unknown'
st['vos'] = extract_site_vos(site['services'])
st
end
end
#
def extract_site_vos(element)
return [] if element.blank?
vos = []
element.each do |service|
vos << service['vos'].collect { |vo| vo['name'] }
end
vos.flatten!
vos.compact!
vos.uniq!
vos
end
end
end
| 23.385965 | 95 | 0.579895 |
26ad402bb18a87dd99f7bd81db670bdb3728f881 | 5,339 | =begin
PureCloud Platform API
With the PureCloud Platform API, you can control all aspects of your PureCloud environment. With the APIs you can access the system configuration, manage conversations and more.
OpenAPI spec version: v2
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
License: UNLICENSED
https://help.mypurecloud.com/articles/terms-and-conditions/
Terms of Service: https://help.mypurecloud.com/articles/terms-and-conditions/
=end
require 'date'
module PureCloud
class ConversationChatEventTopicJourneyAction
attr_accessor :id
attr_accessor :action_map
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'id' => :'id',
:'action_map' => :'actionMap'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'id' => :'String',
:'action_map' => :'ConversationChatEventTopicJourneyActionMap'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v}
if attributes.has_key?(:'id')
self.id = attributes[:'id']
end
if attributes.has_key?(:'actionMap')
self.action_map = attributes[:'actionMap']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properies with the reasons
def list_invalid_properties
invalid_properties = Array.new
return invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
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 &&
id == o.id &&
action_map == o.action_map
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[id, action_map].hash
end
# build the object from hash
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
else
#TODO show warning in debug mode
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
else
# data not found in attributes(hash), not an issue as the data can be optional
end
end
self
end
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /^(true|t|yes|y|1)$/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
_model = Object.const_get("PureCloud").const_get(type).new
_model.build_from_hash(value)
end
end
def to_s
to_hash.to_s
end
# to_body is an alias to to_body (backward compatibility))
def to_body
to_hash
end
# return the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Method to output non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
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
| 23.519824 | 177 | 0.582881 |
08d064b604ee1cfca58eb6e6890f4bd1ad42c7ee | 98 | require "organ/trail/version"
module Organ
module Trail
# Your code goes here...
end
end
| 12.25 | 29 | 0.693878 |
39b4c1cf17d3bf47d55de9d572b287541d724c5e | 4,465 | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20141018212156) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "connect_github_user_statuses", force: true do |t|
t.integer "user_id"
t.integer "github_user_id"
t.string "oauth_code"
t.string "status"
t.string "step"
t.text "error_message"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "delayed_jobs", force: true do |t|
t.integer "priority", default: 0, null: false
t.integer "attempts", default: 0, null: false
t.text "handler", null: false
t.text "last_error"
t.datetime "run_at"
t.datetime "locked_at"
t.datetime "failed_at"
t.string "locked_by"
t.string "queue"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "delayed_jobs", ["priority", "run_at"], name: "delayed_jobs_priority", using: :btree
create_table "github_emails", force: true do |t|
t.integer "github_user_id", null: false
t.string "address", limit: 255
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "github_emails", ["github_user_id"], name: "index_github_emails_on_github_user_id", using: :btree
create_table "github_teams", force: true do |t|
t.string "slug", limit: 255
t.string "organization", limit: 255
t.string "name", limit: 255
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "github_user_disabled_teams", id: false, force: true do |t|
t.integer "github_user_id"
t.integer "github_team_id"
end
create_table "github_user_teams", id: false, force: true do |t|
t.integer "github_user_id"
t.integer "github_team_id"
end
create_table "github_users", force: true do |t|
t.integer "user_id"
t.string "login", limit: 255, null: false
t.boolean "mfa"
t.string "encrypted_token", limit: 255
t.datetime "last_sync_at"
t.string "sync_error", limit: 255
t.datetime "sync_error_at"
t.datetime "created_at"
t.datetime "updated_at"
t.string "state", limit: 255, default: "unknown", null: false
t.string "avatar_url", limit: 255
t.string "html_url", limit: 255
end
add_index "github_users", ["login"], name: "index_github_users_on_login", unique: true, using: :btree
add_index "github_users", ["user_id"], name: "index_github_users_on_user_id", using: :btree
create_table "settings", force: true do |t|
t.string "key", limit: 255
t.text "value"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "settings", ["key"], name: "index_settings_on_key", unique: true, using: :btree
create_table "users", force: true do |t|
t.string "username", limit: 255, default: "", null: false
t.string "name", limit: 255
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip", limit: 255
t.string "last_sign_in_ip", limit: 255
t.datetime "created_at"
t.datetime "updated_at"
t.datetime "last_ldap_sync"
t.integer "ldap_account_control"
t.string "ldap_sync_error", limit: 255
t.datetime "ldap_sync_error_at"
t.string "email", limit: 255
t.boolean "admin"
t.string "remember_token"
end
add_index "users", ["username"], name: "index_users_on_username", unique: true, using: :btree
end
| 36.300813 | 109 | 0.665398 |
e278fdd51009ad621d1c947e74a02b1494974c38 | 16,284 | class PythonAT37 < Formula
desc "Interpreted, interactive, object-oriented programming language"
homepage "https://www.python.org/"
url "https://www.python.org/ftp/python/3.7.10/Python-3.7.10.tar.xz"
sha256 "f8d82e7572c86ec9d55c8627aae5040124fd2203af400c383c821b980306ee6b"
license "Python-2.0"
revision 2
livecheck do
url "https://www.python.org/ftp/python/"
regex(%r{href=.*?v?(3\.7(?:\.\d+)*)/?["' >]}i)
end
bottle do
sha256 big_sur: "80254e0ed92ea7c5a77aab2e1ca9f1b7ea4f9258419710114b9cdca2740f2247"
sha256 catalina: "a5ae644b32ffc98ae4c06fa252b97d55abd653b6798cf908e8555bf03294ea12"
sha256 mojave: "032d2875bd49a94e0a465f9ddb578198bc2c498a3308eb03536c07a9730dcf7b"
end
# setuptools remembers the build flags python is built with and uses them to
# build packages later. Xcode-only systems need different flags.
pour_bottle? do
on_macos do
reason <<~EOS
The bottle needs the Apple Command Line Tools to be installed.
You can install them, if desired, with:
xcode-select --install
EOS
satisfy { MacOS::CLT.installed? }
end
end
keg_only :versioned_formula
depends_on "pkg-config" => :build
depends_on arch: :x86_64
depends_on "gdbm"
depends_on "mpdecimal"
depends_on "[email protected]"
depends_on "readline"
depends_on "sqlite"
depends_on "xz"
uses_from_macos "bzip2"
uses_from_macos "libffi"
uses_from_macos "ncurses"
uses_from_macos "xz"
uses_from_macos "zlib"
skip_clean "bin/pip3", "bin/pip-3.4", "bin/pip-3.5", "bin/pip-3.6", "bin/pip-3.7"
skip_clean "bin/easy_install3", "bin/easy_install-3.4", "bin/easy_install-3.5",
"bin/easy_install-3.6", "bin/easy_install-3.7"
resource "setuptools" do
url "https://files.pythonhosted.org/packages/12/68/95515eaff788370246dac534830ea9ccb0758e921ac9e9041996026ecaf2/setuptools-53.0.0.tar.gz"
sha256 "1b18ef17d74ba97ac9c0e4b4265f123f07a8ae85d9cd093949fa056d3eeeead5"
end
resource "pip" do
url "https://files.pythonhosted.org/packages/b7/2d/ad02de84a4c9fd3b1958dc9fb72764de1aa2605a9d7e943837be6ad82337/pip-21.0.1.tar.gz"
sha256 "99bbde183ec5ec037318e774b0d8ae0a64352fe53b2c7fd630be1d07e94f41e5"
end
resource "wheel" do
url "https://files.pythonhosted.org/packages/75/28/521c6dc7fef23a68368efefdcd682f5b3d1d58c2b90b06dc1d0b805b51ae/wheel-0.34.2.tar.gz"
sha256 "8788e9155fe14f54164c1b9eb0a319d98ef02c160725587ad60f14ddc57b6f96"
end
resource "importlib-metadata" do
url "https://files.pythonhosted.org/packages/0c/89/412afa5f0018dccf637c2d25b9d6a41623cd22beef6797c0d67a2082ccfe/importlib_metadata-3.4.0.tar.gz"
sha256 "fa5daa4477a7414ae34e95942e4dd07f62adf589143c875c133c1e53c4eff38d"
end
resource "zipp" do
url "https://files.pythonhosted.org/packages/ce/b0/757db659e8b91cb3ea47d90350d7735817fe1df36086afc77c1c4610d559/zipp-3.4.0.tar.gz"
sha256 "ed5eee1974372595f9e416cc7bbeeb12335201d8081ca8a0743c954d4446e5cb"
end
# Patch for MACOSX_DEPLOYMENT_TARGET on Big Sur. Upstream currently does
# not have plans to backport the fix to 3.7, so we're maintaining this patch
# ourselves.
# https://bugs.python.org/issue42504
patch do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/05a27807/python/3.7.9.patch"
sha256 "486188ac1a4af4565de5ad54949939bb69bffc006297e8eac9339f19d7d7492b"
end
# Link against libmpdec.so.3, update for mpdecimal.h symbol cleanup.
patch do
url "https://www.bytereef.org/contrib/decimal-3.7.diff"
sha256 "aa9a3002420079a7d2c6033d80b49038d490984a9ddb3d1195bb48ca7fb4a1f0"
end
def lib_cellar
on_macos do
return prefix/"Frameworks/Python.framework/Versions/#{version.major_minor}/lib/python#{version.major_minor}"
end
on_linux do
return prefix/"lib/python#{version.major_minor}"
end
end
def site_packages_cellar
lib_cellar/"site-packages"
end
# The HOMEBREW_PREFIX location of site-packages.
def site_packages
HOMEBREW_PREFIX/"lib/python#{version.major_minor}/site-packages"
end
def install
# Unset these so that installing pip and setuptools puts them where we want
# and not into some other Python the user has installed.
ENV["PYTHONHOME"] = nil
ENV["PYTHONPATH"] = nil
# Override the auto-detection in setup.py, which assumes a universal build.
on_macos do
ENV["PYTHON_DECIMAL_WITH_MACHINE"] = "x64"
end
args = %W[
--prefix=#{prefix}
--enable-ipv6
--datarootdir=#{share}
--datadir=#{share}
--enable-loadable-sqlite-extensions
--without-ensurepip
--with-openssl=#{Formula["[email protected]"].opt_prefix}
--with-system-libmpdec
]
args << "--without-gcc" if ENV.compiler == :clang
on_macos do
args << "--enable-framework=#{frameworks}"
args << "--with-dtrace"
end
on_linux do
args << "--enable-shared"
# Required for the _ctypes module
# see https://github.com/Linuxbrew/homebrew-core/pull/1007#issuecomment-252421573
args << "--with-system-ffi"
end
cflags = []
ldflags = []
cppflags = []
if MacOS.sdk_path_if_needed
# Help Python's build system (setuptools/pip) to build things on SDK-based systems
# The setup.py looks at "-isysroot" to get the sysroot (and not at --sysroot)
cflags << "-isysroot #{MacOS.sdk_path}"
ldflags << "-isysroot #{MacOS.sdk_path}"
# For the Xlib.h, Python needs this header dir with the system Tk
# Yep, this needs the absolute path where zlib needed a path relative
# to the SDK.
cflags << "-isystem #{MacOS.sdk_path}/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers"
end
# Avoid linking to libgcc https://mail.python.org/pipermail/python-dev/2012-February/116205.html
args << "MACOSX_DEPLOYMENT_TARGET=#{MacOS.version}"
# Python's setup.py parses CPPFLAGS and LDFLAGS to learn search
# paths for the dependencies of the compiled extension modules.
# See Linuxbrew/linuxbrew#420, Linuxbrew/linuxbrew#460, and Linuxbrew/linuxbrew#875
on_linux do
cppflags << ENV.cppflags << " -I#{HOMEBREW_PREFIX}/include"
ldflags << ENV.ldflags << " -L#{HOMEBREW_PREFIX}/lib"
end
# We want our readline! This is just to outsmart the detection code,
# superenv makes cc always find includes/libs!
inreplace "setup.py",
"do_readline = self.compiler.find_library_file(lib_dirs, 'readline')",
"do_readline = '#{Formula["readline"].opt_lib}/libhistory.dylib'"
inreplace "setup.py" do |s|
s.gsub! "sqlite_setup_debug = False", "sqlite_setup_debug = True"
s.gsub! "for d_ in inc_dirs + sqlite_inc_paths:",
"for d_ in ['#{Formula["sqlite"].opt_include}']:"
end
# Allow python modules to use ctypes.find_library to find homebrew's stuff
# even if homebrew is not a /usr/local/lib. Try this with:
# `brew install enchant && pip install pyenchant`
inreplace "./Lib/ctypes/macholib/dyld.py" do |f|
f.gsub! "DEFAULT_LIBRARY_FALLBACK = [", "DEFAULT_LIBRARY_FALLBACK = [ '#{HOMEBREW_PREFIX}/lib',"
f.gsub! "DEFAULT_FRAMEWORK_FALLBACK = [", "DEFAULT_FRAMEWORK_FALLBACK = [ '#{HOMEBREW_PREFIX}/Frameworks',"
end
args << "CFLAGS=#{cflags.join(" ")}" unless cflags.empty?
args << "LDFLAGS=#{ldflags.join(" ")}" unless ldflags.empty?
args << "CPPFLAGS=#{cppflags.join(" ")}" unless cppflags.empty?
system "./configure", *args
system "make"
ENV.deparallelize do
# Tell Python not to install into /Applications (default for framework builds)
system "make", "install", "PYTHONAPPSDIR=#{prefix}"
on_macos do
system "make", "frameworkinstallextras", "PYTHONAPPSDIR=#{pkgshare}"
end
end
# Any .app get a " 3" attached, so it does not conflict with python 2.x.
Dir.glob("#{prefix}/*.app") { |app| mv app, app.sub(/\.app$/, " 3.app") }
on_macos do
# Prevent third-party packages from building against fragile Cellar paths
inreplace Dir[lib_cellar/"**/_sysconfigdata_m_darwin_darwin.py",
lib_cellar/"config*/Makefile",
frameworks/"Python.framework/Versions/3*/lib/pkgconfig/python-3.?.pc"],
prefix, opt_prefix
# Help third-party packages find the Python framework
inreplace Dir[lib_cellar/"config*/Makefile"],
/^LINKFORSHARED=(.*)PYTHONFRAMEWORKDIR(.*)/,
"LINKFORSHARED=\\1PYTHONFRAMEWORKINSTALLDIR\\2"
# Fix for https://github.com/Homebrew/homebrew-core/issues/21212
inreplace Dir[lib_cellar/"**/_sysconfigdata_m_darwin_darwin.py"],
%r{('LINKFORSHARED': .*?)'(Python.framework/Versions/3.\d+/Python)'}m,
"\\1'#{opt_prefix}/Frameworks/\\2'"
end
on_linux do
# Prevent third-party packages from building against fragile Cellar paths
inreplace Dir[lib_cellar/"**/_sysconfigdata_m_linux_x86_64-*.py",
lib_cellar/"config*/Makefile",
lib/"pkgconfig/python-3.?.pc"],
prefix, opt_prefix
end
# Symlink the pkgconfig files into HOMEBREW_PREFIX so they're accessible.
(lib/"pkgconfig").install_symlink Dir["#{frameworks}/Python.framework/Versions/#{version.major_minor}/lib/pkgconfig/*"]
# Remove the site-packages that Python created in its Cellar.
site_packages_cellar.rmtree
%w[setuptools pip wheel importlib-metadata zipp].each do |r|
(libexec/r).install resource(r)
end
# Remove wheel test data.
# It's for people editing wheel and contains binaries which fail `brew linkage`.
rm libexec/"wheel/tox.ini"
rm_r libexec/"wheel/tests"
# Install unversioned symlinks in libexec/bin.
{
"idle" => "idle3",
"pydoc" => "pydoc3",
"python" => "python3",
"python-config" => "python3-config",
}.each do |unversioned_name, versioned_name|
(libexec/"bin").install_symlink (bin/versioned_name).realpath => unversioned_name
end
end
def post_install
ENV.delete "PYTHONPATH"
# Fix up the site-packages so that user-installed Python software survives
# minor updates, such as going from 3.3.2 to 3.3.3:
# Create a site-packages in HOMEBREW_PREFIX/lib/python#{version.major_minor}/site-packages
site_packages.mkpath
# Symlink the prefix site-packages into the cellar.
site_packages_cellar.unlink if site_packages_cellar.exist?
site_packages_cellar.parent.install_symlink site_packages
# Write our sitecustomize.py
rm_rf Dir["#{site_packages}/sitecustomize.py[co]"]
(site_packages/"sitecustomize.py").atomic_write(sitecustomize)
# Remove old setuptools installations that may still fly around and be
# listed in the easy_install.pth. This can break setuptools build with
# zipimport.ZipImportError: bad local file header
# setuptools-0.9.8-py3.3.egg
rm_rf Dir["#{site_packages}/setuptools*"]
rm_rf Dir["#{site_packages}/distribute*"]
rm_rf Dir["#{site_packages}/pip[-_.][0-9]*", "#{site_packages}/pip"]
%w[setuptools pip wheel importlib-metadata zipp].each do |pkg|
(libexec/pkg).cd do
system bin/"python3", "-s", "setup.py", "--no-user-cfg", "install",
"--force", "--verbose", "--install-scripts=#{bin}",
"--install-lib=#{site_packages}",
"--single-version-externally-managed",
"--record=installed.txt"
end
end
rm_rf [bin/"pip", bin/"easy_install"]
mv bin/"wheel", bin/"wheel3"
# Install unversioned symlinks in libexec/bin.
{
"pip" => "pip3",
"wheel" => "wheel3",
}.each do |unversioned_name, versioned_name|
(libexec/"bin").install_symlink (bin/versioned_name).realpath => unversioned_name
end
# Help distutils find brewed stuff when building extensions
include_dirs = [HOMEBREW_PREFIX/"include", Formula["[email protected]"].opt_include,
Formula["sqlite"].opt_include]
library_dirs = [HOMEBREW_PREFIX/"lib", Formula["[email protected]"].opt_lib,
Formula["sqlite"].opt_lib]
cfg = lib_cellar/"distutils/distutils.cfg"
cfg.atomic_write <<~EOS
[install]
prefix=#{HOMEBREW_PREFIX}
[build_ext]
include_dirs=#{include_dirs.join ":"}
library_dirs=#{library_dirs.join ":"}
EOS
end
def sitecustomize
<<~EOS
# This file is created by Homebrew and is executed on each python startup.
# Don't print from here, or else python command line scripts may fail!
# <https://docs.brew.sh/Homebrew-and-Python>
import re
import os
import sys
if sys.version_info[0] != 3:
# This can only happen if the user has set the PYTHONPATH for 3.x and run Python 2.x or vice versa.
# Every Python looks at the PYTHONPATH variable and we can't fix it here in sitecustomize.py,
# because the PYTHONPATH is evaluated after the sitecustomize.py. Many modules (e.g. PyQt4) are
# built only for a specific version of Python and will fail with cryptic error messages.
# In the end this means: Don't set the PYTHONPATH permanently if you use different Python versions.
exit('Your PYTHONPATH points to a site-packages dir for Python 3.x but you are running Python ' +
str(sys.version_info[0]) + '.x!\\n PYTHONPATH is currently: "' + str(os.environ['PYTHONPATH']) + '"\\n' +
' You should `unset PYTHONPATH` to fix this.')
# Only do this for a brewed python:
if os.path.realpath(sys.executable).startswith('#{rack}'):
# Shuffle /Library site-packages to the end of sys.path
library_site = '/Library/Python/#{version.major_minor}/site-packages'
library_packages = [p for p in sys.path if p.startswith(library_site)]
sys.path = [p for p in sys.path if not p.startswith(library_site)]
# .pth files have already been processed so don't use addsitedir
sys.path.extend(library_packages)
# the Cellar site-packages is a symlink to the HOMEBREW_PREFIX
# site_packages; prefer the shorter paths
long_prefix = re.compile(r'#{rack}/[0-9\._abrc]+/Frameworks/Python\.framework/Versions/#{version.major_minor}/lib/python#{version.major_minor}/site-packages')
sys.path = [long_prefix.sub('#{site_packages}', p) for p in sys.path]
# Set the sys.executable to use the opt_prefix. Only do this if PYTHONEXECUTABLE is not
# explicitly set and we are not in a virtualenv:
if 'PYTHONEXECUTABLE' not in os.environ and sys.prefix == sys.base_prefix:
sys.executable = '#{opt_bin}/python#{version.major_minor}'
EOS
end
def caveats
<<~EOS
Python has been installed as
#{opt_bin}/python3
Unversioned symlinks `python`, `python-config`, `pip` etc. pointing to
`python3`, `python3-config`, `pip3` etc., respectively, have been installed into
#{opt_libexec}/bin
You can install Python packages with
#{opt_bin}/pip3 install <package>
They will install into the site-package directory
#{HOMEBREW_PREFIX/"lib/python#{version.major_minor}/site-packages"}
See: https://docs.brew.sh/Homebrew-and-Python
EOS
end
test do
# Check if sqlite is ok, because we build with --enable-loadable-sqlite-extensions
# and it can occur that building sqlite silently fails if OSX's sqlite is used.
system "#{bin}/python#{version.major_minor}", "-c", "import sqlite3"
# Check if some other modules import. Then the linked libs are working.
on_macos do
# Temporary failure on macOS 11.1 due to https://bugs.python.org/issue42480
# Reenable unconditionnaly once Apple fixes the Tcl/Tk issue
system "#{bin}/python#{version.major_minor}", "-c", "import tkinter; root = tkinter.Tk()" if MacOS.full_version < "11.1"
end
system "#{bin}/python#{version.major_minor}", "-c", "import _decimal"
system "#{bin}/python#{version.major_minor}", "-c", "import _gdbm"
system "#{bin}/python#{version.major_minor}", "-c", "import zlib"
system bin/"pip3", "list", "--format=columns"
end
end
| 40.306931 | 168 | 0.681221 |
bf29f6bd43af5079a534de8e373a4cde9e8677ed | 119 | module HtmlComposite
class MapTag < Tag
def to_s
"<map#{attributes_list}>#{super}</map>"
end
end
end
| 14.875 | 45 | 0.630252 |
7a5210fac700bdce89162b1f4283d537fcfb7794 | 1,571 | RSpec.describe 'ValidatesTimeliness::Extensions::MultiparameterHandler' do
context "time column" do
it 'should be nil invalid date portion' do
employee = record_with_multiparameter_attribute(:birth_datetime, [2000, 2, 31, 12, 0, 0])
expect(employee.birth_datetime).to be_nil
end
it 'should assign a Time value for valid datetimes' do
employee = record_with_multiparameter_attribute(:birth_datetime, [2000, 2, 28, 12, 0, 0])
expect(employee.birth_datetime).to eq Time.zone.local(2000, 2, 28, 12, 0, 0)
end
it 'should be nil for incomplete date portion' do
employee = record_with_multiparameter_attribute(:birth_datetime, [2000, nil, nil])
expect(employee.birth_datetime).to be_nil
end
end
context "date column" do
it 'should assign nil for invalid date' do
employee = record_with_multiparameter_attribute(:birth_date, [2000, 2, 31])
expect(employee.birth_date).to be_nil
end
it 'should assign a Date value for valid date' do
employee = record_with_multiparameter_attribute(:birth_date, [2000, 2, 28])
expect(employee.birth_date).to eq Date.new(2000, 2, 28)
end
it 'should assign hash values for incomplete date' do
employee = record_with_multiparameter_attribute(:birth_date, [2000, nil, nil])
expect(employee.birth_date).to be_nil
end
end
def record_with_multiparameter_attribute(name, values)
hash = {}
values.each_with_index {|value, index| hash["#{name}(#{index+1}i)"] = value.to_s }
Employee.new(hash)
end
end
| 35.704545 | 95 | 0.707193 |
bf072162d9ee5dd85497c7d5238d1c5ec4729a04 | 1,891 | #
# Copyright:: 2015-2019, Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'rake'
SOURCE = File.join(File.dirname(__FILE__), '..', 'MAINTAINERS.toml')
TARGET = File.join(File.dirname(__FILE__), '..', 'MAINTAINERS.md')
begin
require 'tomlrb'
task default: 'maintainers:generate'
namespace :maintainers do
desc 'Generate MarkDown version of MAINTAINERS file'
task :generate do
@toml = Tomlrb.load_file SOURCE
out = "<!-- This is a generated file. Please do not edit directly -->\n\n"
out << preamble
out << project_lieutenant
out << all_maintainers
File.write(TARGET, out)
end
end
rescue LoadError
warn "\n*** TomlRb not available. Skipping the Maintainers Rake task\n\n"
end
private
def preamble
<<-EOL
# #{@toml['Preamble']['title']}
#{@toml['Preamble']['text']}
EOL
end
def project_lieutenant
<<-EOL
# #{@toml['Org']['Components']['Core']['title']}
#{github_link(@toml['Org']['Components']['Core']['lieutenant'])}
EOL
end
def all_maintainers
text = "# Maintainers\n"
@toml['Org']['Components']['Core']['maintainers'].each do |m|
text << "#{github_link(m)}\n"
end
text
end
def github_link(person)
name = @toml['people'][person]['name']
github = @toml['people'][person]['github']
"* [#{name}](https://github.com/#{github})"
end
| 25.554054 | 80 | 0.680592 |
e93465c9cb8b6d0df89aadbbbd25f84b08430e74 | 1,664 | require 'beaker-rspec/spec_helper'
require 'beaker-rspec/helpers/serverspec'
require 'beaker/puppet_install_helper'
run_puppet_install_helper
UNSUPPORTED_PLATFORMS = ['Suse','windows','AIX','Solaris']
RSpec.configure do |c|
# Project root
proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))
# Readable test descriptions
c.formatter = :documentation
# Configure all nodes in nodeset
c.before :suite do
# Install module and dependencies
hosts.each do |host|
copy_module_to(host, :source => proj_root, :module_name => 'apache')
# Required for mod_passenger tests.
if fact('osfamily') == 'RedHat'
on host, puppet('module','install','stahnma/epel'), { :acceptable_exit_codes => [0,1] }
end
# Required for manifest to make mod_pagespeed repository available
if fact('osfamily') == 'Debian'
on host, puppet('module','install','puppetlabs-apt', '--version 1.8.0', '--force'), { :acceptable_exit_codes => [0,1] }
end
on host, puppet('module','install','puppetlabs-stdlib'), { :acceptable_exit_codes => [0,1] }
on host, puppet('module','install','puppetlabs-concat', '--version 1.1.1', '--force'), { :acceptable_exit_codes => [0,1] }
# Make sure selinux is disabled before each test or apache won't work.
if ! UNSUPPORTED_PLATFORMS.include?(fact('osfamily'))
on host, puppet('apply', '-e',
%{"exec { 'setenforce 0': path => '/bin:/sbin:/usr/bin:/usr/sbin', onlyif => 'which setenforce && getenforce | grep Enforcing', }"}),
{ :acceptable_exit_codes => [0] }
end
end
end
end
| 40.585366 | 161 | 0.640625 |
ff57e845e538e6066f6ecd96f9619ba990940868 | 1,945 | # -*- encoding: utf-8 -*-
#
# Author:: Fletcher Nichol (<[email protected]>)
#
# Copyright (C) 2012, Fletcher Nichol
#
# 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 "rake/tasklib"
require "kitchen"
module Kitchen
# Kitchen Rake task generator.
#
# @author Fletcher Nichol <[email protected]>
class RakeTasks < ::Rake::TaskLib
# Creates Kitchen Rake tasks and allows the callee to configure it.
#
# @yield [self] gives itself to the block
def initialize(cfg = {})
@loader = Kitchen::Loader::YAML.new(
project_config: ENV["KITCHEN_YAML"],
local_config: ENV["KITCHEN_LOCAL_YAML"],
global_config: ENV["KITCHEN_GLOBAL_YAML"]
)
@config = Kitchen::Config.new(
{ loader: @loader }.merge(cfg)
)
Kitchen.logger = Kitchen.default_file_logger(nil, false)
yield self if block_given?
define
end
# @return [Config] a Kitchen::Config
attr_reader :config
private
# Generates a test Rake task for each instance and one to test all
# instances in serial.
#
# @api private
def define
namespace "kitchen" do
config.instances.each do |instance|
desc "Run #{instance.name} test instance"
task instance.name do
instance.test(:always)
end
end
desc "Run all test instances"
task "all" => config.instances.map(&:name)
end
end
end
end
| 28.188406 | 74 | 0.660668 |
61e781928626aa2e8267262125820ed1d28723a0 | 1,337 | require 'spec_helper'
describe Arrays do
context "empty array" do
it "should work" do
array = []
Arrays.sort_012(array)
array.should == []
end
end
context "only 0s" do
it "should work" do
array = [0, 0, 0, 0, 0]
Arrays.sort_012(array)
array.should == [0, 0, 0, 0, 0]
end
end
context "only 1s" do
it "should work" do
array = [1, 1, 1, 1, 1]
Arrays.sort_012(array)
array.should == [1, 1, 1, 1, 1]
end
end
context "only 2s" do
it "should work" do
array = [2, 2, 2, 2, 2]
Arrays.sort_012(array)
array.should == [2, 2, 2, 2, 2]
end
end
context "0s and 1s" do
it "should work" do
array = [1, 0, 0, 1, 0]
Arrays.sort_012(array)
array.should == [0, 0, 0, 1, 1]
end
end
context "1s and 2s" do
it "should work" do
array = [2, 1, 1, 2, 1]
Arrays.sort_012(array)
array.should == [1, 1, 1, 2, 2]
end
end
context "0s and 2s" do
it "should work" do
array = [2, 0, 0, 2, 0]
Arrays.sort_012(array)
array.should == [0, 0, 0, 2, 2]
end
end
context "0s, 1s and 2s" do
it "should work" do
array = [1, 1, 0, 2, 0, 0, 2, 1, 2, 0]
Arrays.sort_012(array)
array.should == [0, 0, 0, 0, 1, 1, 1, 2, 2, 2]
end
end
end
| 19.661765 | 52 | 0.513837 |
e22c390df1c3a150baf6d00df24b246ff3388c6e | 527 | require 'test_helper'
class SessionHelperTest < ActionView::TestCase
include SessionsHelper
def setup
@user = users(:derek)
remember(@user)
end
test "current_user returns right user when session is nil" do
assert_equal @user, current_user
assert is_logged_in?
end
test "current_user returns nul when remember digest is wrong" do
@user.update_attribute(:remember_digest, User.digest(User.new_token))
assert_nil current_user
end
end | 27.736842 | 78 | 0.671727 |
385dbf17e3b8683258de4c8e8aee1493b3ee5375 | 6,737 | require 'rubyXL'
require 'rubyXL/convenience_methods/cell'
module PolyPress
module Serializers
class Excel
send(:include, Dry::Monads[:result, :do])
send(:include, Dry::Monads[:try])
DATA_FEATURE_KEYS = %w(sheet page_group rows row cells checkboxes split_fields)
DERIVED_INPUT_KINDS = %w(checkboxes split_fields)
# @param[Dry::Struct] data (required)
# @param[String] form_namespace (required)
# @param[Dry::Container] registry
# @return [Dry::Monad::Result<PolyPress::Document>] document
def call(data:, form_namespace:, registry:)
@registry = registry
template = yield get_template(registry, form_namespace)
data_features = yield get_data_features(registry, form_namespace)
document = yield create(data, template, data_features, form_namespace)
Success(document)
end
private
def get_template(registry, form_namespace)
form_name = form_namespace.split('.')[-1]
template_feature = [form_name, 'template'].join('_')
template = registry[template_feature].item
Success(template)
end
def get_data_features(registry, form_namespace)
data_features = registry.features_by_namespace(form_namespace).collect do |feature_key|
feature = registry[feature_key]
feature if DATA_FEATURE_KEYS.include?(feature.item.to_s)
end.compact
Success(data_features)
end
def create(data, template, data_features, form_namespace)
sheet = data_features.detect{|feature| feature.item == :sheet}
sheet_namespaces = sheet.setting(:sheet_namespaces).item
workbook = RubyXL::Parser.parse(template)
sheet.setting(:data_elements).item.each do |index, elements|
form_name = sheet_namespaces[index]
features = data_features.select{|feature| elements.include?(feature.key.to_sym) }
worksheet_index = index
page_group_features = features.select{|feature| feature.item == :page_group}
if page_group_features.present?
feature = page_group_features[0]
if matched = feature.key.to_s.match(/^#{form_name}_(.*)$/)
page_group_data = data.send(matched[1]) rescue data
end
page_group_data.each do |page_data|
worksheet = workbook[worksheet_index]
derived_features = features.select{|feature| DERIVED_INPUT_KINDS.include?(feature.item.to_s) }
cell_features = features.select{|feature| feature.item == :cells}
worksheet = process_cell_features(worksheet, cell_features, data, form_name, derived_features)
worksheet = process_page_group(worksheet, page_data || data, feature, derived_features, form_name)
worksheet_index += 1
end
workbook.worksheets.delete(workbook["OSHA Form 300 (#{worksheet_index})"])
else
worksheet = workbook[index]
cell_features = features.select{|feature| feature.item == :cells}
derived_features = features.select{|feature| DERIVED_INPUT_KINDS.include?(feature.item.to_s) }
worksheet = process_cell_features(worksheet, cell_features, data, form_name, derived_features)
end
end
file = workbook.write("tmp/#{template.to_s.split(/\//)[-1]}")
Success(file)
end
def process_cell_features(worksheet, cell_features, data, form_name, derived_features)
cell_features.each do |feature|
if matched = feature.key.to_s.match(/^#{form_name}_(.*)$/)
feature_data = data.send(matched[1]) rescue data
end
worksheet = populate_cells(worksheet, feature_data || data, feature, derived_features)
end
worksheet
end
def populate_cells(worksheet, data, feature, derived_features, begin_index = nil)
feature.settings.each do |setting|
value = fetch_value(setting.key.to_s, data)
if value.to_s.present?
value = parse_dates(value)
if setting.item.is_a?(Hash)
setting_location = setting.item
else
derived_input_keys = setting.item.split('.')
derived_feature = derived_features.detect{|feature| feature.item == derived_input_keys[0].to_sym }
setting = derived_feature.setting(derived_input_keys[1..-1].join('.'))
derived_feature_type = derived_feature.item
if derived_feature_type == :split_fields
value = data.send(derived_input_keys[-1])
cells = setting.item[:cells]
cells[(cells.length - value.length)..-1].each_with_index do |points, index|
worksheet.sheet_data[points[0]][points[1]].change_contents(value[index])
end
next
else
setting_location = setting.item[(boolean?(value) ? value : value.to_sym)]
if derived_feature_type == :checkboxes
value = 'X'
end
end
end
points = setting_location[:cell]
worksheet.sheet_data[begin_index || points[0]][points[1]].change_contents(value)
end
end
worksheet
end
def process_page_group(worksheet, data, feature, derived_features, form_name)
feature.setting(:sections).item.each do |feature_key|
section_feature = @registry[feature_key]
if section_feature.item == :rows
rows = []
if matched = section_feature.key.to_s.match(/^#{form_name}_(.*)$/)
rows = data.send(matched[1]) rescue data
end
begin_index = section_feature.setting(:begin_row_index).item
row_feature = @registry[section_feature.setting(:row).item]
rows.each do |row|
worksheet = populate_cells(worksheet, row, row_feature, derived_features, begin_index)
begin_index += 1
end
end
end
worksheet
end
def fetch_value(attribute, data)
attributes = attribute.split('.')
if attributes.count > 1
fetch_value(attributes[1..-1].join('.'), data.send(attributes[0]))
else
data.send(attributes[0])
end
end
def boolean?(value)
value.is_a?(TrueClass) || value.is_a?(FalseClass)
end
def parse_dates(value)
if value.is_a?(Date)
value.strftime('%m/%d/%Y')
elsif value.is_a?(DateTime)
value
else
value
end
end
end
end
end
| 35.645503 | 113 | 0.614814 |
bfdfa767d3d78d7a7c181bb91c5fe9cff94d4aa5 | 2,991 | #-- encoding: UTF-8
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2020 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
# rubocop:disable MethodName
class Authorization::QueryTransformationVisitor < Arel::Visitors::Visitor
attr_accessor :transformations,
:args
def initialize(transformations:,
args:)
self.transformations = transformations
self.args = args
super()
end
def accept(ast)
applied_transformations.clear
super
end
private
def visit_Arel_SelectManager(ast)
ast = replace_if_equals(ast, :all)
ast.join_sources.each do |join_source|
visit join_source
end
end
def visit_Arel_Nodes_OuterJoin(ast)
visit ast.right
end
def visit_Arel_Nodes_On(ast)
ast.expr = replace_if_equals(ast.expr)
visit ast.expr
end
def visit_Arel_Nodes_Grouping(ast)
ast.expr = replace_if_equals(ast.expr)
visit ast.expr
end
def visit_Arel_Nodes_Or(ast)
ast.left = replace_if_equals(ast.left)
visit ast.left
ast.right = replace_if_equals(ast.right)
visit ast.right
end
def visit_Arel_Nodes_And(ast)
ast.children.each_with_index do |_, i|
ast.children[i] = replace_if_equals(ast.children[i])
visit ast.children[i]
end
end
def method_missing(name, *args, &block)
super unless name.to_s.start_with?('visit_')
end
def replace_if_equals(ast, key = nil)
if applicable_transformation?(key || ast)
transformations.for(key || ast).each do |transformation|
ast = transformation.apply(ast, *args)
end
end
ast
end
def applicable_transformation?(key)
if transformations.for?(key) && !applied_transformations.include?(key)
applied_transformations << key
true
else
false
end
end
def applied_transformations
@applied_transformations ||= []
end
end
| 24.516393 | 91 | 0.715145 |
87338488ebac7bcbf8f330c1637e04933daedcc7 | 5,317 | # frozen_string_literal: true
class Import::BitbucketServerController < Import::BaseController
before_action :verify_bitbucket_server_import_enabled
before_action :bitbucket_auth, except: [:new, :configure]
before_action :validate_import_params, only: [:create]
# As a basic sanity check to prevent URL injection, restrict project
# repository input and repository slugs to allowed characters. For Bitbucket:
#
# Project keys must start with a letter and may only consist of ASCII letters, numbers and underscores (A-Z, a-z, 0-9, _).
#
# Repository names are limited to 128 characters. They must start with a
# letter or number and may contain spaces, hyphens, underscores, and periods.
# (https://community.atlassian.com/t5/Answers-Developer-Questions/stash-repository-names/qaq-p/499054)
VALID_BITBUCKET_CHARS = /\A[\w\-_\.\s]+\z/
def new
end
def create
repo = bitbucket_client.repo(@project_key, @repo_slug)
unless repo
return render json: { errors: "Project #{@project_key}/#{@repo_slug} could not be found" }, status: :unprocessable_entity
end
project_name = params[:new_name].presence || repo.name
namespace_path = params[:new_namespace].presence || current_user.username
target_namespace = find_or_create_namespace(namespace_path, current_user)
if current_user.can?(:create_projects, target_namespace)
project = Gitlab::BitbucketServerImport::ProjectCreator.new(@project_key, @repo_slug, repo, project_name, target_namespace, current_user, credentials).execute
if project.persisted?
render json: ProjectSerializer.new.represent(project)
else
render json: { errors: project_save_error(project) }, status: :unprocessable_entity
end
else
render json: { errors: 'This namespace has already been taken! Please choose another one.' }, status: :unprocessable_entity
end
rescue BitbucketServer::Connection::ConnectionError => e
render json: { errors: "Unable to connect to server: #{e}" }, status: :unprocessable_entity
end
def configure
session[personal_access_token_key] = params[:personal_access_token]
session[bitbucket_server_username_key] = params[:bitbucket_username]
session[bitbucket_server_url_key] = params[:bitbucket_server_url]
redirect_to status_import_bitbucket_server_path
end
# rubocop: disable CodeReuse/ActiveRecord
def status
@collection = bitbucket_client.repos(page_offset: page_offset, limit: limit_per_page)
@repos, @incompatible_repos = @collection.partition { |repo| repo.valid? }
# Use the import URL to filter beyond what BaseService#find_already_added_projects
@already_added_projects = filter_added_projects('bitbucket_server', @repos.map(&:browse_url))
already_added_projects_names = @already_added_projects.pluck(:import_source)
@repos.reject! { |repo| already_added_projects_names.include?(repo.browse_url) }
rescue BitbucketServer::Connection::ConnectionError => e
flash[:alert] = "Unable to connect to server: #{e}"
clear_session_data
redirect_to new_import_bitbucket_server_path
end
# rubocop: enable CodeReuse/ActiveRecord
def jobs
render json: find_jobs('bitbucket_server')
end
private
# rubocop: disable CodeReuse/ActiveRecord
def filter_added_projects(import_type, import_sources)
current_user.created_projects.where(import_type: import_type, import_source: import_sources).includes(:import_state)
end
# rubocop: enable CodeReuse/ActiveRecord
def bitbucket_client
@bitbucket_client ||= BitbucketServer::Client.new(credentials)
end
def validate_import_params
@project_key = params[:project]
@repo_slug = params[:repository]
return render_validation_error('Missing project key') unless @project_key.present? && @repo_slug.present?
return render_validation_error('Missing repository slug') unless @repo_slug.present?
return render_validation_error('Invalid project key') unless @project_key =~ VALID_BITBUCKET_CHARS
return render_validation_error('Invalid repository slug') unless @repo_slug =~ VALID_BITBUCKET_CHARS
end
def render_validation_error(message)
render json: { errors: message }, status: :unprocessable_entity
end
def bitbucket_auth
unless session[bitbucket_server_url_key].present? &&
session[bitbucket_server_username_key].present? &&
session[personal_access_token_key].present?
redirect_to new_import_bitbucket_server_path
end
end
def verify_bitbucket_server_import_enabled
render_404 unless bitbucket_server_import_enabled?
end
def bitbucket_server_url_key
:bitbucket_server_url
end
def bitbucket_server_username_key
:bitbucket_server_username
end
def personal_access_token_key
:bitbucket_server_personal_access_token
end
def clear_session_data
session[bitbucket_server_url_key] = nil
session[bitbucket_server_username_key] = nil
session[personal_access_token_key] = nil
end
def credentials
{
base_uri: session[bitbucket_server_url_key],
user: session[bitbucket_server_username_key],
password: session[personal_access_token_key]
}
end
def page_offset
[0, params[:page].to_i].max
end
def limit_per_page
BitbucketServer::Paginator::PAGE_LENGTH
end
end
| 35.925676 | 164 | 0.7634 |
1aef7569b03f6fe746d4b214eb3bad99a0a2be2f | 2,864 | module Pod
class ConfigureIOS
attr_reader :configurator
def self.perform(options)
new(options).perform
end
def initialize(options)
@configurator = options.fetch(:configurator)
end
def perform
# keep_demo = configurator.ask_with_answers("Would you like to include a demo application with your library", ["Yes", "No"]).to_sym
puts "include a demo application with your library"
keep_demo = :yes
# framework = configurator.ask_with_answers("Which testing frameworks will you use", ["Specta", "Kiwi", "None"]).to_sym
puts "testing frameworks will you use none"
framework = :none
case framework
when :specta
configurator.add_pod_to_podfile "Specta"
configurator.add_pod_to_podfile "Expecta"
configurator.add_line_to_pch "@import Specta;"
configurator.add_line_to_pch "@import Expecta;"
configurator.set_test_framework("specta", "m", "ios")
when :kiwi
configurator.add_pod_to_podfile "Kiwi"
configurator.add_line_to_pch "@import Kiwi;"
configurator.set_test_framework("kiwi", "m", "ios")
when :none
configurator.set_test_framework("xctest", "m", "ios")
end
# snapshots = configurator.ask_with_answers("Would you like to do view based testing", ["Yes", "No"]).to_sym
puts "Would you like to do view based testing: No"
snapshots = :no
case snapshots
when :yes
configurator.add_pod_to_podfile "FBSnapshotTestCase"
configurator.add_line_to_pch "@import FBSnapshotTestCase;"
if keep_demo == :no
puts " Putting demo application back in, you cannot do view tests without a host application."
keep_demo = :yes
end
if framework == :specta
configurator.add_pod_to_podfile "Expecta+Snapshots"
configurator.add_line_to_pch "@import Expecta_Snapshots;"
end
end
prefix = nil
loop do
# prefix = configurator.ask("What is your class prefix")
prefix = "KY"
if prefix.include?(' ')
puts 'Your class prefix cannot contain spaces.'.red
else
break
end
end
Pod::ProjectManipulator.new({
:configurator => @configurator,
:xcodeproj_path => "templates/ios/Example/PROJECT.xcodeproj",
:classes_path => "Pod/Classes/.gitkeep",
:platform => :ios,
:remove_demo_project => (keep_demo == :no),
:prefix => prefix
}).run
# There has to be a single file in the Classes dir
# or a framework won't be created, which is now default
# `touch Pod/Classes/ReplaceMe.m`
`mv ./templates/ios/* ./`
# remove podspec for osx
`rm ./NAME-osx.podspec`
end
end
end
| 30.468085 | 137 | 0.622905 |
79b5d4eae6d2baa05fe0a2cf8ada06161ec31594 | 1,093 | require 'rails'
require 'redcarpet'
require 'omniauth'
require 'omniauth-shibboleth'
# require 'omniauth-google-oauth2'
require 'omniauth-orcid'
require 'jquery-rails'
require 'jquery-ui-rails'
require 'jquery-turbolinks'
require 'filesize'
require 'kaminari'
require 'amoeba'
require 'font-awesome-rails'
require 'stash_engine/engine'
require 'stash/repo'
require 'stash/event_data'
require 'stash/datacite_metadata'
module StashEngine
class Engine < ::Rails::Engine
isolate_namespace StashEngine
config.autoload_paths << File.expand_path('lib/stash/doi', __dir__)
config.autoload_paths << File.expand_path('lib/stash/indexer', __dir__)
config.autoload_paths << File.expand_path('lib/stash/payments', __dir__)
config.autoload_paths << File.expand_path('lib/stash/download', __dir__)
# :nocov:
initializer :append_migrations do |app|
unless app.root.to_s.match?(root.to_s)
config.paths['db/migrate'].expanded.each do |expanded_path|
app.config.paths['db/migrate'] << expanded_path
end
end
end
# :nocov:
end
end
| 27.325 | 76 | 0.730101 |
e990fab304b9224dfc64494f5be649fa7e861cab | 138 | # frozen_string_literal: true
module Cropio
module Resources
class ProductivityEstimate < Cropio::Resource::Base
end
end
end
| 15.333333 | 55 | 0.753623 |
7a48897b7fdfaad3ad3a2617751e56b4c2fc3a64 | 6,437 | require "spec_helper"
return unless defined?(Sequel)
require "mobility/plugins/sequel/column_fallback"
describe Mobility::Plugins::Sequel::ColumnFallback, orm: :sequel, type: :plugin do
plugins :sequel, :backend, :reader, :writer, :column_fallback
let(:model_class) do
stub_const 'Article', Class.new(Sequel::Model)
Article.dataset = DB[:articles]
Article.include translations
Article
end
context "column_fallback: true" do
plugin_setup :slug, column_fallback: true
it "reads/writes from/to model column if locale is I18n.default_locale" do
instance[:slug] = "foo"
Mobility.with_locale(:en) do
expect(instance.slug).to eq("foo")
instance.slug = "bar"
expect(instance.slug).to eq("bar")
expect(instance[:slug]).to eq("bar")
end
end
it "reads/writes from/to backend if locale is not I18n.default_locale" do
instance[:slug] = "foo"
Mobility.with_locale(:fr) do
expect(listener).to receive(:read).with(:fr, any_args).and_return("bar")
expect(instance.slug).to eq("bar")
expect(listener).to receive(:write).with(:fr, "baz", any_args)
instance.slug = "baz"
end
end
end
locales = [:de, :ja]
context "column_fallback: #{locales.inspect}" do
plugin_setup :slug, column_fallback: locales
it "reads/writes from/to model column if locale is locales array" do
locales.each do |locale|
instance[:slug] = "foo"
Mobility.with_locale(locale) do
expect(instance.slug).to eq("foo")
instance.slug = "bar"
expect(instance.slug).to eq("bar")
expect(instance[:slug]).to eq("bar")
end
end
end
it "reads/writes from/to backend if locale is not in locales array" do
instance[:slug] = "foo"
Mobility.with_locale(:fr) do
expect(listener).to receive(:read).with(:fr, any_args).and_return("bar")
expect(instance.slug).to eq("bar")
expect(listener).to receive(:write).with(:fr, "baz", any_args)
instance.slug = "baz"
end
end
end
context "column_fallback: ->(locale) { locale == :de }" do
plugin_setup :slug, column_fallback: ->(locale) { locale == :de }
it "reads/writes from/to model column if proc returns false" do
instance[:slug] = "foo"
Mobility.with_locale(:de) do
expect(instance.slug).to eq("foo")
instance.slug = "bar"
expect(instance.slug).to eq("bar")
expect(instance[:slug]).to eq("bar")
end
end
it "reads/writes from/to backend if proc returns true" do
instance[:slug] = "foo"
Mobility.with_locale(:fr) do
expect(listener).to receive(:read).with(:fr, any_args).and_return("bar")
expect(instance.slug).to eq("bar")
expect(listener).to receive(:write).with(:fr, "baz", any_args)
instance.slug = "baz"
end
end
end
describe "querying" do
# need to include because Sequel KeyValue backend depends on it, and we're
# using that backend in tests below
plugins :sequel, :writer, :query, :cache, :column_fallback
let(:model_class) do
stub_const 'Article', Class.new(Sequel::Model)
Article.dataset = DB[:articles]
Article
end
context "column_fallback: true" do
before do
translates model_class, :slug, backend: [:key_value, type: :string], column_fallback: true
end
it "queries on model column if locale is I18n.default_locale" do
instance1 = model_class.new
instance1[:slug] = "foo"
instance1.save
instance2 = model_class.new
Mobility.with_locale(:fr) { instance2.slug = "bar" }
instance2.save
expect(model_class.i18n.where(slug: "foo", locale: :en).select_all(:articles).all).to match_array([instance1])
expect(model_class.i18n.where(slug: "foo", locale: :fr).select_all(:articles).all).to eq([])
expect(model_class.i18n.where(slug: "bar", locale: :fr).select_all(:articles).all).to eq([instance2])
expect(model_class.i18n.where(slug: "bar", locale: :en).select_all(:articles).all).to eq([])
end
end
locales = [:de, :ja]
context "column_fallback: #{locales.inspect}" do
before do
translates model_class, :slug, backend: [:key_value, type: :string], column_fallback: locales
end
it "queries on model column if locale is locales array" do
instance1 = model_class.new
Mobility.with_locale(:de) { instance1.slug = "foo" }
instance1.save
instance2 = model_class.new
Mobility.with_locale(:ja) { instance2.slug = "bar" }
instance2.save
instance3 = model_class.new
Mobility.with_locale(:en) { instance3.slug = "baz" }
instance3.save
expect(model_class.i18n.where(slug: "foo", locale: :de).select_all(:articles).all).to eq([instance1])
expect(model_class.i18n.where(slug: "foo", locale: :en).select_all(:articles).all).to eq([])
expect(model_class.i18n.where(slug: "bar", locale: :ja).select_all(:articles).all).to eq([instance2])
expect(model_class.i18n.where(slug: "bar", locale: :en).select_all(:articles).all).to eq([])
expect(model_class.i18n.where(slug: "baz", locale: :en).select_all(:articles).all).to eq([instance3])
expect(model_class.i18n.where(slug: "baz", locale: :de).select_all(:articles).all).to eq([])
end
end
context "column_fallback: ->(locale) { locale == :de }" do
before do
translates model_class, :slug, backend: [:key_value, type: :string], column_fallback: ->(locale) { locale == :de }
end
it "queries on model column if proc returns false" do
instance1 = model_class.new
Mobility.with_locale(:de) { instance1.slug = "foo" }
instance1.save
instance2 = model_class.new
Mobility.with_locale(:ja) { instance2.slug = "bar" }
instance2.save
expect(model_class.i18n.where(slug: "foo", locale: :de).select_all(:articles).all).to eq([instance1])
expect(model_class.i18n.where(slug: "foo", locale: :ja).select_all(:articles).all).to eq([])
expect(model_class.i18n.where(slug: "bar", locale: :ja).select_all(:articles).all).to eq([instance2])
expect(model_class.i18n.where(slug: "bar", locale: :de).select_all(:articles).all).to eq([])
end
end
end
end
| 35.174863 | 122 | 0.63803 |
f895b8d30cd70a6e40c2b1e9816a0b0db036af99 | 144 | # frozen_string_literal: true
json.extract! widget, :id, :name, :slug, :content, :design_id
json.url backend_widget_url(widget, format: :json)
| 28.8 | 61 | 0.756944 |
6148b5a8d335cbf1253bd520f6c060e24cd1e1a0 | 224 | require 'sidekiq/testing'
# https://github.com/mperham/sidekiq/wiki/Testing#testing-worker-queueing-fake
Sidekiq::Testing.fake!
RSpec.configure do |config|
config.before(:each) do
Sidekiq::Worker.clear_all
end
end
| 20.363636 | 78 | 0.763393 |
5d9aafb708dc362dde907199205f1b494ef24c2a | 882 | Pod::Spec.new do |s|
s.name = 'FacebookImagePicker'
s.version = '2.0.11'
s.license = 'MIT'
s.summary = 'An image/photo picker for Facebook albums & photos modelled after UIImagePickerController'
s.author = { "Deon Botha" => "[email protected]" }
s.social_media_url = 'https://twitter.com/dbotha'
s.homepage = 'https://github.com/OceanLabs/FacebookImagePicker-iOS'
s.platform = :ios, '7.0'
s.requires_arc = true
s.source = {
:git => 'https://github.com/OceanLabs/FacebookImagePicker-iOS.git',
:tag => s.version.to_s
}
s.source_files = ['FacebookImagePicker/OL*.{h,m}', 'FacebookImagePicker/UIImageView+FacebookFadeIn.{h,m}']
s.resources = ['FacebookImagePicker/FacebookImagePicker.xcassets', 'FacebookImagePicker/*.xib']
s.dependency 'FBSDKCoreKit', '~> 4.11.0'
s.dependency 'FBSDKLoginKit', '~> 4.11.0'
end
| 44.1 | 110 | 0.668934 |
acfee31474e811f0066fc179691712272fd43ce9 | 37,152 | require 'spec_helper'
describe ActiveHash, "Base" do
before do
class Country < ActiveHash::Base
end
end
after do
Object.send :remove_const, :Country
end
it "passes LocalJumpError through in .transaction when no block is given" do
expect { Country.transaction }.to raise_error(LocalJumpError)
end
describe ".new" do
it "yields a block" do
expect { |b| Country.new(&b) }.to yield_with_args(Country)
end
context "initializing with a block" do
subject do
Country.fields :name
Country.new do |country|
country.name = 'Germany'
end
end
it "sets assigns the fields" do
expect(subject.name).to eq('Germany')
end
end
end
describe ".fields" do
before do
Country.fields :name, :iso_name
end
it "defines a reader for each field" do
Country.new.should respond_to(:name)
Country.new.should respond_to(:iso_name)
end
it "defines interrogator methods for each field" do
Country.new.should respond_to(:name?)
Country.new.should respond_to(:iso_name?)
end
it "defines single finder methods for each field" do
Country.should respond_to(:find_by_name)
Country.should respond_to(:find_by_iso_name)
end
it "defines banged single finder methods for each field" do
Country.should respond_to(:find_by_name!)
Country.should respond_to(:find_by_iso_name!)
end
it "defines array finder methods for each field" do
Country.should respond_to(:find_all_by_name)
Country.should respond_to(:find_all_by_iso_name)
end
it "does not define banged array finder methods for each field" do
Country.should_not respond_to(:find_all_by_name!)
Country.should_not respond_to(:find_all_by_iso_name!)
end
it "defines single finder methods for all combinations of fields" do
Country.should respond_to(:find_by_name_and_iso_name)
Country.should respond_to(:find_by_iso_name_and_name)
end
it "defines banged single finder methods for all combinations of fields" do
Country.should respond_to(:find_by_name_and_iso_name!)
Country.should respond_to(:find_by_iso_name_and_name!)
end
it "defines array finder methods for all combinations of fields" do
Country.should respond_to(:find_all_by_name_and_iso_name)
Country.should respond_to(:find_all_by_iso_name_and_name)
end
it "does not define banged array finder methods for all combinations of fields" do
Country.should_not respond_to(:find_all_by_name_and_iso_name!)
Country.should_not respond_to(:find_all_by_iso_name_and_name!)
end
it "allows you to pass options to the built-in find_by_* methods (but ignores the hash for now)" do
Country.find_by_name("Canada", :select => nil).should be_nil
Country.find_all_by_name("Canada", :select => nil).should == []
end
it "allows you to pass options to the custom find_by_* methods (but ignores the hash for now)" do
Country.find_by_name_and_iso_name("Canada", "CA", :select => nil).should be_nil
Country.find_all_by_name_and_iso_name("Canada", "CA", :select => nil).should == []
end
it "blows up if you try to overwrite :attributes" do
proc do
Country.field :attributes
end.should raise_error(ActiveHash::ReservedFieldError)
end
end
describe ".data=" do
before do
class Region < ActiveHash::Base
field :description
end
end
it "populates the object with data and auto-assigns keys" do
Country.data = [{:name => "US"}, {:name => "Canada"}]
Country.data.should == [{:name => "US", :id => 1}, {:name => "Canada", :id => 2}]
end
it "allows each of it's subclasses to have it's own data" do
Country.data = [{:name => "US"}, {:name => "Canada"}]
Region.data = [{:description => "A big region"}, {:description => "A remote region"}]
Country.data.should == [{:name => "US", :id => 1}, {:name => "Canada", :id => 2}]
Region.data.should == [{:description => "A big region", :id => 1}, {:description => "A remote region", :id => 2}]
end
it "marks the class as dirty" do
Country.dirty.should be_falsey
Country.data = []
Country.dirty.should be_truthy
end
end
describe ".add" do
before do
Country.fields :name
end
it "adds a record" do
proc {
Country.add :name => "Russia"
}.should change { Country.count }
end
it "marks the class as dirty" do
Country.dirty.should be_falsey
Country.add :name => "Russia"
Country.dirty.should be_truthy
end
it "returns the record" do
record = Country.add :name => "Russia"
record.name.should == "Russia"
end
it "should populate the id" do
record = Country.add :name => "Russia"
record.id.should_not be_nil
end
end
describe ".all" do
before do
Country.field :name
Country.data = [
{:id => 1, :name => "US"},
{:id => 2, :name => "Canada"}
]
end
it "returns an empty array if data is nil" do
Country.data = nil
Country.all.should be_empty
end
it "returns all data as inflated objects" do
Country.all.all? { |country| country.should be_kind_of(Country) }
end
it "populates the data correctly" do
records = Country.all
records.first.id.should == 1
records.first.name.should == "US"
records.last.id.should == 2
records.last.name.should == "Canada"
end
it "re-populates the records after data= is called" do
Country.data = [
{:id => 45, :name => "Canada"}
]
records = Country.all
records.first.id.should == 45
records.first.name.should == "Canada"
records.length.should == 1
end
it "filters the records from a AR-like conditions hash" do
record = Country.all(:conditions => {:name => 'US'})
record.count.should == 1
record.first.id.should == 1
record.first.name.should == 'US'
end
end
describe ".where" do
before do
Country.field :name
Country.field :language
Country.data = [
{:id => 1, :name => "US", :language => 'English'},
{:id => 2, :name => "Canada", :language => 'English'},
{:id => 3, :name => "Mexico", :language => 'Spanish'}
]
end
it "returns WhereChain class if no conditions are provided" do
Country.where.class.should == ActiveHash::Base::WhereChain
end
it "returns all records when passed nil" do
Country.where(nil).should == Country.all
end
it "returns all records when an empty hash" do
Country.where({}).should == Country.all
end
it "returns all data as inflated objects" do
Country.where(:language => 'English').all? { |country| country.should be_kind_of(Country) }
end
it "populates the data correctly" do
records = Country.where(:language => 'English')
records.first.id.should == 1
records.first.name.should == "US"
records.last.id.should == 2
records.last.name.should == "Canada"
end
it "re-populates the records after data= is called" do
Country.data = [
{:id => 45, :name => "Canada"}
]
records = Country.where(:name => 'Canada')
records.first.id.should == 45
records.first.name.should == "Canada"
records.length.should == 1
end
it "filters the records from a AR-like conditions hash" do
record = Country.where(:name => 'US')
record.count.should == 1
record.first.id.should == 1
record.first.name.should == 'US'
end
it "raises an error if ids aren't unique" do
proc do
Country.data = [
{:id => 1, :name => "US", :language => 'English'},
{:id => 2, :name => "Canada", :language => 'English'},
{:id => 2, :name => "Mexico", :language => 'Spanish'}
]
end.should raise_error(ActiveHash::IdError)
end
it "returns a record for specified id" do
record = Country.where(id: 1)
record.first.id.should == 1
record.first.name.should == 'US'
end
it "returns empty array" do
expect(Country.where(id: nil)).to eq []
end
it "returns multiple records for multiple ids" do
expect(Country.where(:id => %w(1 2)).map(&:id)).to match_array([1,2])
end
it "filters records for multiple values" do
expect(Country.where(:name => %w(US Canada)).map(&:name)).to match_array(%w(US Canada))
end
it "filters records for multiple symbol values" do
expect(Country.where(:name => [:US, :Canada]).map(&:name)).to match_array(%w(US Canada))
end
end
describe ".where.not" do
before do
Country.field :name
Country.field :language
Country.data = [
{:id => 1, :name => "US", :language => 'English'},
{:id => 2, :name => "Canada", :language => 'English'},
{:id => 3, :name => "Mexico", :language => 'Spanish'}
]
end
it "raises ArgumentError if no conditions are provided" do
lambda{
Country.where.not
}.should raise_error(ArgumentError)
end
it "returns all records when passed nil" do
Country.where.not(nil).should == Country.all
end
it "returns all records when an empty hash" do
Country.where.not({}).should == Country.all
end
it "returns all records as inflated objects" do
Country.where.not(:language => 'English').all? { |country| country.should be_kind_of(Country) }
end
it "populates the records correctly" do
records = Country.where.not(:language => 'Spanish')
records.first.id.should == 1
records.first.name.should == "US"
records.last.id.should == 2
records.last.name.should == "Canada"
records.length.should == 2
end
it "re-populates the records after data= is called" do
Country.data = [
{:id => 45, :name => "Canada"}
]
records = Country.where.not(:name => "US")
records.first.id.should == 45
records.first.name.should == "Canada"
records.length.should == 1
end
it "filters the records from a AR-like conditions hash" do
record = Country.where.not(:name => 'US')
record.first.id.should == 2
record.first.name.should == 'Canada'
record.last.id.should == 3
record.last.name.should == 'Mexico'
record.length.should == 2
end
it "returns the records for NOT specified id" do
record = Country.where.not(id: 1)
record.first.id.should == 2
record.first.name.should == 'Canada'
record.last.id.should == 3
record.last.name.should == 'Mexico'
end
it "returns all records when id is nil" do
expect(Country.where.not(:id => nil)).to eq Country.all
end
it "filters records for multiple ids" do
expect(Country.where.not(:id => [1, 2]).pluck(:id)).to match_array([3])
end
it "filters records for multiple values" do
expect(Country.where.not(:name => %w[US Canada]).pluck(:name)).to match_array(%w[Mexico])
end
it "filters records for multiple symbol values" do
expect(Country.where.not(:name => %i[US Canada]).pluck(:name)).to match_array(%w[Mexico])
end
it "filters records for multiple conditions" do
expect(Country.where.not(:id => 1, :name => 'Mexico')).to match_array([Country.find(2)])
end
end
describe ".find_by" do
before do
Country.field :name
Country.field :language
Country.data = [
{:id => 1, :name => "US", :language => 'English'},
{:id => 2, :name => "Canada", :language => 'English'},
{:id => 3, :name => "Mexico", :language => 'Spanish'}
]
end
it "raises ArgumentError if no conditions are provided" do
lambda{
Country.find_by
}.should raise_error(ArgumentError)
end
it "returns first record when passed nil" do
Country.find_by(nil).should == Country.first
end
it "returns all data as inflated objects" do
Country.find_by(:language => 'English').should be_kind_of(Country)
end
it "populates the data correctly" do
record = Country.find_by(:language => 'English')
record.id.should == 1
record.name.should == "US"
end
it "re-populates the records after data= is called" do
Country.data = [
{:id => 45, :name => "Canada"}
]
record = Country.find_by(:name => 'Canada')
record.id.should == 45
record.name.should == "Canada"
end
it "filters the records from a AR-like conditions hash" do
record = Country.find_by(:name => 'US')
record.id.should == 1
record.name.should == 'US'
end
it "finds the record with the specified id as a string" do
record = Country.find_by(:id => '1')
record.name.should == 'US'
end
it "returns the record that matches options" do
expect(Country.find_by(:name => "US").id).to eq(1)
end
it "returns the record that matches options with symbol value" do
expect(Country.find_by(:name => :US).id).to eq(1)
end
it "returns nil when not matched in candidates" do
expect(Country.find_by(:name => "UK")).to be_nil
end
it "returns nil when passed a wrong id" do
expect(Country.find_by(:id => 4)).to be_nil
end
end
describe ".find_by!" do
before do
Country.field :name
Country.field :language
Country.data = [
{:id => 1, :name => "US", :language => 'English'}
]
end
subject { Country.find_by!(name: word) }
context 'when data exists' do
let(:word) { 'US' }
it { expect(subject.id).to eq 1 }
end
context 'when data not found' do
let(:word) { 'UK' }
it { expect{ subject }.to raise_error ActiveHash::RecordNotFound }
it "raises 'RecordNotFound' when passed a wrong id" do
expect { Country.find_by!(id: 2) }.
to raise_error ActiveHash::RecordNotFound
end
it "raises 'RecordNotFound' when passed wrong id and options" do
expect { Country.find_by!(id: 2, name: "FR") }.
to raise_error ActiveHash::RecordNotFound
end
end
end
describe ".count" do
before do
Country.data = [
{:id => 1, :name => "US"},
{:id => 2, :name => "Canada"}
]
end
it "returns the number of elements in the array" do
Country.count.should == 2
end
end
describe ".pluck" do
before do
Country.data = [
{:id => 1, :name => "US"},
{:id => 2, :name => "Canada"}
]
end
it "returns an two dimensional Array of attributes values" do
expect(Country.pluck(:id, :name)).to match_array([[1,"US"], [2, "Canada"]])
end
it "returns an Array of attribute values" do
expect(Country.pluck(:id)).to match_array([1,2])
end
end
describe ".first" do
before do
Country.data = [
{:id => 1, :name => "US"},
{:id => 2, :name => "Canada"}
]
end
it "returns the first object" do
Country.first.should == Country.new(:id => 1)
end
end
describe ".last" do
before do
Country.data = [
{:id => 1, :name => "US"},
{:id => 2, :name => "Canada"}
]
end
it "returns the last object" do
Country.last.should == Country.new(:id => 2)
end
end
describe ".find" do
before do
Country.data = [
{:id => 1, :name => "US"},
{:id => 2, :name => "Canada"}
]
end
context "with an id" do
it "finds the record with the specified id" do
Country.find(2).id.should == 2
end
it "finds the record with the specified id as a string" do
Country.find("2").id.should == 2
end
it "raises ActiveHash::RecordNotFound when id not found" do
proc do
Country.find(0)
end.should raise_error(ActiveHash::RecordNotFound, /Couldn't find Country with ID=0/)
end
end
context "with :all" do
it "returns all records" do
Country.find(:all).should == [Country.new(:id => 1), Country.new(:id => 2)]
end
end
context "with :first" do
it "returns the first record" do
Country.find(:first).should == Country.new(:id => 1)
end
it "returns the first record that matches the search criteria" do
Country.find(:first, :conditions => {:id => 2}).should == Country.new(:id => 2)
end
it "returns nil if none matches the search criteria" do
Country.find(:first, :conditions => {:id => 3}).should == nil
end
end
context "with 2 arguments" do
it "returns the record with the given id and ignores the conditions" do
Country.find(1, :conditions => "foo=bar").should == Country.new(:id => 1)
Country.find(:all, :conditions => "foo=bar").length.should == 2
end
end
context "with an array of ids" do
before do
Country.data = [
{:id => 1},
{:id => 2},
{:id => 3}
]
end
it "returns all matching ids" do
Country.find([1, 3]).should == [Country.new(:id => 1), Country.new(:id => 3)]
end
it "raises ActiveHash::RecordNotFound when id not found" do
proc do
Country.find([0, 3])
end.should raise_error(ActiveHash::RecordNotFound, /Couldn't find Country with ID=0/)
end
end
end
describe ".find_by_id" do
before do
Country.data = [
{:id => 1, :name => "US"},
{:id => 2, :name => "Canada"}
]
end
context "with an id" do
it "finds the record with the specified id" do
Country.find_by_id(2).id.should == 2
end
it "finds the record with the specified id as a string" do
Country.find_by_id("2").id.should == 2
end
end
context "with string ids" do
before do
Country.data = [
{:id => "abc", :name => "US"},
{:id => "def", :name => "Canada"}
]
end
it "finds the record with the specified id" do
Country.find_by_id("abc").id.should == "abc"
end
end
context "with nil" do
it "returns nil" do
Country.find_by_id(nil).should be_nil
end
end
context "with an id not present" do
it "returns nil" do
Country.find_by_id(4567).should be_nil
end
end
end
describe "custom finders" do
before do
Country.fields :name, :monarch, :language
# Start ids above 4 lest we get nil and think it's an AH::Base model with id=4.
Country.data = [
{:id => 11, :name => nil, :monarch => nil, :language => "Latin"},
{:id => 12, :name => "US", :monarch => nil, :language => "English"},
{:id => 13, :name => "Canada", :monarch => "The Crown of England", :language => "English"},
{:id => 14, :name => "UK", :monarch => "The Crown of England", :language => "English"}
]
end
describe "find_by_<field_name>" do
describe "with a match" do
context "for a non-nil argument" do
it "returns the first matching record" do
Country.find_by_name("US").id.should == 12
end
end
context "for a nil argument" do
it "returns the first matching record" do
Country.find_by_name(nil).id.should == 11
end
end
end
describe "without a match" do
before do
Country.data = []
end
context "for a non-nil argument" do
it "returns nil" do
Country.find_by_name("Mexico").should be_nil
end
end
context "for a nil argument" do
it "returns nil" do
Country.find_by_name(nil).should be_nil
end
end
end
end
describe "find_by_<field_name>!" do
describe "with a match" do
context "for a non-nil argument" do
it "returns the first matching record" do
Country.find_by_name!("US").id.should == 12
end
end
context "for a nil argument" do
it "returns the first matching record" do
Country.find_by_name!(nil).id.should == 11
end
end
end
describe "without a match" do
before do
Country.data = []
end
context "for a non-nil argument" do
it "raises ActiveHash::RecordNotFound" do
lambda { Country.find_by_name!("Mexico") }.should raise_error(ActiveHash::RecordNotFound, /Couldn't find Country with name = Mexico/)
end
end
context "for a nil argument" do
it "raises ActiveHash::RecordNotFound" do
lambda { Country.find_by_name!(nil) }.should raise_error(ActiveHash::RecordNotFound, /Couldn't find Country with name = /)
end
end
end
end
describe "find_all_by_<field_name>" do
describe "with matches" do
it "returns all matching records" do
countries = Country.find_all_by_monarch("The Crown of England")
countries.length.should == 2
countries.first.name.should == "Canada"
countries.last.name.should == "UK"
end
end
describe "without matches" do
it "returns an empty array" do
Country.find_all_by_name("Mexico").should be_empty
end
end
end
describe "find_by_<field_one>_and_<field_two>" do
describe "with a match" do
it "returns the first matching record" do
Country.find_by_name_and_monarch("Canada", "The Crown of England").id.should == 13
Country.find_by_monarch_and_name("The Crown of England", "Canada").id.should == 13
end
end
describe "with a match based on to_s" do
it "returns the first matching record" do
Country.find_by_name_and_id("Canada", "13").id.should == 13
end
end
describe "without a match" do
it "returns nil" do
Country.find_by_name_and_monarch("US", "The Crown of England").should be_nil
end
end
describe "for fields the class doesn't have" do
it "raises a NoMethodError" do
lambda {
Country.find_by_name_and_shoe_size("US", 10)
}.should raise_error(NoMethodError, /undefined method `find_by_name_and_shoe_size' (?:for|on) Country/)
end
end
end
describe "find_by_<field_one>_and_<field_two>!" do
describe "with a match" do
it "returns the first matching record" do
Country.find_by_name_and_monarch!("Canada", "The Crown of England").id.should == 13
Country.find_by_monarch_and_name!("The Crown of England", "Canada").id.should == 13
end
end
describe "with a match based on to_s" do
it "returns the first matching record" do
Country.find_by_name_and_id!("Canada", "13").id.should == 13
end
end
describe "without a match" do
it "raises ActiveHash::RecordNotFound" do
lambda { Country.find_by_name_and_monarch!("US", "The Crown of England") }.should raise_error(ActiveHash::RecordNotFound, /Couldn't find Country with name = US, monarch = The Crown of England/)
end
end
describe "for fields the class doesn't have" do
it "raises a NoMethodError" do
lambda {
Country.find_by_name_and_shoe_size!("US", 10)
}.should raise_error(NoMethodError, /undefined method `find_by_name_and_shoe_size!' (?:for|on) Country/)
end
end
end
describe "find_all_by_<field_one>_and_<field_two>" do
describe "with matches" do
it "returns all matching records" do
countries = Country.find_all_by_monarch_and_language("The Crown of England", "English")
countries.length.should == 2
countries.first.name.should == "Canada"
countries.last.name.should == "UK"
end
end
describe "without matches" do
it "returns an empty array" do
Country.find_all_by_monarch_and_language("Shaka Zulu", "Zulu").should be_empty
end
end
end
end
describe "#method_missing" do
it "doesn't blow up if you call a missing dynamic finder when fields haven't been set" do
proc do
Country.find_by_name("Foo")
end.should raise_error(NoMethodError, /undefined method `find_by_name' (?:for|on) Country/)
end
end
describe "#attributes" do
it "returns the hash passed in the initializer" do
Country.field :foo
country = Country.new(:foo => :bar)
country.attributes.should == {:foo => :bar}
end
it "symbolizes keys" do
Country.field :foo
country = Country.new("foo" => :bar)
country.attributes.should == {:foo => :bar}
end
it "works with #[]" do
Country.field :foo
country = Country.new(:foo => :bar)
country[:foo].should == :bar
end
it "works with _read_attribute" do
Country.field :foo
country = Country.new(:foo => :bar)
country._read_attribute(:foo).should == :bar
end
it "works with read_attribute" do
Country.field :foo
country = Country.new(:foo => :bar)
country.read_attribute(:foo).should == :bar
end
it "works with #[]=" do
Country.field :foo
country = Country.new
country[:foo] = :bar
country.foo.should == :bar
end
end
describe "reader methods" do
context "for regular fields" do
before do
Country.fields :name, :iso_name
end
it "returns the given attribute when present" do
country = Country.new(:name => "Spain")
country.name.should == "Spain"
end
it "returns nil when not present" do
country = Country.new
country.name.should be_nil
end
end
context "for fields with default values" do
before do
Country.field :name, :default => "foobar"
end
it "returns the given attribute when present" do
country = Country.new(:name => "Spain")
country.name.should == "Spain"
end
it "returns the default value when not present" do
country = Country.new
country.name.should == "foobar"
end
context "#attributes" do
it "returns the default value when not present" do
country = Country.new
country.attributes[:name].should == "foobar"
end
end
end
end
describe "interrogator methods" do
before do
Country.fields :name, :iso_name
end
it "returns true if the given attribute is non-blank" do
country = Country.new(:name => "Spain")
country.should be_name
end
it "returns false if the given attribute is blank" do
country = Country.new(:name => " ")
country.name?.should == false
end
it "returns false if the given attribute was not passed" do
country = Country.new
country.should_not be_name
end
end
describe "#id" do
context "when not passed an id" do
it "returns nil" do
country = Country.new
country.id.should be_nil
end
end
end
describe "#quoted_id" do
it "should return id" do
Country.new(:id => 2).quoted_id.should == 2
end
end
describe "#to_param" do
it "should return id as a string" do
Country.create(:id => 2).to_param.should == "2"
end
end
describe "#persisted" do
it "should return true if the object has been saved" do
Country.create(:id => 2).should be_persisted
end
it "should return false if the object has not been saved" do
Country.new(:id => 2).should_not be_persisted
end
end
describe "#persisted" do
it "should return true if the object has been saved" do
Country.create(:id => 2).should be_persisted
end
it "should return false if the object has not been saved" do
Country.new(:id => 2).should_not be_persisted
end
end
describe "#eql?" do
before do
class Region < ActiveHash::Base
end
end
it "should return true with the same class and id" do
Country.new(:id => 23).eql?(Country.new(:id => 23)).should be_truthy
end
it "should return false with the same class and different ids" do
Country.new(:id => 24).eql?(Country.new(:id => 23)).should be_falsey
end
it "should return false with the different classes and the same id" do
Country.new(:id => 23).eql?(Region.new(:id => 23)).should be_falsey
end
it "returns false when id is nil" do
Country.new.eql?(Country.new).should be_falsey
end
end
describe "#==" do
before do
class Region < ActiveHash::Base
end
end
it "should return true with the same class and id" do
Country.new(:id => 23).should == Country.new(:id => 23)
end
it "should return false with the same class and different ids" do
Country.new(:id => 24).should_not == Country.new(:id => 23)
end
it "should return false with the different classes and the same id" do
Country.new(:id => 23).should_not == Region.new(:id => 23)
end
it "returns false when id is nil" do
Country.new.should_not == Country.new
end
end
describe "#hash" do
it "returns id for hash" do
Country.new(:id => 45).hash.should == 45.hash
Country.new.hash.should == nil.hash
end
it "is hashable" do
{Country.new(:id => 4) => "bar"}.should == {Country.new(:id => 4) => "bar"}
{Country.new(:id => 3) => "bar"}.should_not == {Country.new(:id => 4) => "bar"}
end
end
describe "#readonly?" do
it "returns true" do
Country.new.should be_readonly
end
end
describe "auto-discovery of fields" do
it "dynamically creates fields for all keys in the hash" do
Country.data = [
{:field1 => "foo"},
{:field2 => "bar"},
{:field3 => "biz"}
]
[:field1, :field2, :field3].each do |field|
Country.should respond_to("find_by_#{field}")
Country.should respond_to("find_all_by_#{field}")
Country.new.should respond_to(field)
Country.new.should respond_to("#{field}?")
end
end
it "doesn't override methods already defined" do
Country.class_eval do
class << self
def find_by_name(name)
"find_by_name defined manually"
end
def find_all_by_name(name)
"find_all_by_name defined manually"
end
end
def name
"name defined manually"
end
def name?
"name? defined manually"
end
end
Country.find_by_name("foo").should == "find_by_name defined manually"
Country.find_all_by_name("foo").should == "find_all_by_name defined manually"
Country.new.name.should == "name defined manually"
Country.new.name?.should == "name? defined manually"
Country.data = [
{:name => "foo"}
]
Country.all
Country.find_by_name("foo").should == "find_by_name defined manually"
Country.find_all_by_name("foo").should == "find_all_by_name defined manually"
Country.new.name.should == "name defined manually"
Country.new.name?.should == "name? defined manually"
end
end
describe "using with belongs_to in ActiveRecord", :unless => SKIP_ACTIVE_RECORD do
before do
Country.data = [
{:id => 1, :name => "foo"}
]
class Book < ActiveRecord::Base
establish_connection :adapter => "sqlite3", :database => ":memory:"
connection.create_table(:books, :force => true) do |t|
t.text :subject_type
t.integer :subject_id
t.integer :country_id
end
belongs_to :subject, :polymorphic => true
belongs_to :country
end
end
after do
Object.send :remove_const, :Book
end
it "should be possible to use it as a parent" do
book = Book.new
book.country = Country.first
book.country.should == Country.first
end
it "should be possible to use it as a polymorphic parent" do
book = Book.new
book.subject = Country.first
book.subject.should == Country.first
end
end
describe "#cache_key" do
it 'should use the class\'s cache_key and id' do
Country.data = [
{:id => 1, :name => "foo"}
]
Country.first.cache_key.should == 'countries/1'
end
it 'should use the record\'s updated_at if present' do
timestamp = Time.now
Country.data = [
{:id => 1, :name => "foo", :updated_at => timestamp}
]
Country.first.cache_key.should == "countries/1-#{timestamp.to_s(:number)}"
end
it 'should use "new" instead of the id for a new record' do
Country.new(:id => 1).cache_key.should == 'countries/new'
end
end
describe "#save" do
before do
Country.field :name
end
it "adds the new object to the data collection" do
Country.all.should be_empty
country = Country.new :id => 1, :name => "foo"
country.save.should be_truthy
Country.all.should == [country]
end
it "adds the new object to the data collection" do
Country.all.should be_empty
country = Country.new :id => 1, :name => "foo"
country.save!.should be_truthy
Country.all.should == [country]
end
it "marks the class as dirty" do
Country.dirty.should be_falsey
Country.new(:id => 1, :name => "foo").save
Country.dirty.should be_truthy
end
it "it is a no-op if the object has already been added to the collection" do
Country.all.should be_empty
country = Country.new :id => 1, :name => "foo"
country.save
country.name = "bar"
country.save
country.save!
Country.all.should == [country]
end
end
describe ".create" do
before do
Country.field :name
end
it "works with no args" do
Country.all.should be_empty
country = Country.create
country.id.should == 1
end
it "adds the new object to the data collection" do
Country.all.should be_empty
country = Country.create :id => 1, :name => "foo"
country.id.should == 1
country.name.should == "foo"
Country.all.should == [country]
end
it "adds an auto-incrementing id if the id is nil" do
country1 = Country.new :name => "foo"
country1.save
country1.id.should == 1
country2 = Country.new :name => "bar"
country2.save
country2.id.should == 2
end
it "does not add auto-incrementing id if the id is present" do
country1 = Country.new :id => 456, :name => "foo"
country1.save
country1.id.should == 456
end
it "does not blow up with strings" do
country1 = Country.new :id => "foo", :name => "foo"
country1.save
country1.id.should == "foo"
country2 = Country.new :name => "foo"
country2.save
country2.id.should be_nil
end
it "adds the new object to the data collection" do
Country.all.should be_empty
country = Country.create! :id => 1, :name => "foo"
country.id.should == 1
country.name.should == "foo"
Country.all.should == [country]
end
it "marks the class as dirty" do
Country.dirty.should be_falsey
Country.create! :id => 1, :name => "foo"
Country.dirty.should be_truthy
end
end
describe "#valid?" do
it "should return true" do
Country.new.should be_valid
end
end
describe "#new_record?" do
before do
Country.field :name
Country.data = [
:id => 1, :name => "foo"
]
end
it "returns false when the object is already part of the collection" do
Country.new(:id => 1).should_not be_new_record
end
it "returns true when the object is not part of the collection" do
Country.new(:id => 2).should be_new_record
end
end
describe ".transaction" do
it "execute the block given to it" do
foo = Object.new
foo.should_receive(:bar)
Country.transaction do
foo.bar
end
end
it "swallows ActiveRecord::Rollback errors", :unless => SKIP_ACTIVE_RECORD do
proc do
Country.transaction do
raise ActiveRecord::Rollback
end
end.should_not raise_error
end
it "passes other errors through" do
proc do
Country.transaction do
raise "hell"
end
end.should raise_error("hell")
end
end
describe ".delete_all" do
it "clears out all record" do
country1 = Country.create
country2 = Country.create
Country.all.should == [country1, country2]
Country.delete_all
Country.all.should be_empty
end
it "marks the class as dirty" do
Country.dirty.should be_falsey
Country.delete_all
Country.dirty.should be_truthy
end
end
end
| 28.039245 | 203 | 0.603117 |
39da7d5a4b484c584183ec2a70865aac8262831f | 1,438 | require 'test_helper'
class CrumbsTest < ActionDispatch::IntegrationTest
test 'links' do
get '/'
assert_equal Hash.new, session[:referers]
assert_select 'a', count: 1
assert_select 'a[href=?]', 'http://www.example.com', text: /home/, count: 1
get '/admin/users?query='
assert_equal(
{ 'http://www.example.com/admin/users' => 'query=' },
session[:referers]
)
assert_select 'a', count: 2
assert_select 'a[href=?]', 'http://www.example.com', text: /home/, count: 1
assert_select 'a[href=?]', 'http://www.example.com/admin/users?query=', text: /users/, count: 1
get '/admin/users/7'
assert_equal(
{ 'http://www.example.com/admin/users' => 'query=' },
session[:referers]
)
assert_select 'a', count: 3
assert_select 'a[href=?]', 'http://www.example.com', text: /home/, count: 1
assert_select 'a[href=?]', 'http://www.example.com/admin/users?query=', text: /users/, count: 1
assert_select 'a[href=?]', 'http://www.example.com/admin/users/7', text: /user 7/, count: 1
get '/admin/reports/deliveries'
assert_equal(
{ 'http://www.example.com/admin/users' => 'query=' },
session[:referers]
)
assert_select 'a', count: 2
assert_select 'a[href=?]', 'http://www.example.com', text: /home/, count: 1
assert_select 'a[href=?]', 'http://www.example.com/admin/reports/deliveries', text: /deliveries/, count: 1
end
end
| 35.073171 | 110 | 0.621697 |
e250a15039b7dd16154cf0191bba43b7d3118454 | 1,457 | Gem::Specification.new do |s|
s.name = 'logstash-output-s3'
s.version = '4.1.1'
s.licenses = ['Apache-2.0']
s.summary = "Sends Logstash events to the Amazon Simple Storage Service"
s.description = "This gem is a Logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/logstash-plugin install gemname. This gem is not a stand-alone program"
s.authors = ["Elastic"]
s.email = '[email protected]'
s.homepage = "http://www.elastic.co/guide/en/logstash/current/index.html"
s.require_paths = ["lib"]
# Files
s.files = Dir["lib/**/*","spec/**/*","*.gemspec","*.md","CONTRIBUTORS","Gemfile","LICENSE","NOTICE.TXT", "vendor/jar-dependencies/**/*.jar", "vendor/jar-dependencies/**/*.rb", "VERSION", "docs/**/*"]
# Tests
s.test_files = s.files.grep(%r{^(test|spec|features)/})
# Special flag to let us know this is actually a logstash plugin
s.metadata = { "logstash_plugin" => "true", "logstash_group" => "output" }
# Gem dependencies
s.add_runtime_dependency "logstash-core-plugin-api", ">= 1.60", "<= 2.99"
s.add_runtime_dependency 'logstash-mixin-aws', '>= 4.3.0'
s.add_runtime_dependency "concurrent-ruby"
s.add_runtime_dependency 'stud', '~> 0.0.22'
s.add_development_dependency 'logstash-devutils'
s.add_development_dependency 'logstash-input-generator'
s.add_development_dependency 'logstash-codec-line'
end
| 48.566667 | 205 | 0.669183 |
e9072d545a8e241fe97a1d64726488305cb48fa9 | 21,415 | ##
# Module ISO Test
def labeled_module(name, &block)
Module.new do
(class <<self; self end).class_eval do
define_method(:to_s) { name }
alias_method :inspect, :to_s
end
class_eval(&block) if block
end
end
def labeled_class(name, supklass = Object, &block)
Class.new(supklass) do
(class <<self; self end).class_eval do
define_method(:to_s) { name }
alias_method :inspect, :to_s
end
class_eval(&block) if block
end
end
def assert_uninitialized_const(&block)
assert_raise_with_message_pattern(NameError, "uninitialized constant *", &block)
end
def assert_wrong_const_name(&block)
assert_raise_with_message_pattern(NameError, "wrong constant name *", &block)
end
assert('Module', '15.2.2') do
assert_equal Class, Module.class
end
assert('Module#alias_method', '15.2.2.4.8') do
cls = Class.new do
def foo
"FOO"
end
end
assert_same(cls, cls.alias_method(:bar, :foo))
assert_equal("FOO", cls.new.bar)
end
# TODO not implemented ATM assert('Module.constants', '15.2.2.3.1') do
assert('Module#ancestors', '15.2.2.4.9') do
class Test4ModuleAncestors
end
r = String.ancestors
assert_equal Array, r.class
assert_true r.include?(String)
assert_true r.include?(Object)
end
assert('Module#append_features', '15.2.2.4.10') do
module Test4AppendFeatures
def self.append_features(mod)
Test4AppendFeatures2.const_set(:Const4AppendFeatures2, mod)
end
end
module Test4AppendFeatures2
include Test4AppendFeatures
end
assert_equal Test4AppendFeatures2, Test4AppendFeatures2.const_get(:Const4AppendFeatures2)
assert_raise(FrozenError) { Module.new.append_features Class.new.freeze }
end
assert('Module#attr NameError') do
%w[
foo?
@foo
@@foo
$foo
].each do |name|
module NameTest; end
assert_raise(NameError) do
NameTest.module_eval { attr_reader name.to_sym }
end
assert_raise(NameError) do
NameTest.module_eval { attr_writer name.to_sym }
end
assert_raise(NameError) do
NameTest.module_eval { attr name.to_sym }
end
assert_raise(NameError) do
NameTest.module_eval { attr_accessor name.to_sym }
end
end
end
assert('Module#attr', '15.2.2.4.11') do
class AttrTest
class << self
attr :cattr
def cattr_val=(val)
@cattr = val
end
end
attr :iattr
def iattr_val=(val)
@iattr = val
end
end
test = AttrTest.new
assert_true AttrTest.respond_to?(:cattr)
assert_true test.respond_to?(:iattr)
assert_false AttrTest.respond_to?(:cattr=)
assert_false test.respond_to?(:iattr=)
test.iattr_val = 'test'
assert_equal 'test', test.iattr
AttrTest.cattr_val = 'test'
assert_equal 'test', AttrTest.cattr
end
assert('Module#attr_accessor', '15.2.2.4.12') do
class AttrTestAccessor
class << self
attr_accessor :cattr
end
attr_accessor :iattr, 'iattr2'
end
attr_instance = AttrTestAccessor.new
assert_true AttrTestAccessor.respond_to?(:cattr=)
assert_true attr_instance.respond_to?(:iattr=)
assert_true attr_instance.respond_to?(:iattr2=)
assert_true AttrTestAccessor.respond_to?(:cattr)
assert_true attr_instance.respond_to?(:iattr)
assert_true attr_instance.respond_to?(:iattr2)
attr_instance.iattr = 'test'
assert_equal 'test', attr_instance.iattr
AttrTestAccessor.cattr = 'test'
assert_equal 'test', AttrTestAccessor.cattr
end
assert('Module#attr_reader', '15.2.2.4.13') do
class AttrTestReader
class << self
attr_reader :cattr
def cattr_val=(val)
@cattr = val
end
end
attr_reader :iattr, 'iattr2'
def iattr_val=(val)
@iattr = val
end
end
attr_instance = AttrTestReader.new
assert_true AttrTestReader.respond_to?(:cattr)
assert_true attr_instance.respond_to?(:iattr)
assert_true attr_instance.respond_to?(:iattr2)
assert_false AttrTestReader.respond_to?(:cattr=)
assert_false attr_instance.respond_to?(:iattr=)
assert_false attr_instance.respond_to?(:iattr2=)
attr_instance.iattr_val = 'test'
assert_equal 'test', attr_instance.iattr
AttrTestReader.cattr_val = 'test'
assert_equal 'test', AttrTestReader.cattr
end
assert('Module#attr_writer', '15.2.2.4.14') do
class AttrTestWriter
class << self
attr_writer :cattr
def cattr_val
@cattr
end
end
attr_writer :iattr, 'iattr2'
def iattr_val
@iattr
end
end
attr_instance = AttrTestWriter.new
assert_true AttrTestWriter.respond_to?(:cattr=)
assert_true attr_instance.respond_to?(:iattr=)
assert_true attr_instance.respond_to?(:iattr2=)
assert_false AttrTestWriter.respond_to?(:cattr)
assert_false attr_instance.respond_to?(:iattr)
assert_false attr_instance.respond_to?(:iattr2)
attr_instance.iattr = 'test'
assert_equal 'test', attr_instance.iattr_val
AttrTestWriter.cattr = 'test'
assert_equal 'test', AttrTestWriter.cattr_val
end
assert('Module#class_eval', '15.2.2.4.15') do
class Test4ClassEval
@a = 11
@b = 12
end
Test4ClassEval.class_eval do
def method1
end
end
assert_equal 11, Test4ClassEval.class_eval{ @a }
assert_equal 12, Test4ClassEval.class_eval{ @b }
assert_equal true, Test4ClassEval.new.respond_to?(:method1)
end
assert('Module#const_defined?', '15.2.2.4.20') do
module Test4ConstDefined
Const4Test4ConstDefined = true
end
assert_true Test4ConstDefined.const_defined?(:Const4Test4ConstDefined)
assert_false Test4ConstDefined.const_defined?(:NotExisting)
assert_wrong_const_name{ Test4ConstDefined.const_defined?(:wrong_name) }
# shared empty iv_tbl (include)
m = Module.new
c = Class.new{include m}
m::CONST = 1
assert_true c.const_defined?(:CONST)
# shared empty iv_tbl (prepend)
m = Module.new
c = Class.new{prepend m}
m::CONST = 1
assert_true c.const_defined?(:CONST)
end
assert('Module#const_get', '15.2.2.4.21') do
module Test4ConstGet
Const4Test4ConstGet = 42
end
assert_equal 42, Test4ConstGet.const_get(:Const4Test4ConstGet)
assert_equal 42, Test4ConstGet.const_get("Const4Test4ConstGet")
assert_equal 42, Object.const_get("Test4ConstGet::Const4Test4ConstGet")
assert_raise(TypeError){ Test4ConstGet.const_get(123) }
assert_uninitialized_const{ Test4ConstGet.const_get(:I_DO_NOT_EXIST) }
assert_uninitialized_const{ Test4ConstGet.const_get("I_DO_NOT_EXIST::ME_NEITHER") }
assert_wrong_const_name{ Test4ConstGet.const_get(:wrong_name) }
# shared empty iv_tbl (include)
m = Module.new
c = Class.new{include m}
m::CONST = 1
assert_equal 1, c.const_get(:CONST)
# shared empty iv_tbl (prepend)
m = Module.new
c = Class.new{prepend m}
m::CONST = 1
assert_equal 1, c.const_get(:CONST)
end
assert('Module#const_set', '15.2.2.4.23') do
module Test4ConstSet
Const4Test4ConstSet = 42
end
assert_equal 23, Test4ConstSet.const_set(:Const4Test4ConstSet, 23)
assert_equal 23, Test4ConstSet.const_get(:Const4Test4ConstSet)
["", "wrongNAME", "Wrong-Name"].each do |n|
assert_wrong_const_name { Test4ConstSet.const_set(n, 1) }
end
end
assert('Module#remove_const', '15.2.2.4.40') do
module Test4RemoveConst
ExistingConst = 23
end
assert_equal 23, Test4RemoveConst.remove_const(:ExistingConst)
assert_false Test4RemoveConst.const_defined?(:ExistingConst)
assert_raise_with_message_pattern(NameError, "constant * not defined") do
Test4RemoveConst.remove_const(:NonExistingConst)
end
%i[x X!].each do |n|
assert_wrong_const_name { Test4RemoveConst.remove_const(n) }
end
assert_raise(FrozenError) { Test4RemoveConst.freeze.remove_const(:A) }
end
assert('Module#const_missing', '15.2.2.4.22') do
module Test4ConstMissing
def self.const_missing(sym)
42 # the answer to everything
end
end
assert_equal 42, Test4ConstMissing.const_get(:ConstDoesntExist)
end
assert('Module#extend_object', '15.2.2.4.25') do
cls = Class.new
mod = Module.new { def foo; end }
a = cls.new
b = cls.new
mod.extend_object(b)
assert_false a.respond_to?(:foo)
assert_true b.respond_to?(:foo)
assert_raise(FrozenError) { mod.extend_object(cls.new.freeze) }
assert_raise(FrozenError, TypeError) { mod.extend_object(1) }
end
assert('Module#include', '15.2.2.4.27') do
module Test4Include
Const4Include = 42
end
module Test4Include2
@include_result = include Test4Include
class << self
attr_reader :include_result
end
end
assert_equal 42, Test4Include2.const_get(:Const4Include)
assert_equal Test4Include2, Test4Include2.include_result
assert_raise(FrozenError) { Module.new.freeze.include Test4Include }
end
assert('Module#include?', '15.2.2.4.28') do
module Test4IncludeP
end
class Test4IncludeP2
include Test4IncludeP
end
class Test4IncludeP3 < Test4IncludeP2
end
assert_true Test4IncludeP2.include?(Test4IncludeP)
assert_true Test4IncludeP3.include?(Test4IncludeP)
assert_false Test4IncludeP.include?(Test4IncludeP)
end
assert('Module#included', '15.2.2.4.29') do
module Test4Included
Const4Included = 42
def self.included mod
Test4Included.const_set(:Const4Included2, mod)
end
end
module Test4Included2
include Test4Included
end
assert_equal 42, Test4Included2.const_get(:Const4Included)
assert_equal Test4Included2, Test4Included2.const_get(:Const4Included2)
end
assert('Module#initialize', '15.2.2.4.31') do
assert_kind_of Module, Module.new
mod = Module.new { def hello; "hello"; end }
cls = Class.new{include mod}
assert_true cls.new.respond_to?(:hello)
a = nil
mod = Module.new { |m| a = m }
assert_equal mod, a
end
assert('Module#method_defined?', '15.2.2.4.34') do
module Test4MethodDefined
module A
def method1() end
end
class B
def method2() end
end
class C < B
include A
def method3() end
end
end
assert_true Test4MethodDefined::A.method_defined? :method1
assert_true Test4MethodDefined::C.method_defined? :method1
assert_true Test4MethodDefined::C.method_defined? "method2"
assert_true Test4MethodDefined::C.method_defined? "method3"
assert_false Test4MethodDefined::C.method_defined? "method4"
end
assert('Module#module_eval', '15.2.2.4.35') do
module Test4ModuleEval
@a = 11
@b = 12
end
assert_equal 11, Test4ModuleEval.module_eval{ @a }
assert_equal 12, Test4ModuleEval.module_eval{ @b }
end
assert('Module#undef_method', '15.2.2.4.42') do
module Test4UndefMethod
class Parent
def hello
end
end
class Child < Parent
def hello
end
end
class GrandChild < Child
end
end
Test4UndefMethod::Child.class_eval{ undef_method :hello }
assert_true Test4UndefMethod::Parent.new.respond_to?(:hello)
assert_false Test4UndefMethod::Child.new.respond_to?(:hello)
assert_false Test4UndefMethod::GrandChild.new.respond_to?(:hello)
end
# Not ISO specified
assert('Module#dup') do
module TestModuleDup
@@cvar = :cvar
class << self
attr_accessor :cattr
def cmeth; :cmeth end
end
def cvar; @@cvar end
def imeth; :imeth end
self.cattr = :cattr
end
m = TestModuleDup.dup
o = Object.include(m).new
assert_equal(:cattr, m.cattr)
assert_equal(:cmeth, m.cmeth)
assert_equal(:cvar, o.cvar)
assert_equal(:imeth, o.imeth)
assert_match("#<Module:0x*>", m.to_s)
assert_not_predicate(m, :frozen?)
assert_not_predicate(TestModuleDup.freeze.dup, :frozen?)
end
assert('Module#define_method') do
c = Class.new {
define_method(:m1) { :ok }
define_method(:m2, Proc.new { :ok })
}
assert_equal c.new.m1, :ok
assert_equal c.new.m2, :ok
assert_raise(TypeError) do
Class.new { define_method(:n1, nil) }
end
end
assert 'Module#prepend_features' do
mod = Module.new { def m; :mod end }
cls = Class.new { def m; :cls end }
assert_equal :cls, cls.new.m
mod.prepend_features(cls)
assert_equal :mod, cls.new.m
assert_raise(FrozenError) { Module.new.prepend_features(Class.new.freeze) }
end
# @!group prepend
assert('Module#prepend') do
module M0
def m1; [:M0] end
end
module M1
def m1; [:M1, super, :M1] end
end
module M2
def m1; [:M2, super, :M2] end
end
M3 = Module.new do
def m1; [:M3, super, :M3] end
end
module M4
def m1; [:M4, super, :M4] end
end
class P0
include M0
prepend M1
def m1; [:C0, super, :C0] end
end
class P1 < P0
prepend M2, M3
include M4
def m1; [:C1, super, :C1] end
end
obj = P1.new
expected = [:M2,[:M3,[:C1,[:M4,[:M1,[:C0,[:M0],:C0],:M1],:M4],:C1],:M3],:M2]
assert_equal(expected, obj.m1)
end
assert('Module#prepend result') do
module TestPrepended; end
module TestPrependResult
@prepend_result = prepend TestPrepended
class << self
attr_reader :prepend_result
end
end
assert_equal TestPrependResult, TestPrependResult.prepend_result
end
# mruby shouldn't be affected by this since there is
# no visibility control (yet)
assert('Module#prepend public') do
assert_nothing_raised('ruby/ruby #8846') do
Class.new.prepend(Module.new)
end
end
assert('Module#prepend inheritance') do
bug6654 = '[ruby-core:45914]'
a = labeled_module('a')
b = labeled_module('b') { include a }
c = labeled_module('c') { prepend b }
#assert bug6654 do
# the Module#< operator should be used here instead, but we don't have it
assert_include(c.ancestors, a)
assert_include(c.ancestors, b)
#end
bug8357 = '[ruby-core:54736] [Bug #8357]'
b = labeled_module('b') { prepend a }
c = labeled_class('c') { include b }
#assert bug8357 do
# the Module#< operator should be used here instead, but we don't have it
assert_include(c.ancestors, a)
assert_include(c.ancestors, b)
#end
bug8357 = '[ruby-core:54742] [Bug #8357]'
assert_kind_of(b, c.new, bug8357)
end
assert 'Module#prepend + Class#ancestors' do
bug6658 = '[ruby-core:45919]'
m = labeled_module("m")
c = labeled_class("c") {prepend m}
assert_equal([m, c], c.ancestors[0, 2], bug6658)
bug6662 = '[ruby-dev:45868]'
c2 = labeled_class("c2", c)
anc = c2.ancestors
assert_equal([c2, m, c, Object], anc[0..anc.index(Object)], bug6662)
end
assert 'Module#prepend + Module#ancestors' do
bug6659 = '[ruby-dev:45861]'
m0 = labeled_module("m0") { def x; [:m0, *super] end }
m1 = labeled_module("m1") { def x; [:m1, *super] end; prepend m0 }
m2 = labeled_module("m2") { def x; [:m2, *super] end; prepend m1 }
c0 = labeled_class("c0") { def x; [:c0] end }
c1 = labeled_class("c1") { def x; [:c1] end; prepend m2 }
c2 = labeled_class("c2", c0) { def x; [:c2, *super] end; include m2 }
#
assert_equal([m0, m1], m1.ancestors, bug6659)
#
bug6662 = '[ruby-dev:45868]'
assert_equal([m0, m1, m2], m2.ancestors, bug6662)
assert_equal([m0, m1, m2, c1], c1.ancestors[0, 4], bug6662)
assert_equal([:m0, :m1, :m2, :c1], c1.new.x)
assert_equal([c2, m0, m1, m2, c0], c2.ancestors[0, 5], bug6662)
assert_equal([:c2, :m0, :m1, :m2, :c0], c2.new.x)
#
m3 = labeled_module("m3") { include m1; prepend m1 }
assert_equal([m3, m0, m1], m3.ancestors)
m3 = labeled_module("m3") { prepend m1; include m1 }
assert_equal([m0, m1, m3], m3.ancestors)
m3 = labeled_module("m3") { prepend m1; prepend m1 }
assert_equal([m0, m1, m3], m3.ancestors)
m3 = labeled_module("m3") { include m1; include m1 }
assert_equal([m3, m0, m1], m3.ancestors)
end
assert 'cyclic Module#prepend' do
bug7841 = '[ruby-core:52205] [Bug #7841]'
m1 = Module.new
m2 = Module.new
m1.instance_eval { prepend(m2) }
assert_raise(ArgumentError, bug7841) do
m2.instance_eval { prepend(m1) }
end
end
# these assertions will not run without a #assert_separately method
#assert 'test_prepend_optmethod' do
# bug7983 = '[ruby-dev:47124] [Bug #7983]'
# assert_separately [], %{
# module M
# def /(other)
# to_f / other
# end
# end
# Integer.send(:prepend, M)
# assert_equal(0.5, 1 / 2, "#{bug7983}")
# }
# assert_equal(0, 1 / 2)
#end
# mruby has no visibility control
# assert 'Module#prepend visibility' do
# bug8005 = '[ruby-core:53106] [Bug #8005]'
# c = Class.new do
# prepend Module.new {}
# def foo() end
# protected :foo
# end
# a = c.new
# assert_true a.respond_to?(:foo), bug8005
# assert_nothing_raised(bug8005) {a.send :foo}
# end
# mruby has no visibility control
# assert 'Module#prepend inherited visibility' do
# bug8238 = '[ruby-core:54105] [Bug #8238]'
# module Test4PrependVisibilityInherited
# class A
# def foo() A; end
# private :foo
# end
# class B < A
# public :foo
# prepend Module.new
# end
# end
# assert_equal(Test4PrependVisibilityInherited::A, Test4PrependVisibilityInherited::B.new.foo, "#{bug8238}")
# end
# assert 'Module#prepend super in alias' do
# skip "super does not currently work in aliased methods"
# bug7842 = '[Bug #7842]'
# p = labeled_module("P") do
# def m; "P"+super; end
# end
# a = labeled_class("A") do
# def m; "A"; end
# end
# b = labeled_class("B", a) do
# def m; "B"+super; end
# alias m2 m
# prepend p
# alias m3 m
# end
# assert_nothing_raised do
# assert_equal("BA", b.new.m2, bug7842)
# end
# assert_nothing_raised do
# assert_equal("PBA", b.new.m3, bug7842)
# end
# end
assert 'Module#prepend each class' do
m = labeled_module("M")
c1 = labeled_class("C1") {prepend m}
c2 = labeled_class("C2", c1) {prepend m}
assert_equal([m, c2, m, c1], c2.ancestors[0, 4], "should be able to prepend each class")
end
assert 'Module#prepend no duplication' do
m = labeled_module("M")
c = labeled_class("C") {prepend m; prepend m}
assert_equal([m, c], c.ancestors[0, 2], "should never duplicate")
end
assert 'Module#prepend in superclass' do
m = labeled_module("M")
c1 = labeled_class("C1")
c2 = labeled_class("C2", c1) {prepend m}
c1.class_eval {prepend m}
assert_equal([m, c2, m, c1], c2.ancestors[0, 4], "should accessible prepended module in superclass")
end
# requires #assert_separately
#assert 'Module#prepend call super' do
# assert_separately([], <<-'end;') #do
# bug10847 = '[ruby-core:68093] [Bug #10847]'
# module M; end
# Float.prepend M
# assert_nothing_raised(SystemStackError, bug10847) do
# 0.3.numerator
# end
# end;
#end
assert 'Module#prepend to frozen class' do
assert_raise(FrozenError) { Class.new.freeze.prepend Module.new }
end
# @!endgroup prepend
assert('Module#to_s') do
module Outer
class Inner; end
const_set :SetInner, Class.new
end
assert_equal 'Outer', Outer.to_s
assert_equal 'Outer::Inner', Outer::Inner.to_s
assert_equal 'Outer::SetInner', Outer::SetInner.to_s
outer = Module.new do
const_set :SetInner, Class.new
end
Object.const_set :SetOuter, outer
assert_equal 'SetOuter', SetOuter.to_s
assert_equal 'SetOuter::SetInner', SetOuter::SetInner.to_s
assert_match "#<Module:0x*>", Module.new.to_s
assert_match "#<Class:0x*>", Class.new.to_s
assert_equal "FrozenClassToS", (FrozenClassToS = Class.new.freeze).to_s
assert_equal "Outer::A", (Outer::A = Module.new.freeze).to_s
assert_match "#<Module:0x*>::A", (Module.new::A = Class.new.freeze).to_s
end
assert('Module#inspect') do
module Test4to_sModules
end
assert_equal 'Test4to_sModules', Test4to_sModules.inspect
end
assert('Issue 1467') do
module M1
def initialize()
super()
end
end
class C1
include M1
def initialize()
super()
end
end
class C2
include M1
end
assert_kind_of(M1, C1.new)
assert_kind_of(M1, C2.new)
end
assert('clone Module') do
module M1
def foo
true
end
end
class B
include M1.clone
end
assert_true(B.new.foo)
end
assert('Module#module_function') do
module M
def modfunc; end
module_function :modfunc
end
assert_true M.respond_to?(:modfunc)
end
assert('module with non-class/module outer raises TypeError') do
assert_raise(TypeError) { module 0::M1 end }
assert_raise(TypeError) { module []::M2 end }
end
assert('module to return the last value') do
m = module M; :m end
assert_equal(:m, m)
end
assert('module to return nil if body is empty') do
assert_nil(module M end)
end
assert('get constant of parent module in singleton class; issue #3568') do
actual = module GetConstantInSingletonTest
EXPECTED = "value"
class << self
EXPECTED
end
end
assert_equal("value", actual)
end
assert('shared empty iv_tbl (include)') do
m1 = Module.new
m2 = Module.new{include m1}
c = Class.new{include m2}
m1::CONST1 = 1
assert_equal 1, m2::CONST1
assert_equal 1, c::CONST1
m2::CONST2 = 2
assert_equal 2, c::CONST2
end
assert('shared empty iv_tbl (prepend)') do
m1 = Module.new
m2 = Module.new{prepend m1}
c = Class.new{include m2}
m1::CONST1 = 1
assert_equal 1, m2::CONST1
assert_equal 1, c::CONST1
m2::CONST2 = 2
assert_equal 2, c::CONST2
end
| 25.343195 | 112 | 0.678917 |
28eaf291c7cbd30f0c4c46504e5ac7787c1f76fd | 1,871 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::ContainerInstance::Mgmt::V2017_10_01_preview
module Models
#
# Image registry credential.
#
class ImageRegistryCredential
include MsRestAzure
# @return [String] The Docker image registry server without a protocol
# such as "http" and "https".
attr_accessor :server
# @return [String] The username for the private registry.
attr_accessor :username
# @return [String] The password for the private registry.
attr_accessor :password
#
# Mapper for ImageRegistryCredential class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ImageRegistryCredential',
type: {
name: 'Composite',
class_name: 'ImageRegistryCredential',
model_properties: {
server: {
client_side_validation: true,
required: true,
serialized_name: 'server',
type: {
name: 'String'
}
},
username: {
client_side_validation: true,
required: true,
serialized_name: 'username',
type: {
name: 'String'
}
},
password: {
client_side_validation: true,
required: false,
serialized_name: 'password',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 27.115942 | 76 | 0.520577 |
d5579b94308b0e3e44980f0c132c2a6c5263188f | 225 | class RiceReportsController < CropController
def safe_params
get_model unless @symbol
return params.require(@symbol).permit(:bags_harvested, :pishori_bags, :super_bags, :other_bags, :kg_of_seed_planted)
end
end
| 25 | 120 | 0.782222 |
e90a15b5f8bb4a925b0af9b1456a37575a96f336 | 2,509 | # frozen_string_literal: true
require 'spec_helper'
describe 'epics list', :js do
include FilteredSearchHelpers
let(:user) { create(:user) }
let(:group) { create(:group, :public) }
let(:label) { create(:group_label, group: group, title: 'bug') }
let!(:epic) { create(:epic, group: group, start_date: 10.days.ago, due_date: 5.days.ago) }
let(:filtered_search) { find('.filtered-search') }
let(:filter_author_dropdown) { find("#js-dropdown-author .filter-dropdown") }
let(:filter_label_dropdown) { find("#js-dropdown-label .filter-dropdown") }
before do
stub_licensed_features(epics: true)
sign_in(user)
visit group_epics_path(group)
end
context 'editing author token' do
before do
input_filtered_search('author:=@root', submit: false)
first('.tokens-container .filtered-search-token').click
end
it 'converts keyword into visual token' do
page.within('.tokens-container') do
expect(page).to have_selector('.js-visual-token')
expect(page).to have_content('Author')
end
end
it 'opens author dropdown' do
expect(page).to have_css('#js-dropdown-author', visible: true)
end
it 'makes value editable' do
expect_filtered_search_input('@root')
end
it 'filters value' do
filtered_search.send_keys(:backspace)
expect(page).to have_css('#js-dropdown-author .filter-dropdown .filter-dropdown-item', count: 1)
end
end
context 'editing label token' do
before do
input_filtered_search("label:=~#{label.title}", submit: false)
first('.tokens-container .filtered-search-token').click
end
it 'converts keyword into visual token' do
page.within('.tokens-container') do
expect(page).to have_selector('.js-visual-token')
expect(page).to have_content('Label')
end
end
it 'opens label dropdown' do
expect(filter_label_dropdown.find('.filter-dropdown-item', text: label.title)).to be_visible
expect(page).to have_css('#js-dropdown-label', visible: true)
end
it 'makes value editable' do
expect_filtered_search_input("~#{label.title}")
end
it 'filters value' do
expect(filter_label_dropdown.find('.filter-dropdown-item', text: label.title)).to be_visible
filtered_search.send_keys(:backspace)
filter_label_dropdown.find('.filter-dropdown-item')
expect(page.all('#js-dropdown-label .filter-dropdown .filter-dropdown-item').size).to eq(1)
end
end
end
| 29.174419 | 102 | 0.679155 |
4ad5f0ba3b1c4ed1510ed14d51221d4314f6c180 | 879 | module Capable
module ActsAsCapabilityRenewer
def self.included(base)
base.extend Capable::Base
base.extend ClassMethods
end
module ClassMethods
def acts_as_capability_renewer
has_many :capabilities, as: :renewer, :dependent => :destroy
include Capable::ActsAsCapabilityRenewer::InstanceMethods
end
end
module InstanceMethods
def create_capabilities(capable, abilities, active, expires_at)
if capable.present? and abilities.present? and self.capabilities.count == 0
abilities.each do |ability|
Capability.create_capability(capable, ability, active, expires_at, self)
end
end
end
def renew_capabilities(expires_at)
self.capabilities.each do |capability|
capability.renew(expires_at)
end
end
end
end
end
| 21.975 | 84 | 0.667804 |
1d61fb6f01d6034b1b5eb265415b1f5e0f2a8896 | 1,063 | #!/usr/bin/env ruby
#
# Graphite
# ===
#
# DESCRIPTION:
# I extend OnlyCheckOutput mutator specialy for Graphite.
# This mutator only send event output (so you don't need to use
# OnlyCheckOutput) and change parameter name if it is hostname
# for better view in Graphite.
#
# OUTPUT:
# event output with all dot changed to underline in host name
# If -r or --reverse parameter given script put hostname in
# reverse order for better graphite tree view
#
# PLATFORM:
# all
#
# DEPENDENCIES:
#
# json Ruby gem
#
# Copyright 2013 Peter Kepes <https://github.com/kepes>
#
# Released under the same terms as Sensu (the MIT license); see LICENSE
# for details.
require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'json'
# parse event
event = JSON.parse(STDIN.read, symbolize_names: true)
if ARGV[0] == '-r' || ARGV[0] == '--reverse'
puts event[:check][:output].gsub(event[:client][:name], event[:client][:name].split('.').reverse.join('.'))
else
puts event[:check][:output].gsub(event[:client][:name], event[:client][:name].gsub('.', '_'))
end
| 27.25641 | 109 | 0.687676 |
b9b9b6e4e880dbb7eb849c310308a1c0a7033858 | 2,243 | module UploadsActions
include Gitlab::Utils::StrongMemoize
include SendFileUpload
UPLOAD_MOUNTS = %w(avatar attachment file logo header_logo).freeze
def create
link_to_file = UploadService.new(model, params[:file], uploader_class).execute
respond_to do |format|
if link_to_file
format.json do
render json: { link: link_to_file }
end
else
format.json do
render json: 'Invalid file.', status: :unprocessable_entity
end
end
end
end
# This should either
# - send the file directly
# - or redirect to its URL
#
def show
return render_404 unless uploader&.exists?
expires_in 0.seconds, must_revalidate: true, private: true
disposition = uploader.image_or_video? ? 'inline' : 'attachment'
send_upload(uploader, attachment: uploader.filename, disposition: disposition)
end
private
def uploader_class
raise NotImplementedError
end
def upload_mount
mounted_as = params[:mounted_as]
mounted_as if UPLOAD_MOUNTS.include?(mounted_as)
end
def uploader_mounted?
upload_model_class < CarrierWave::Mount::Extension && !upload_mount.nil?
end
def uploader
strong_memoize(:uploader) do
if uploader_mounted?
model.public_send(upload_mount) # rubocop:disable GitlabSecurity/PublicSend
else
build_uploader_from_upload || build_uploader_from_params
end
end
end
def build_uploader_from_upload
return unless uploader = build_uploader
upload_paths = uploader.upload_paths(params[:filename])
upload = Upload.find_by(uploader: uploader_class.to_s, path: upload_paths)
upload&.build_uploader
end
def build_uploader_from_params
return unless uploader = build_uploader
uploader.retrieve_from_store!(params[:filename])
uploader
end
def build_uploader
return unless params[:secret] && params[:filename]
uploader = uploader_class.new(model, secret: params[:secret])
return unless uploader.model_valid?
uploader
end
def image_or_video?
uploader && uploader.exists? && uploader.image_or_video?
end
def find_model
nil
end
def model
strong_memoize(:model) { find_model }
end
end
| 22.656566 | 83 | 0.709318 |
7aa440e30f0a9ebf38ff92d66a07144160eb263d | 662 | default['gusztavvargadr_packer_dotnet']['default'] = {
'features' => {
# 'NetFx3' => {},
},
'native_packages' => {
'.NET Core 1.1.4 Runtime' => {
'source' => 'https://download.microsoft.com/download/6/F/B/6FB4F9D2-699B-4A40-A674-B7FF41E0E4D2/dotnet-win-x64.1.1.4.exe',
'install' => [
'/install',
'/quiet',
'/norestart',
],
},
'.NET Core 2.0.0 Runtime' => {
'source' => 'https://download.microsoft.com/download/5/6/B/56BFEF92-9045-4414-970C-AB31E0FC07EC/dotnet-runtime-2.0.0-win-x64.exe',
'install' => [
'/install',
'/quiet',
'/norestart',
],
},
},
}
| 27.583333 | 136 | 0.531722 |
abf9036cf815083a324c846095a61dd8ace310ad | 2,399 | require 'cinch'
require 'array_utility'
require_relative 'base_command'
require_relative '../wiki'
module Plugins
module Commands
class Abbreviate < AuthorizedCommand
include Cinch::Plugin
include Plugins::Wiki
using ArrayUtility
ignore_ignored_users
set(help: 'Abbreviates a mod for the Tilesheet extension. Op-only. 2 args: $abbrv <abbreviation> <mod name>',
plugin_name: 'abbrv')
match(/abbrv ([A-Z0-9\-]+) (.+)/i)
# Abbreviates the given mod with the given abbreviation. Fails when the
# mod or abbreviation are already on the list, or the user is not
# logged into LittleHelper. Will state the error code if there is any.
# @param msg [Cinch::Message]
# @param abbreviation [String] The abbreviation.
# @param mod [String] The mod name.
def execute(msg, abbreviation, mod)
abbreviation = abbreviation.upcase
escaped_mod = mod.gsub("'") { "\\'" }
edit('Module:Mods/list', msg, minor: true, summary: "Adding #{mod}") do |text|
if text =~ /[\s+]#{abbreviation} = \{\'/ || text =~ /[\s+]\["#{abbreviation}"\] = \{\'/
next { terminate: Proc.new { 'That abbreviation is already on the list.' } }
end
if text.include?("= {'#{mod}',")
next { terminate: Proc.new { 'The mod is already on the list.' } }
end
new_line = ' ' * 4
if abbreviation.include?('-')
new_line << "[\"#{abbreviation}\"]"
else
new_line << abbreviation
end
new_line << " = {'#{escaped_mod}', [=[<translate>#{mod}</translate>]=]},"
text_ary = text.split("\n")
text_ary.each_with_index do |line, index|
next unless line =~ /^[\s]+[\w]+ = {'/
ary = [new_line, line]
next unless ary == ary.sort
new_line.delete!(',', '') if text_ary.next(line) == '}'
text_ary.insert(index, new_line)
break
end
{
text: text_ary.join("\n"),
success: Proc.new { "Successfully abbreviated #{mod} as #{abbreviation}" },
fail: Proc.new { 'Failed! There was no change to the mod list' },
error: Proc.new { |e| "Failed! Error code: #{e.message}" },
summary: "Adding #{mod}"
}
end
end
end
end
end
| 38.079365 | 115 | 0.55148 |
62c7d1fb2fc775dbaf1e7e90b826fa46b2cfaf9f | 622 | class ContactsController < ApplicationController
before_action :find_candidate, only: %i[new create]
def new
@contact = Contact.new
end
def create
success = verify_recaptcha(action: 'contact_create', minimum_score: ENV['RECAPTCHA_MINIMUM_SCORE'].to_f)
@contact = @user.contacts.build(contact_params)
if success && @contact.save
redirect_to cv_section_path(@user.subdomain)
else
render 'contacts/errors'
end
end
private
def find_candidate
@user = User.find_by(id: contact_params[:user_id])
end
def contact_params
params.require(:contact).permit!
end
end
| 22.214286 | 108 | 0.71865 |
08009bf0d9cd69b35f922898fcf1f508b5aaa96d | 1,170 | require 'rails_helper'
describe Mutations::Cart::Update, type: :request do
let(:user) { create(:user) }
let(:account) { user.account }
let(:product) { create(:product, account: account) }
let!(:jwt_token) { generate_jwt_test_token(user) }
let(:name) { 'Spiritual Instinct' }
let(:query) do
<<~GQL
mutation {
updateCart (
input: {
quantity: 10
productId: "#{product.uuid}"
}
) {
cart {
cartItems {
product {
name
}
quantity
}
totalGross
totalNet
totalTax
totalDiscount
}
errors
}
}
GQL
end
describe 'update_cart' do
subject(:update_cart) do
post '/graphql', params: { query: query }, headers: { 'Authorization' => "Bearer #{jwt_token}" }
parse_graphql_response(response.body)['updateCart']
end
it { expect(update_cart['cart']).to include 'cartItems' => [{ 'product' => { 'name' => product.name }, 'quantity' => 10.0 }] }
it { is_expected.to include 'errors' => [] }
end
end
| 25.434783 | 130 | 0.516239 |
08bc809885762ecfbaf5aaea541ec5e3ce66a0f9 | 5,650 | require 'test_helper'
require 'json'
require 'webmock'
module Api
module V1
class SingleMessagesControllerTest < ActionController::TestCase
fixtures :all
def setup
@request.env["devise.mapping"] = Devise.mappings[:user]
@request.headers['Accept'] = Mime::JSON
@request.headers['Content-Type'] = Mime::JSON.to_s
end
test "action index" do
@request.headers["HTTP_EMAIL"]= '[email protected]'
@request.headers["HTTP_API_KEY"] = '561b7ec89b0ca61b250815b24e398ae'
resp = get :index
assert_response 200, resp.body
end
test "action show" do
@request.headers["HTTP_EMAIL"]= '[email protected]'
@request.headers["HTTP_API_KEY"] = '561b7ec89b0ca61b250815b24e398ae'
data_params={:id=>14}
resp = get :show,data_params
assert_response 200, resp.body
assert JSON.parse(resp.body)['number'].include?('5358428432')
end
test "action show wrong parameters" do
@request.headers["HTTP_EMAIL"]= '[email protected]'
@request.headers["HTTP_API_KEY"] = '561b7ec89b0ca61b250815b24e398ae'
data_params={:id=>146}
resp = get :show,data_params
assert_response 422, resp.body
end
test "create single message wrong parameters" do
@request.headers["HTTP_EMAIL"]= '[email protected]'
@request.headers["HTTP_API_KEY"] = '561b7ec89b0ca61b250815b24e398ae'
data_params={:single_message=>{:message=>"message test to api", :route=>'golAAdA',:numbers=>['5351627143']}}
resp = post :create , data_params
assert_response 422, resp.body
data_params={:single_message=>{ :route=>'golAAdA',:numbers=>['5351627143']}}
resp = post :create , data_params
assert_response 404, resp.body
data_params={:single_message=>{:message=>"message test to api" ,:numbers=>['5351627143']}}
resp = post :create , data_params
assert_response 404, resp.body
data_params={:single_message=>{:message=>"message test to api" ,:route=>'GoldA',:numbers=>['5451627143']}}
resp = post :create , data_params
assert_response 422, resp.body
end
#error en environmet development and test
# test "create single message ok" do
# @request.headers["HTTP_EMAIL"]= '[email protected]'
# @request.headers["HTTP_API_KEY"] = '561b7ec89b0ca61b250815b24e398ae'
# data_params={:single_message=>{:message=>"message test to api", :route=>'goldA',:numbers=>['5351627143']}}
# resp = post :create , data_params
# assert_response 200, resp.body
# end
test "destroy single message" do
@request.headers["HTTP_EMAIL"]= '[email protected]'
@request.headers["HTTP_API_KEY"] = '561b7ec89b0ca61b250815b24e408a1'
data_params= {:id=>14}
resp = delete :destroy , data_params
assert_response 301, resp.body
end
test "destroy single message wrong parameters" do
@request.headers["HTTP_EMAIL"]= '[email protected]'
@request.headers["HTTP_API_KEY"] = '561b7ec89b0ca61b250815b24e398ae'
data_params= {:id=>14}
resp = delete :destroy , data_params
assert_response 401, resp.body
@request.headers["HTTP_EMAIL"]= '[email protected]'
@request.headers["HTTP_API_KEY"] = '561b7ec89b0ca61b250815b24e408a1'
data_params={:id=>161}
delete :destroy,data_params
assert_response 422
end
test "send single message with authenticate in body" do
WebMock.disable!
resp=''
data_params={:authenticate_api=>{:email=>'[email protected]',:api_key=>'561b7ec89b0ca61b250815b24e398ae'},:single_message=>{:message=>"send test message",:route=>'Gold',:numbers=>["5356789032"]}}
assert_difference('SingleMessage.count') do
resp = post :create, data_params
end
assert_response 200,resp.body
end
test "destroy single message wrong parameters with authenticate in body" do
data_params= {:id=>14,:authenticate_api=>{:email=>'[email protected]',:api_key=>'561b7ec89b0ca61b250815b24e408a14'}}
resp = delete :destroy , data_params
assert_response 401, resp.body
data_params={:id=>161,:authenticate_api=>{:email=>'[email protected]',:api_key=>'561b7ec89b0ca61b250815b24e408a1'}}
delete :destroy,data_params
assert_response 422
end
test "action show wrong parameters with authenticate in body" do
data_params={:id=>146,:authenticate_api=>{:email=>'[email protected]',:api_key=>'561b7ec89b0ca61b250815b24e398ae'}}
resp = get :show,data_params
assert_response 422, resp.body
end
test "wrong api_key" do
data_params={:id=>146,:authenticate_api=>{:email=>'[email protected]',:api_key=>'x561b7ec89b0ca61b250815b24e398ae'}}
resp = get :show,data_params
assert_response 401, resp.body
data_params={:id=>146,:authenticate_api=>{:email=>'[email protected]'}}
resp = get :show,data_params
assert_response 400, resp.body
data_params={:id=>146,:authenticate_api=>{}}
resp = get :show,data_params
assert_response 400, resp.body
end
test "send single message with authenticate in body wrong" do
WebMock.disable!
data_params={:authenticate_api=>{:email=>'[email protected]',:api_key=>'561b7ec89b0ca61b250815b24e398aeXXXXXX'},:single_message=>{:message=>"send test message",:route=>'Gold',:numbers=>["5356789032"]}}
resp = post :create, data_params
assert_response 401,resp.body
end
end
end
end
| 41.544118 | 207 | 0.655221 |
91aa1105b0f0ec9c75cb6cfcdd6934d6523c4f4d | 229 | $LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'rubygems'
require 'faketwitter'
require 'spec'
require 'spec/autorun'
Spec::Runner.configure do |config|
end
| 22.9 | 66 | 0.755459 |
1c8bf2bf1488115ee17ac7e2786d38332cfee305 | 318 | class CreateAuthorCommentVotes < ActiveRecord::Migration[6.1]
def change
create_table :author_comment_votes do |t|
t.references :author, null: false, foreign_key: true
t.references :comment, null: false, foreign_key: true
t.integer :vote_value, default: 0
t.timestamps
end
end
end
| 26.5 | 61 | 0.707547 |
bf72a2508fde6370716bc83c1fa8fd0308acf22f | 120 | class AddRatingColToRecipeTable < ActiveRecord::Migration
def change
add_column :recipes, :rating, :int
end
end
| 20 | 57 | 0.766667 |
e8ae24b673352a2465f292ca7b7b796f35d10b9e | 2,304 | ### Calculate ProductOptionBridge
#
## ===== source columns ======
#
## ===== calculated columns ======
# :selling_price
#
class ProductOptionBridge < ApplicationRecord
belongs_to :connectable, polymorphic: true
belongs_to :product_option
JOIN_CONNECTABLE_QUERY = lambda do |klass|
resource_key = 'connectable'
klass = klass.to_s.constantize if klass.is_a?(String) || klass.is_a?(Symbol)
resource_id, resource_type = "#{resource_key}_id", "#{resource_key}_type"
"LEFT JOIN #{klass.table_name} ON #{klass.table_name}.id = #{table_name}.#{resource_id} AND #{table_name}.#{resource_type} = \"#{klass.name}\""
end
delegate :alive_barcodes_count, to: :connectable
scope :item_with, ->(product_item) { where(connectable: product_item).or(where(connectable: ProductCollection.item_with(product_item))) }
scope :option_with, ->(*option_ids) { where(product_option_id: option_ids) }
scope :connectables, -> { group(:connectable_type, :connectable_id).count.keys.map { |con| Object.const_get(con.first).find con.second } }
scope :joins_connectable, lambda {
get_sql = JOIN_CONNECTABLE_QUERY
joins(get_sql.call(ProductItem)).joins(get_sql.call(ProductCollection))
}
after_save :after_save_propagation
def active
connectable.active
end
alias active? active
def unit_count
connectable&.unit_count
end
def available_quantity
connectable.available_quantity
end
def items
case connectable_type
when 'ProductItem'
ProductItem.where(id: connectable_id)
when 'ProductCollection'
connectable.items
end
end
def brands
case connectable_type
when 'ProductItem'
[] << connectable.brand
when 'ProductCollection'
connectable.brands.uniq
end
end
## ===== before calculator =====
# def selling_price
# connectable&.selling_price.to_i
# end
# alias price selling_price
## ===== Calculators =====
def calc_selling_price
connectable&.selling_price.to_i
end
def calculate_price_columns
self.selling_price = calc_selling_price
print_columns :selling_price
end
private
## ===== ActiveRecord Callbacks =====
def after_save_propagation
product_option.tap do |option|
option.calculate_price_columns
option.save
end
end
end
| 24.510638 | 147 | 0.708333 |
015b1da191441585ed22dc238e8e28c87982c431 | 653 |
require 'async/mysql/client'
RSpec.describe Async::MySQL::Client do
include_context Async::RSpec::Reactor
let(:connection) {Async::MySQL::Client.new(host: 'localhost', database: 'test')}
it "should execute query" do
reactor.async do
results = connection.query("SELECT 42 AS LIFE")
expect(results.each.to_a).to be == [{"LIFE" => 42}]
connection.close
end
end
it "can stream results" do
results = connection.query("SELECT * FROM seq_1_to_3", stream: true)
rows = [{"seq" => 1}, {"seq" => 2}, {"seq" => 3}].each
results.each do |fields|
expect(fields).to be == rows.next
end
connection.close
end
end
| 21.064516 | 81 | 0.652374 |
e959a796b9320e105dc06606073790d575b876ba | 1,142 | # http://www.jroller.com/obie/tags/unicode
class String
class << self
def unpack(string)
return ActiveSupport::Multibyte::Chars.g_unpack(string).collect{ |c| c[0] } if ActiveSupport::Multibyte::Chars.respond_to?(:g_unpack)
string.split('').collect{ |c| c.chars[0] }
end
end
def to_ascii
# split in muti-byte aware fashion and translate characters over 127
# and dropping characters not in the translation hash
String.unpack(self).collect{ |c| (c <= 127) ? c.chr : translation_hash[c] }.join
end
protected
def translation_hash
@@translation_hash ||= setup_translation_hash
end
def setup_translation_hash
accented_chars = String.unpack("ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüý")
unaccented_chars = "AAAAAACEEEEIIIIDNOOOOOxOUUUUYaaaaaaceeeeiiiinoooooouuuuy".split('')
translation_hash = {}
accented_chars.each_with_index { |char, idx| translation_hash[char] = unaccented_chars[idx] }
translation_hash[String.unpack("Æ").first] = 'AE'
translation_hash[String.unpack("æ").first] = 'ae'
translation_hash
end
end | 36.83871 | 139 | 0.706655 |
7abac9e58d5e495c6c01cb755ad1e694daac8961 | 1,050 | cask 'casio-screen-receiver' do
version '3.02,b:4'
sha256 '5eaff7fd7894d483534d82e7fbc6b77a6d304afa580e10b1c7bce38a3a69e07a'
url "https://edu.casio.com/education/support_software/dl/screen_Receiver/screenrecv_inst_#{version.before_comma.no_dots}#{version.after_comma.before_colon}_#{version.after_colon}.zip"
name 'Casio Screen Receiver'
homepage 'https://edu.casio.com/education/support_software/'
pkg "ScreenReceiver_Ver.#{version.before_comma}_#{version.after_comma.before_colon}.pkg"
uninstall pkgutil: [
'com.casio.fx.ScreenReceiver.ScreenReceiver',
'com.casio.fx.ScreenReceiver.fxASPIDriver',
'com.casio.fx.ScreenReceiver.fxSRManual',
],
delete: '/Applications/CASIO/ScreenReceiver.app',
rmdir: '/Applications/CASIO'
zap delete: '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.casio.fx.screenreceiver.sfl'
caveats do
reboot
end
end
| 42 | 185 | 0.712381 |
d5015343465ef4d7a6a9003e2cc3df928c119ff1 | 79 | module WebSql
class ApplicationController < ActionController::Base
end
end
| 15.8 | 54 | 0.810127 |
1ad74c23e83c012c1c6b74a60723532ae50cdd08 | 72 | module ISO8601
##
# The gem version
VERSION = '0.11.0'.freeze
end
| 12 | 27 | 0.638889 |
79da0f53ac3ded097f21d144e346f9f3f8d20568 | 21 | require 'mauth/rack'
| 10.5 | 20 | 0.761905 |
21b1d167f3312d8328fe4ff7aeaaf27b694b53b1 | 295 | default['packagecloud']['base_repo_path'] = "/install/repositories/"
default['packagecloud']['gpg_key_path'] = "/gpgkey"
default['packagecloud']['hostname_override'] = nil
default['packagecloud']['default_type'] = value_for_platform_family(
'debian' => 'deb',
['rhel', 'fedora'] => 'rpm'
)
| 32.777778 | 68 | 0.698305 |
91a1b41bef71f20039c8844b3c7d77a36ceba400 | 896 | module RBKubeMQ
class Streamer < Faye::WebSocket::Client
include Check
def initialize(client:, client_id: nil, channel: nil, meta: nil, store: false)
is_class?(client, [RBKubeMQ::Client], "client")
@client = client
@client_id = client_id
@channel = channel
@meta = meta.nil? ? meta.to_s : meta
@store = store
super("#{@client.ws}/send/stream")
end
attr_reader :client_id, :channel, :meta, :store
def send(message, meta: @meta, store: @store, client_id: @client_id,
channel: @channel, id: nil)
body = {
"EventID" => id,
"ClientID" => client_id,
"Channel" => channel,
"Metadata" => meta,
"Body" => message,
"Store" => store
}
super(RBKubeMQ::Utility.dump(body))
rescue StandardError => e
raise RBKubeMQ::Error.new(e.message)
end
end
end
| 27.151515 | 82 | 0.581473 |
796380bbed9c893abc1a888c4996e400c7d8f297 | 3,071 | cask 'markdown-service-tools' do
version '2.14'
sha256 'd0f48be1acaae6ad46370869501b44fdcc765fbe3f1ca8594a766273fc9c128f'
url "http://cdn3.brettterpstra.com/downloads/MarkdownServiceTools#{version}.zip"
name 'Markdown Service Tools'
homepage 'http://brettterpstra.com/projects/markdown-service-tools/'
service "MarkdownServiceTools#{version}/md - Code - Make Code Block.workflow"
service "MarkdownServiceTools#{version}/md - Convert - HTML to Clipboard.workflow"
service "MarkdownServiceTools#{version}/md - Convert - HTML to Markdown.workflow"
service "MarkdownServiceTools#{version}/md - Convert - MultiMarkdown to HTML.workflow"
service "MarkdownServiceTools#{version}/md - Convert - MultiMarkdown to RTF.workflow"
service "MarkdownServiceTools#{version}/md - Convert - Strip Markdown.workflow"
service "MarkdownServiceTools#{version}/md - Emphasis - Bold.workflow"
service "MarkdownServiceTools#{version}/md - Emphasis - Italics.workflow"
service "MarkdownServiceTools#{version}/md - Footnotes - Convert Inline Format.workflow"
service "MarkdownServiceTools#{version}/md - Footnotes - Make IDs Unique.workflow"
service "MarkdownServiceTools#{version}/md - Images - Image Link.workflow"
service "MarkdownServiceTools#{version}/md - Indentation - Indent.workflow"
service "MarkdownServiceTools#{version}/md - Indentation - Outdent.workflow"
service "MarkdownServiceTools#{version}/md - Links - Auto-link Wikipedia.workflow"
service "MarkdownServiceTools#{version}/md - Links - Chrome Tabs.workflow"
service "MarkdownServiceTools#{version}/md - Links - Clipboard.workflow"
service "MarkdownServiceTools#{version}/md - Links - Flip Link Style.workflow"
service "MarkdownServiceTools#{version}/md - Links - New Link.workflow"
service "MarkdownServiceTools#{version}/md - Links - Safari Tabs.workflow"
service "MarkdownServiceTools#{version}/md - Links - Self-Link URLs.workflow"
service "MarkdownServiceTools#{version}/md - Links - To References.workflow"
service "MarkdownServiceTools#{version}/md - Lists - Bullet List.workflow"
service "MarkdownServiceTools#{version}/md - Lists - Copy without delimiter.workflow"
service "MarkdownServiceTools#{version}/md - Lists - Fix Numbered List.workflow"
service "MarkdownServiceTools#{version}/md - Lists - Numbered List.workflow"
service "MarkdownServiceTools#{version}/md - Paragraphs - Blockquote.workflow"
service "MarkdownServiceTools#{version}/md - Paragraphs - Compress Empty Lines.workflow"
service "MarkdownServiceTools#{version}/md - Paragraphs - Preserve Line Breaks.workflow"
service "MarkdownServiceTools#{version}/md - Paragraphs - Unwrap.workflow"
service "MarkdownServiceTools#{version}/md - Tables - Cleanup.workflow"
service "MarkdownServiceTools#{version}/md - Tables - Create from CSV.workflow"
service "MarkdownServiceTools#{version}/md - Wrap - Angle Brackets.workflow"
service "MarkdownServiceTools#{version}/md - Wrap - Parenthesis.workflow"
service "MarkdownServiceTools#{version}/md - Wrap - Square Brackets.workflow"
end
| 69.795455 | 90 | 0.778248 |
e95327c4822b5c73910c8c68cc2cc36d17af9c39 | 1,028 | require 'java'
require 'jolt-core'
require 'multi_json'
require 'jruby-jolt/namespace'
require 'jruby-jolt/errors'
require 'jruby-jolt/chainr'
require 'jruby-jolt/spec_store'
module Jolt
@specs = Jolt::SpecStore.new
class << self
attr_reader :specs
def spec(name)
@specs[name]
end
def load_spec_from_file(name, file)
@specs[name] = Jolt::Chainr.from_spec(MultiJson.load(File.read(file)))
end
def load_spec_from_data(name, data)
@specs[name] = Jolt::Chainr.from_spec(data)
end
def load_spec(name, spec)
case spec
when String
load_spec_from_file(name, spec)
when Hash, Array
load_spec_from_data(name, spec)
else
raise "Invalid spec input. Please provide the file path or parsed JSON data."
end
end
def clear_specs
@specs.clear
end
def transform(name, data)
raise Jolt::SpecError.new("Spec not found: #{name}") unless @specs[name]
@specs[name].transform(data)
end
end
end
| 20.156863 | 85 | 0.655642 |
bbe9a14c20e487a995833456be344ca501dbf97a | 158 | class User < ApplicationRecord
belongs_to :authentication
has_many :messages
delegate :email, to: :authentication, prefix: false, allow_nil: false
end
| 22.571429 | 71 | 0.778481 |
8764f4bf85f088585ee4bead2232ff051ccd1a35 | 1,173 | # Watch for any rails server exceptions and write the stacktrace to ./tmp/test_bot/exception.txt
# This file is checked for by assert_no_exceptions
module EffectiveTestBot
class Middleware
def initialize(app)
@app = app
end
def call(env)
begin
@app.call(env)
rescue Exception => exception
begin
save(exception)
rescue => e
puts "TestBotError: An error occurred while attempting to save a rails server exception: #{e.message}"
end
raise exception
end
end
def save(exception)
lines = [exception.message] + exception.backtrace.first(EffectiveTestBot&.backtrace_lines || 10)
dir = File.join(Dir.pwd, 'tmp', 'test_bot')
file = File.join(dir, 'exception.txt')
Dir.mkdir(dir) unless File.exist?(dir)
File.delete(file) if File.exist?(file)
File.open(file, 'w') do |file|
file.write "================== Start server exception ==================\n"
lines.each { |line| file.write(line); file.write("\n") }
file.write "=================== End server exception ===================\n"
end
end
end
end
| 28.609756 | 112 | 0.589088 |
1c94522ae0bbd26bd6ef4ef59e74147a9457b80b | 1,468 | require 'priority_queue'
module Algorithms
class DijkstraService
def initialize(list, start, finish)
@nodes = list.nodes
@start = @nodes.find(start)
@finish = @nodes.find(finish)
@queue = PriorityQueue.new
@maxint = (2**(0.size * 8 -2) -1)
@distances = {}
@previous = {}
end
def process
fill_queues
calculate_path
end
def fill_queues
@nodes.each do |node|
if node.info == @start.info
@distances[node.info] = 0
@queue[node.info] = 0
else
@distances[node.info] = @maxint
@queue[node.info] = @maxint
end
@previous[node.info] = nil
end
end
def calculate_path
while @queue
smallest = @queue.delete_min_return_key
if smallest == @finish.info
path = []
while @previous[smallest]
path.push(smallest)
smallest = @previous[smallest]
end
return path
end
if smallest == nil or @distances[smallest] == @maxint
break
end
@nodes.find_by(info: smallest).arcs.each do |arc|
alt = @distances[smallest] + arc.weight
neighbor = arc.connection.info
if alt < @distances[neighbor]
@distances[neighbor] = alt
@previous[neighbor] = smallest
@queue[neighbor] = alt
end
end
end
end
end
end
| 22.242424 | 61 | 0.535422 |
385fc5cd7e733207c8e49fcc744e3850b633f103 | 1,917 | # A wiki page
class WikiPage < ActiveRecord::Base
has_many :revisions, :class_name => 'WikiRevision', :order => 'id'
has_many :references, :class_name => 'WikiReference', :order => 'referenced_name'
has_one :current_revision, :class_name => 'WikiRevision', :order => 'id DESC'
belongs_to :company
has_many :event_logs, :as => :target, :dependent => :destroy, :order => 'id DESC'
LOCKING_PERIOD = 30.minutes
def lock(time, locked_by)
update_attributes(:locked_at => time, :locked_by => locked_by)
end
def lock_duration(time)
((time - locked_at) / 60).to_i unless locked_at.nil?
end
def unlock
update_attributes(:locked_at => nil, :locked_by => nil)
end
def locked?
locked_at + LOCKING_PERIOD > Time.now.utc unless locked_at.nil?
end
def locked_by
User.find( self.attributes['locked_by'] ) unless self.attributes['locked_by'].nil?
end
# SELECT wiki_pages.* FROM wiki_pages LEFT OUTER JOIN wiki_references w_r ON wiki_pages.id = w_r.wiki_page_id WHERE w_r.referenced_name = 'pagename';
def pages_linking_here
@refs ||= WikiPage.find(:all, :select => "wiki_pages.*", :joins => "LEFT OUTER JOIN wiki_references w_r ON wiki_pages.id = w_r.wiki_page_id", :conditions => ["w_r.referenced_name = ? AND wiki_pages.company_id = ?", self.name, self.company_id])
end
def to_url
"<a href=\"/wiki/show/#{URI.encode(name)}\">#{name}</a>"
end
def body
current_revision.body
end
def user
current_revision.user
end
def revision(rev = 0)
rev > 0 ? self.revisions[rev-1] : current_revision
end
def to_html(rev = 0)
if rev > 0
self.revisions[rev-1].to_html
else
current_revision.to_html
end
end
def to_plain_html(rev = 0)
if rev > 0
self.revisions[rev-1].to_plain_html
else
current_revision.to_plain_html
end
end
def started_at
self.created_at
end
end
| 25.223684 | 247 | 0.678143 |
ab75df357b5697d116335ca84286e0a49f877773 | 279 | module CIMaestro::Utils
module Reflection
def instance_variables_as_hash
instance_variables.inject({}) do |hash, ivar|
attr_reader_name =ivar.gsub('@', '').to_sym
hash.merge(attr_reader_name => self.send(attr_reader_name))
end
end
end
end
| 25.363636 | 67 | 0.681004 |
e28e64e9bc215b94ebbf2b57dfb4d01b0a65cfda | 340 | module Faker
class ElderScrolls < Base
class << self
def race
fetch('elder_scrolls.race')
end
def creature
fetch('elder_scrolls.creature')
end
def region
fetch('elder_scrolls.region')
end
def dragon
fetch('elder_scrolls.dragon')
end
end
end
end
| 15.454545 | 39 | 0.570588 |
21ae43aded5b75eb8afe2ade0922216e0641a84f | 897 | class Ocamlbuild < Formula
desc "Generic build tool for OCaml"
homepage "https://github.com/ocaml/ocamlbuild"
url "https://github.com/ocaml/ocamlbuild/archive/0.14.0.tar.gz"
sha256 "87b29ce96958096c0a1a8eeafeb6268077b2d11e1bf2b3de0f5ebc9cf8d42e78"
head "https://github.com/ocaml/ocamlbuild.git"
bottle do
sha256 "5bc4b5c08dc6bb9b5ed2fedff2de70870ca2400ccaf1002ac8919ad26181a4ee" => :mojave
sha256 "0b9fe3df0844b3c7f276e595b75b609611e55be4efa080dc2be10586630dea67" => :high_sierra
sha256 "78f4e83ddb5c5727047f2ed027706c70a76ff16004e24a4c35efda6239175a99" => :sierra
end
depends_on "ocaml"
def install
system "make", "configure", "OCAMLBUILD_BINDIR=#{bin}", "OCAMLBUILD_LIBDIR=#{lib}", "OCAMLBUILD_MANDIR=#{man}"
system "make"
system "make", "install"
end
test do
assert_match version.to_s, shell_output("#{bin}/ocamlbuild --version")
end
end
| 34.5 | 114 | 0.764771 |
33d6cf38ca54f76a4d9c611bf8279cf088bf5a02 | 4,938 | require "spec_helper"
require "httpi/adapter/httpclient"
require "httpi/request"
HTTPI::Adapter.load_adapter(:httpclient)
describe HTTPI::Adapter::HTTPClient do
let(:adapter) { HTTPI::Adapter::HTTPClient.new(request) }
let(:httpclient) { HTTPClient.any_instance }
let(:ssl_config) { HTTPClient::SSLConfig.any_instance }
let(:request) { HTTPI::Request.new("http://example.com") }
describe "#request(:get)" do
it "returns a valid HTTPI::Response" do
httpclient_expects(:get)
adapter.request(:get).should match_response(:body => Fixture.xml)
end
end
describe "#request(:post)" do
it "returns a valid HTTPI::Response" do
request.body = Fixture.xml
httpclient_expects(:post)
adapter.request(:post).should match_response(:body => Fixture.xml)
end
end
describe "#request(:head)" do
it "returns a valid HTTPI::Response" do
httpclient_expects(:head)
adapter.request(:head).should match_response(:body => Fixture.xml)
end
end
describe "#request(:put)" do
it "returns a valid HTTPI::Response" do
request.body = Fixture.xml
httpclient_expects(:put)
adapter.request(:put).should match_response(:body => Fixture.xml)
end
end
describe "#request(:delete)" do
it "returns a valid HTTPI::Response" do
httpclient_expects(:delete)
adapter.request(:delete).should match_response(:body => Fixture.xml)
end
end
describe "#request(:custom)" do
it "returns a valid HTTPI::Response" do
httpclient_expects(:custom)
adapter.request(:custom).should match_response(:body => Fixture.xml)
end
end
describe "settings:" do
before { httpclient.stubs(:request).returns(http_message) }
describe "proxy" do
it "have should specs"
end
describe "connect_timeout" do
it "is not set unless specified" do
httpclient.expects(:connect_timeout=).never
adapter.request(:get)
end
it "is set if specified" do
request.open_timeout = 30
httpclient.expects(:connect_timeout=).with(30)
adapter.request(:get)
end
end
describe "receive_timeout" do
it "is not set unless specified" do
httpclient.expects(:receive_timeout=).never
adapter.request(:get)
end
it "is set if specified" do
request.read_timeout = 30
httpclient.expects(:receive_timeout=).with(30)
adapter.request(:get)
end
end
describe "set_auth" do
it "is set for HTTP basic auth" do
request.auth.basic "username", "password"
httpclient.expects(:set_auth).with(request.url, *request.auth.credentials)
adapter.request(:get)
end
it "is set for HTTP digest auth" do
request.auth.digest "username", "password"
httpclient.expects(:set_auth).with(request.url, *request.auth.credentials)
adapter.request(:get)
end
end
context "(for SSL client auth)" do
before do
request.auth.ssl.cert_key_file = "spec/fixtures/client_key.pem"
request.auth.ssl.cert_file = "spec/fixtures/client_cert.pem"
end
it "client_cert, client_key and verify_mode should be set" do
ssl_config.expects(:client_cert=).with(request.auth.ssl.cert)
ssl_config.expects(:client_key=).with(request.auth.ssl.cert_key)
ssl_config.expects(:verify_mode=).with(request.auth.ssl.openssl_verify_mode)
adapter.request(:get)
end
it "sets the client_ca if specified" do
request.auth.ssl.ca_cert_file = "spec/fixtures/client_cert.pem"
ssl_config.expects(:add_trust_ca).with(request.auth.ssl.ca_cert_file)
adapter.request(:get)
end
it 'should set the ssl_version if specified' do
request.auth.ssl.ssl_version = :SSLv3
ssl_config.expects(:ssl_version=).with(request.auth.ssl.ssl_version)
adapter.request(:get)
end
end
context "(for SSL client auth with a verify mode of :none with no certs provided)" do
before do
request.auth.ssl.verify_mode = :none
end
it "verify_mode should be set" do
ssl_config.expects(:verify_mode=).with(request.auth.ssl.openssl_verify_mode)
adapter.request(:get)
end
it "does not set client_cert and client_key "do
ssl_config.expects(:client_cert=).never
ssl_config.expects(:client_key=).never
adapter.request(:get)
end
it "does not raise an exception" do
expect { adapter.request(:get) }.to_not raise_error
end
end
end
def httpclient_expects(method)
httpclient.expects(:request).
with(method, request.url, nil, request.body, request.headers).
returns(http_message)
end
def http_message(body = Fixture.xml)
message = HTTP::Message.new_response body
message.header.set "Accept-encoding", "utf-8"
message
end
end
| 28.056818 | 89 | 0.663832 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.