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
1a6e860777d76e698cc4a41f26a0b14e964d0dd9
3,753
require "spec_helper" require "net/http" require "securerandom" require "timeout" require "support/test_env" require "support/app_crud_helpers" describe "App CRUD" do include AppCrudHelpers with_user_with_org with_new_space with_time_limit let(:app_content) { "#{SecureRandom.uuid}_#{Time.now.to_i}" } let(:language) { ENV["NYET_APP"] || "java" } let(:app_name) { "crud-#{language}" } attr_reader :route it "creates/updates/deletes an app" do begin monitoring.record_action(:full_run) do monitoring.record_action(:create) do regular_user.clean_up_app_from_previous_run(app_name) @app = regular_user.create_app(@space, app_name, CUSTOM_VAR: app_content) regular_user.clean_up_route_from_previous_run(app_name) @route = regular_user.create_route(@app, app_name, TestEnv.default.apps_domain) end monitoring.record_action(:read) do if path = APPS[language] deploy_app(@app, path) else raise "NYET_APP was set to #{ENV["NYET_APP"].inspect}, must be one of #{APPS.keys.to_s} (or nil)" end end monitoring.record_action(:start) do start_app_and_wait_until_up(@app) end monitoring.record_action(:app_routable) do check_app_routable end monitoring.record_action(:update) do scale_app(@app) check_running_instances(@app) check_first_instance_reachable check_second_instance_reachable end monitoring.record_action(:delete) do @route.delete! @app.delete! check_app_api_unavailable(regular_user, app_name) check_app_uri_unavailable end end monitoring.record_metric("crud_app.health", 1) rescue => e monitoring.record_metric("crud_app.health", 0) raise e end end def check_app_routable puts "starting #{__method__} (#{Time.now})" count = 0 Timeout::timeout(ROUTING_TIMEOUT) do content = nil while content !~ /^It just needed to be restarted!/ count += 1 puts "checking that http://#{route.host}.#{route.domain.name} is routable attempt: #{count}." content = page_content rescue nil sleep 0.2 end end expect(page_content).to include(app_content) end def scale_app(app) puts "starting #{__method__} (#{Time.now})" app.total_instances = 2 app.update! sleep(CHECK_DELAY) until app.running? end def check_running_instances(app) puts "Running instances: #{app.running_instances}" end def check_first_instance_reachable puts "starting #{__method__} (#{Time.now})" sleep(CHECK_DELAY) until page_content.include?('"instance_index":0') end def check_second_instance_reachable puts "starting #{__method__} (#{Time.now})" sleep(CHECK_DELAY) until page_content.include?('"instance_index":1') end def check_app_uri_unavailable puts "starting #{__method__} (#{Time.now})" app_uri = URI("http://#{route.name}") response = Net::HTTP.get_response(app_uri) puts "--- GET #{app_uri}: #{response.class}" while response.is_a?(Net::HTTPSuccess) puts "--- GET #{app_uri}: #{response.class}" sleep(CHECK_DELAY) response = Net::HTTP.get_response(app_uri) end end def check_app_api_unavailable(user, app_name) puts "starting #{__method__} (#{Time.now})" apps = user.list_apps.select { |app| app.name == app_name } while apps.size > 0 puts "--- verifying apps removed from cc" p apps: apps.map { |a| a.name } sleep(CHECK_DELAY) apps = user.list_apps.select { |app| app.name == app_name } end end end
27.195652
109
0.653877
3807595e09af00a51209e529169f9f21ff3b2abb
468
module Fiken class Payment include Virtus.model include ActiveModel::Validations attribute :uuid, String attribute :date, DateTime attribute :account, String attribute :amount, Integer def to_hash result = { account: account, amount: amount } result["uuid"] = uuid if(uuid) result["date"] = date.strftime("%Y-%m-%d") result end end end
22.285714
51
0.547009
21cdb72bf03d5eba68ec05e2cd98829eed900c14
988
class BatsCore < Formula desc "Bash Automated Testing System" homepage "https://github.com/bats-core/bats-core" url "https://github.com/bats-core/bats-core/archive/v1.4.1.tar.gz" sha256 "bff517da043ae24440ec8272039f396c2a7907076ac67693c0f18d4a17c08f7d" license "MIT" bottle do sha256 cellar: :any_skip_relocation, x86_64_linux: "483259b5fb07dab08336816777a08467303bf3da7828f2ff75a7d08ccf9cfc73" # linuxbrew-core end depends_on "coreutils" uses_from_macos "bc" => :test conflicts_with "bats", because: "both install `bats` executables" def install system "./install.sh", prefix # Replace `/usr/local` references for uniform bottles inreplace lib/"bats-core/formatter.bash", "/usr/local", HOMEBREW_PREFIX end test do (testpath/"test.sh").write <<~EOS @test "addition using bc" { result="$(echo 2+2 | bc)" [ "$result" -eq 4 ] } EOS assert_match "addition", shell_output("#{bin}/bats test.sh") end end
29.058824
138
0.703441
26e39ffaffdbebea6f8e29fca507433e3839509e
33,010
require 'spec_helper' require 'securerandom' require 'ddtrace' require 'ddtrace/configuration/settings' RSpec.describe Datadog::Configuration::Settings do subject(:settings) { described_class.new } describe '#analytics' do describe '#enabled' do subject(:enabled) { settings.analytics.enabled } context "when #{Datadog::Ext::Analytics::ENV_TRACE_ANALYTICS_ENABLED}" do around do |example| ClimateControl.modify(Datadog::Ext::Analytics::ENV_TRACE_ANALYTICS_ENABLED => environment) do example.run end end context 'is not defined' do let(:environment) { nil } it { is_expected.to be nil } end context 'is defined' do let(:environment) { 'true' } it { is_expected.to be true } end end end describe '#enabled=' do it 'changes the #enabled setting' do expect { settings.analytics.enabled = true } .to change { settings.analytics.enabled } .from(nil) .to(true) end end end describe '#analytics_enabled' do subject(:analytics_enabled) { settings.analytics_enabled } let(:value) { double } before { expect(settings.analytics).to receive(:enabled).and_return(value) } it 'retrieves the value from the new setting' do is_expected.to be value end end describe '#analytics_enabled=' do it 'changes the new #enabled setting' do expect { settings.analytics_enabled = true } .to change { settings.analytics.enabled } .from(nil) .to(true) end end describe '#api_key' do subject(:api_key) { settings.api_key } context "when #{Datadog::Ext::Environment::ENV_API_KEY}" do around do |example| ClimateControl.modify(Datadog::Ext::Environment::ENV_API_KEY => api_key_env) do example.run end end context 'is not defined' do let(:api_key_env) { nil } it { is_expected.to be nil } end context 'is defined' do let(:api_key_env) { SecureRandom.uuid.delete('-') } it { is_expected.to eq(api_key_env) } end end end describe '#api_key=' do subject(:set_api_key) { settings.api_key = api_key } context 'when given a value' do let(:api_key) { SecureRandom.uuid.delete('-') } before { set_api_key } it { expect(settings.api_key).to eq(api_key) } end end describe '#diagnostics' do describe '#debug' do subject(:debug) { settings.diagnostics.debug } it { is_expected.to be false } context "when #{Datadog::Ext::Diagnostics::DD_TRACE_DEBUG}" do around do |example| ClimateControl.modify(Datadog::Ext::Diagnostics::DD_TRACE_DEBUG => environment) do example.run end end context 'is not defined' do let(:environment) { nil } it { is_expected.to be false } end context 'is set to true' do let(:environment) { 'true' } it { is_expected.to be true } end context 'is set to false' do let(:environment) { 'false' } it { is_expected.to be false } end end end describe '#debug=' do context 'enabled' do subject(:set_debug) { settings.diagnostics.debug = true } after { settings.diagnostics.debug = false } it 'updates the #debug setting' do expect { set_debug }.to change { settings.diagnostics.debug }.from(false).to(true) end it 'requires debug dependencies' do expect_any_instance_of(Object).to receive(:require).with('pp') set_debug end end context 'disabled' do subject(:set_debug) { settings.diagnostics.debug = false } it 'does not require debug dependencies' do expect_any_instance_of(Object).to_not receive(:require) set_debug end end end describe '#health_metrics' do describe '#enabled' do subject(:enabled) { settings.diagnostics.health_metrics.enabled } context "when #{Datadog::Ext::Diagnostics::Health::Metrics::ENV_ENABLED}" do around do |example| ClimateControl.modify(Datadog::Ext::Diagnostics::Health::Metrics::ENV_ENABLED => environment) do example.run end end context 'is not defined' do let(:environment) { nil } it { is_expected.to be false } end context 'is defined' do let(:environment) { 'true' } it { is_expected.to be true } end end end describe '#enabled=' do it 'changes the #enabled setting' do expect { settings.diagnostics.health_metrics.enabled = true } .to change { settings.diagnostics.health_metrics.enabled } .from(false) .to(true) end end describe '#statsd' do subject(:statsd) { settings.diagnostics.health_metrics.statsd } it { is_expected.to be nil } end describe '#statsd=' do let(:statsd) { double('statsd') } it 'changes the #statsd setting' do expect { settings.diagnostics.health_metrics.statsd = statsd } .to change { settings.diagnostics.health_metrics.statsd } .from(nil) .to(statsd) end end end end describe '#distributed_tracing' do describe '#propagation_extract_style' do subject(:propagation_extract_style) { settings.distributed_tracing.propagation_extract_style } context "when #{Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_EXTRACT_ENV}" do around do |example| ClimateControl.modify(Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_EXTRACT_ENV => environment) do example.run end end context 'is not defined' do let(:environment) { nil } it do is_expected.to eq( [ Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_DATADOG, Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_B3, Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_B3_SINGLE_HEADER ] ) end end context 'is defined' do let(:environment) { 'B3,B3 single header' } it do is_expected.to eq( [ Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_B3, Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_B3_SINGLE_HEADER ] ) end end end context "when #{Datadog::Ext::DistributedTracing::PROPAGATION_EXTRACT_STYLE_ENV_OLD}" do around do |example| ClimateControl.modify(Datadog::Ext::DistributedTracing::PROPAGATION_EXTRACT_STYLE_ENV_OLD => environment) do example.run end end context 'is not defined' do let(:environment) { nil } it do is_expected.to eq( [ Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_DATADOG, Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_B3, Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_B3_SINGLE_HEADER ] ) end end context 'is defined' do let(:environment) { 'B3,B3 single header' } it do is_expected.to eq( [ Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_B3, Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_B3_SINGLE_HEADER ] ) end end end end describe '#propagation_inject_style' do subject(:propagation_inject_style) { settings.distributed_tracing.propagation_inject_style } context "when #{Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_INJECT_ENV}" do around do |example| ClimateControl.modify(Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_INJECT_ENV => environment) do example.run end end context 'is not defined' do let(:environment) { nil } it { is_expected.to eq([Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_DATADOG]) } end context 'is defined' do let(:environment) { 'Datadog,B3' } it do is_expected.to eq( [ Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_DATADOG, Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_B3 ] ) end end end context "when #{Datadog::Ext::DistributedTracing::PROPAGATION_INJECT_STYLE_ENV_OLD}" do around do |example| ClimateControl.modify(Datadog::Ext::DistributedTracing::PROPAGATION_INJECT_STYLE_ENV_OLD => environment) do example.run end end context 'is not defined' do let(:environment) { nil } it { is_expected.to eq([Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_DATADOG]) } end context 'is defined' do let(:environment) { 'Datadog,B3' } it do is_expected.to eq( [ Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_DATADOG, Datadog::Ext::DistributedTracing::PROPAGATION_STYLE_B3 ] ) end end end end end describe '#env' do subject(:env) { settings.env } context "when #{Datadog::Ext::Environment::ENV_ENVIRONMENT}" do around do |example| ClimateControl.modify(Datadog::Ext::Environment::ENV_ENVIRONMENT => environment) do example.run end end context 'is not defined' do let(:environment) { nil } it { is_expected.to be nil } end context 'is defined' do let(:environment) { 'env-value' } it { is_expected.to eq(environment) } end end end describe '#env=' do subject(:set_env) { settings.env = env } context 'when given a value' do let(:env) { 'custom-env' } before { set_env } it { expect(settings.env).to eq(env) } end end describe '#logger' do describe '#instance' do subject(:instance) { settings.logger.instance } it { is_expected.to be nil } end describe '#instance=' do let(:logger) do double(:logger, debug: true, info: true, warn: true, error: true, level: true) end it 'updates the #instance setting' do expect { settings.logger.instance = logger } .to change { settings.logger.instance } .from(nil) .to(logger) end end describe '#level' do subject(:level) { settings.logger.level } it { is_expected.to be ::Logger::INFO } end describe 'level=' do let(:level) { ::Logger::DEBUG } it 'changes the #statsd setting' do expect { settings.logger.level = level } .to change { settings.logger.level } .from(::Logger::INFO) .to(level) end end end describe '#logger=' do let(:logger) { Datadog::Logger.new(STDOUT) } it 'sets the logger instance' do expect { settings.logger = logger }.to change { settings.logger.instance } .from(nil) .to(logger) end end describe '#report_hostname' do subject(:report_hostname) { settings.report_hostname } context "when #{Datadog::Ext::NET::ENV_REPORT_HOSTNAME}" do around do |example| ClimateControl.modify(Datadog::Ext::NET::ENV_REPORT_HOSTNAME => environment) do example.run end end context 'is not defined' do let(:environment) { nil } it { is_expected.to be false } end context 'is defined' do let(:environment) { 'true' } it { is_expected.to be true } end end end describe '#report_hostname=' do it 'changes the #report_hostname setting' do expect { settings.report_hostname = true } .to change { settings.report_hostname } .from(false) .to(true) end end describe '#runtime_metrics' do describe 'old style' do context 'given nothing' do subject(:runtime_metrics) { settings.runtime_metrics } it 'returns the new settings object' do is_expected.to be_a_kind_of(Datadog::Configuration::Base) end end context 'given :enabled' do subject(:runtime_metrics) { settings.runtime_metrics enabled: true } it 'updates the new #enabled setting' do expect { settings.runtime_metrics enabled: true } .to change { settings.runtime_metrics.enabled } .from(false) .to(true) end end context 'given :statsd' do subject(:runtime_metrics) { settings.runtime_metrics statsd: statsd } let(:statsd) { double('statsd') } it 'updates the new #statsd setting' do expect { settings.runtime_metrics statsd: statsd } .to change { settings.runtime_metrics.statsd } .from(nil) .to(statsd) end end end describe '#enabled' do subject(:enabled) { settings.runtime_metrics.enabled } context "when #{Datadog::Ext::Runtime::Metrics::ENV_ENABLED}" do around do |example| ClimateControl.modify(Datadog::Ext::Runtime::Metrics::ENV_ENABLED => environment) do example.run end end context 'is not defined' do let(:environment) { nil } it { is_expected.to be false } end context 'is defined' do let(:environment) { 'true' } it { is_expected.to be true } end end end describe '#enabled=' do it 'changes the #enabled setting' do expect { settings.runtime_metrics.enabled = true } .to change { settings.runtime_metrics.enabled } .from(false) .to(true) end end describe '#opts' do subject(:opts) { settings.runtime_metrics.opts } it { is_expected.to eq({}) } end describe '#opts=' do let(:opts) { double('opts') } it 'changes the #opts setting' do expect { settings.runtime_metrics.opts = opts } .to change { settings.runtime_metrics.opts } .from({}) .to(opts) end end describe '#statsd' do subject(:statsd) { settings.runtime_metrics.statsd } it { is_expected.to be nil } end describe '#statsd=' do let(:statsd) { double('statsd') } it 'changes the #statsd setting' do expect { settings.runtime_metrics.statsd = statsd } .to change { settings.runtime_metrics.statsd } .from(nil) .to(statsd) end end end describe '#runtime_metrics_enabled' do subject(:runtime_metrics_enabled) { settings.runtime_metrics_enabled } let(:value) { double } before { expect(settings.runtime_metrics).to receive(:enabled).and_return(value) } it 'retrieves the value from the new setting' do is_expected.to be value end end describe '#runtime_metrics_enabled=' do it 'changes the new #enabled setting' do expect { settings.runtime_metrics_enabled = true } .to change { settings.runtime_metrics.enabled } .from(false) .to(true) end end describe '#sampling' do describe '#rate_limit' do subject(:rate_limit) { settings.sampling.rate_limit } context 'default' do it { is_expected.to eq(100) } end context 'when ENV is provided' do around do |example| ClimateControl.modify(Datadog::Ext::Sampling::ENV_RATE_LIMIT => '20.0') do example.run end end it { is_expected.to eq(20.0) } end end describe '#default_rate' do subject(:default_rate) { settings.sampling.default_rate } context 'default' do it { is_expected.to be nil } end context 'when ENV is provided' do around do |example| ClimateControl.modify(Datadog::Ext::Sampling::ENV_SAMPLE_RATE => '0.5') do example.run end end it { is_expected.to eq(0.5) } end end end describe '#service' do subject(:service) { settings.service } context "when #{Datadog::Ext::Environment::ENV_SERVICE}" do around do |example| ClimateControl.modify(Datadog::Ext::Environment::ENV_SERVICE => service) do example.run end end context 'is not defined' do let(:service) { nil } it { is_expected.to be nil } end context 'is defined' do let(:service) { 'service-value' } it { is_expected.to eq(service) } end end end describe '#service=' do subject(:set_service) { settings.service = service } context 'when given a value' do let(:service) { 'custom-service' } before { set_service } it { expect(settings.service).to eq(service) } end end describe '#site' do subject(:site) { settings.site } context "when #{Datadog::Ext::Environment::ENV_SITE}" do around do |example| ClimateControl.modify(Datadog::Ext::Environment::ENV_SITE => site_env) do example.run end end context 'is not defined' do let(:site_env) { nil } it { is_expected.to be nil } end context 'is defined' do let(:site_env) { 'datadoghq.com' } it { is_expected.to eq(site_env) } end end end describe '#site=' do subject(:set_site) { settings.site = site } context 'when given a value' do let(:site) { 'datadoghq.com' } before { set_site } it { expect(settings.site).to eq(site) } end end describe '#tags' do subject(:tags) { settings.tags } context "when #{Datadog::Ext::Environment::ENV_TAGS}" do around do |example| ClimateControl.modify(Datadog::Ext::Environment::ENV_TAGS => env_tags) do example.run end end context 'is not defined' do let(:env_tags) { nil } it { is_expected.to eq({}) } end context 'is defined' do let(:env_tags) { 'a:1,b:2' } it { is_expected.to include('a' => '1', 'b' => '2') } context 'with an invalid tag' do context do let(:env_tags) { '' } it { is_expected.to eq({}) } end context do let(:env_tags) { 'a' } it { is_expected.to eq({}) } end context do let(:env_tags) { ':' } it { is_expected.to eq({}) } end context do let(:env_tags) { ',' } it { is_expected.to eq({}) } end context do let(:env_tags) { 'a:' } it { is_expected.to eq({}) } end end context 'and when #env' do before { allow(settings).to receive(:env).and_return(env) } context 'is set' do let(:env) { 'env-value' } it { is_expected.to include('env' => env) } end context 'is not set' do let(:env) { nil } it { is_expected.to_not include('env') } end end context 'and when #version' do before { allow(settings).to receive(:version).and_return(version) } context 'is set' do let(:version) { 'version-value' } it { is_expected.to include('version' => version) } end context 'is not set' do let(:version) { nil } it { is_expected.to_not include('version') } end end end context 'defines :env with missing #env' do let(:env_tags) { "env:#{tag_env_value}" } let(:tag_env_value) { 'tag-env-value' } it 'populates #env from the tag' do expect { tags } .to change { settings.env } .from(nil) .to(tag_env_value) end end context 'conflicts with #env' do let(:env_tags) { "env:#{tag_env_value}" } let(:tag_env_value) { 'tag-env-value' } let(:env_value) { 'env-value' } before { allow(settings).to receive(:env).and_return(env_value) } it { is_expected.to include('env' => env_value) } end context 'defines :service with missing #service' do let(:env_tags) { "service:#{tag_service_value}" } let(:tag_service_value) { 'tag-service-value' } it 'populates #service from the tag' do expect { tags } .to change { settings.service } .from(nil) .to(tag_service_value) end end context 'conflicts with #version' do let(:env_tags) { "env:#{tag_version_value}" } let(:tag_version_value) { 'tag-version-value' } let(:version_value) { 'version-value' } before { allow(settings).to receive(:version).and_return(version_value) } it { is_expected.to include('version' => version_value) } end context 'defines :version with missing #version' do let(:env_tags) { "version:#{tag_version_value}" } let(:tag_version_value) { 'tag-version-value' } it 'populates #version from the tag' do expect { tags } .to change { settings.version } .from(nil) .to(tag_version_value) end end end end describe '#tags=' do subject(:set_tags) { settings.tags = tags } context 'when given a Hash' do context 'with Symbol keys' do let(:tags) { { :'custom-tag' => 'custom-value' } } before { set_tags } it { expect(settings.tags).to eq('custom-tag' => 'custom-value') } end context 'with String keys' do let(:tags) { { 'custom-tag' => 'custom-value' } } before { set_tags } it { expect(settings.tags).to eq(tags) } end end context 'called consecutively' do subject(:set_tags) do settings.tags = { foo: 'foo', bar: 'bar' } settings.tags = { 'foo' => 'oof', 'baz' => 'baz' } end before { set_tags } it { expect(settings.tags).to eq('foo' => 'oof', 'bar' => 'bar', 'baz' => 'baz') } end end describe '#tracer' do context 'old style' do context 'given :debug' do it 'updates the new #debug setting' do expect { settings.tracer(debug: true) } .to change { settings.diagnostics.debug } .from(false) .to(true) end end context 'given :env' do let(:env) { 'my-env' } it 'updates the new #env setting' do expect { settings.tracer env: env } .to change { settings.env } .from(nil) .to(env) end end context 'given :log' do let(:custom_log) { Logger.new(STDOUT, level: Logger::INFO) } it 'updates the new #instance setting' do expect { settings.tracer(log: custom_log) } .to change { settings.logger.instance } .from(nil) .to(custom_log) end end describe 'given :min_spans_before_partial_flush' do let(:value) { 1234 } it 'updates the new #min_spans_threshold setting' do expect { settings.tracer min_spans_before_partial_flush: value } .to change { settings.tracer.partial_flush.min_spans_threshold } .from(nil) .to(value) end end describe 'given :partial_flush' do it 'updates the new #enabled setting' do expect { settings.tracer partial_flush: true } .to change { settings.tracer.partial_flush.enabled } .from(false) .to(true) end end context 'given :tags' do let(:tags) { { 'custom-tag' => 'custom-value' } } it 'updates the new #tags setting' do expect { settings.tracer tags: tags } .to change { settings.tags } .from({}) .to(tags) end end context 'given :writer_options' do before { settings.tracer(writer_options: { buffer_size: 1234 }) } it 'updates the new #writer_options setting' do expect(settings.tracer.writer_options).to eq(buffer_size: 1234) end end context 'given some settings' do let(:tracer) { Datadog::Tracer.new } before do settings.tracer( enabled: false, hostname: 'tracer.host.com', port: 1234, env: :config_test, tags: { foo: :bar }, writer_options: { buffer_size: 1234 }, instance: tracer ) end it 'applies settings correctly' do expect(settings.tracer.enabled).to be false expect(settings.tracer.hostname).to eq('tracer.host.com') expect(settings.tracer.port).to eq(1234) expect(settings.env).to eq(:config_test) expect(settings.tags['foo']).to eq(:bar) end end it 'acts on the tracer option' do previous_state = settings.tracer.enabled settings.tracer(enabled: !previous_state) expect(settings.tracer.enabled).to eq(!previous_state) settings.tracer(enabled: previous_state) expect(settings.tracer.enabled).to eq(previous_state) end end describe '#enabled' do subject(:enabled) { settings.tracer.enabled } it { is_expected.to be true } context "when #{Datadog::Ext::Diagnostics::DD_TRACE_ENABLED}" do around do |example| ClimateControl.modify(Datadog::Ext::Diagnostics::DD_TRACE_ENABLED => enable) do example.run end end context 'is not defined' do let(:enable) { nil } it { is_expected.to be true } end context 'is set to true' do let(:enable) { 'true' } it { is_expected.to be true } end context 'is set to false' do let(:enable) { 'false' } it { is_expected.to be false } end end end describe '#enabled=' do it 'updates the #enabled setting' do expect { settings.tracer.enabled = false } .to change { settings.tracer.enabled } .from(true) .to(false) end end describe '#hostname' do subject(:hostname) { settings.tracer.hostname } it { is_expected.to be nil } end describe '#hostname=' do let(:hostname) { 'my-agent' } it 'updates the #hostname setting' do expect { settings.tracer.hostname = hostname } .to change { settings.tracer.hostname } .from(nil) .to(hostname) end end describe '#instance' do subject(:instance) { settings.tracer.instance } it { is_expected.to be nil } end describe '#instance=' do let(:tracer) { instance_double(Datadog::Tracer) } it 'updates the #instance setting' do expect { settings.tracer.instance = tracer } .to change { settings.tracer.instance } .from(nil) .to(tracer) end end describe '#partial_flush' do describe '#enabled' do subject(:enabled) { settings.tracer.partial_flush.enabled } it { is_expected.to be false } end describe '#enabled=' do it 'updates the #enabled setting' do expect { settings.tracer.partial_flush.enabled = true } .to change { settings.tracer.partial_flush.enabled } .from(false) .to(true) end end describe '#min_spans_threshold' do subject(:min_spans_threshold) { settings.tracer.partial_flush.min_spans_threshold } it { is_expected.to be nil } end describe '#min_spans_threshold=' do let(:value) { 1234 } it 'updates the #min_spans_before_partial_flush setting' do expect { settings.tracer.partial_flush.min_spans_threshold = value } .to change { settings.tracer.partial_flush.min_spans_threshold } .from(nil) .to(value) end end end describe '#port' do subject(:port) { settings.tracer.port } it { is_expected.to be nil } end describe '#port=' do let(:port) { 1234 } it 'updates the #port setting' do expect { settings.tracer.port = port } .to change { settings.tracer.port } .from(nil) .to(port) end end describe '#priority_sampling' do subject(:priority_sampling) { settings.tracer.priority_sampling } it { is_expected.to be nil } end describe '#priority_sampling=' do it 'updates the #priority_sampling setting' do expect { settings.tracer.priority_sampling = true } .to change { settings.tracer.priority_sampling } .from(nil) .to(true) end end describe '#sampler' do subject(:sampler) { settings.tracer.sampler } it { is_expected.to be nil } end describe '#sampler=' do let(:sampler) { instance_double(Datadog::PrioritySampler) } it 'updates the #sampler setting' do expect { settings.tracer.sampler = sampler } .to change { settings.tracer.sampler } .from(nil) .to(sampler) end end describe '#transport_options' do subject(:transport_options) { settings.tracer.transport_options } it { is_expected.to eq({}) } context 'when modified' do it 'does not modify the default by reference' do settings.tracer.transport_options[:foo] = :bar expect(settings.tracer.transport_options).to_not be_empty expect(settings.tracer.options[:transport_options].default_value).to be_empty end end end describe '#transport_options=' do let(:options) { { hostname: 'my-agent' } } it 'updates the #transport_options setting' do expect { settings.tracer.transport_options = options } .to change { settings.tracer.transport_options } .from({}) .to(options) end end describe '#writer' do subject(:writer) { settings.tracer.writer } it { is_expected.to be nil } end describe '#writer=' do let(:writer) { instance_double(Datadog::Writer) } it 'updates the #writer setting' do expect { settings.tracer.writer = writer } .to change { settings.tracer.writer } .from(nil) .to(writer) end end describe '#writer_options' do subject(:writer_options) { settings.tracer.writer_options } it { is_expected.to eq({}) } context 'when modified' do it 'does not modify the default by reference' do settings.tracer.writer_options[:foo] = :bar expect(settings.tracer.writer_options).to_not be_empty expect(settings.tracer.options[:writer_options].default_value).to be_empty end end end describe '#writer_options=' do let(:options) { { priority_sampling: true } } it 'updates the #writer_options setting' do expect { settings.tracer.writer_options = options } .to change { settings.tracer.writer_options } .from({}) .to(options) end end end describe '#tracer=' do let(:tracer) { instance_double(Datadog::Tracer) } it 'sets the tracer instance' do expect { settings.tracer = tracer }.to change { settings.tracer.instance } .from(nil) .to(tracer) end end describe '#version' do subject(:version) { settings.version } context "when #{Datadog::Ext::Environment::ENV_VERSION}" do around do |example| ClimateControl.modify(Datadog::Ext::Environment::ENV_VERSION => version) do example.run end end context 'is not defined' do let(:version) { nil } it { is_expected.to be nil } end context 'is defined' do let(:version) { 'version-value' } it { is_expected.to eq(version) } end end end describe '#version=' do subject(:set_version) { settings.version = version } context 'when given a value' do let(:version) { '0.1.0.alpha' } before { set_version } it { expect(settings.version).to eq(version) } end end end
28.045879
118
0.57628
6aaca6eb60aaf7e651b11a4b2307d2459aee85ca
2,299
require 'rails_helper' require 'spec_helper' # rubocop:disable Metrics/BlockLength RSpec.describe PostsController, type: :feature do context 'timeline displays friends posts' do let(:user) { User.create(id: '1', name: 'JonDoe', email: '[email protected]', password: 'password') } scenario 'current_user posts' do visit new_user_session_path fill_in 'user_email', with: user.email fill_in 'user_password', with: user.password click_button 'Log in' fill_in 'post_content', with: 'Create a post for testing' click_button 'Save' visit root_path expect(page).to have_content('Create a post for testing') end scenario 'friends posts' do user2 = User.create(id: '2', name: 'JaneDoe', email: '[email protected]', password: 'password') visit new_user_session_path fill_in 'user_email', with: user.email fill_in 'user_password', with: user.password click_button 'Log in' visit users_path click_link 'Sign out' visit new_user_session_path fill_in 'user_email', with: user2.email fill_in 'user_password', with: user2.password click_button 'Log in' visit root_path fill_in 'post_content', with: 'Add posts with For testing and For your friend' click_button 'Save' sleep(2) click_link 'Sign out' visit new_user_session_path fill_in 'user_email', with: user.email fill_in 'user_password', with: user.password click_button 'Log in' end scenario 'Posts are hidden if not mutual friendship' do user2 = User.create(id: '2', name: 'Angel', email: '[email protected]', password: 'password') visit new_user_session_path fill_in 'user_email', with: user2.email fill_in 'user_password', with: user2.password click_button 'Log in' visit root_path fill_in 'post_content', with: 'Testing posts with rspec in rails and I am a friend' click_button 'Save' sleep(2) click_link 'Sign out' visit new_user_session_path fill_in 'user_email', with: user.email fill_in 'user_password', with: user.password click_button 'Log in' expect(page).not_to have_content('Angel And You Are Friends') end end # rubocop:enable Metrics/BlockLength end
35.369231
103
0.681601
261d90385cd4991a0b1c913287e03f4752ce54eb
1,798
# frozen_string_literal: true require 'spec_helper' feature 'User deleting posts' do scenario 'can delete their own post' do user.log_in topic = users_topic topic.visit_topic last_post = topic.last_post expect(last_post).to be_listed expect(last_post).to be_deletable last_post.delete expect(last_post).not_to be_listed end scenario 'cannot delete the first post of their own topic' do user.log_in topic = users_topic topic.visit_topic expect(topic.first_post).to be_listed expect(topic.first_post).not_to be_deletable end scenario "cannot delete someone else's post" do user.log_in topic = someone_elses_topic topic.visit_topic last_post = topic.last_post expect(last_post).to be_listed expect(last_post).not_to be_deletable end context 'as an admin' do scenario "can delete someone else's post" do admin.log_in topic = someone_elses_topic topic.visit_topic last_post = topic.last_post expect(last_post).to be_listed expect(last_post).to be_deletable last_post.delete expect(last_post).not_to be_listed end scenario 'cannot delete the first post of a topic' do admin.log_in topic = someone_elses_topic topic.visit_topic expect(topic.first_post).to be_listed expect(topic.first_post).not_to be_deletable end end def user @user ||= create(:user) PageObject::User.new(@user) end def admin @user = create(:user, :admin) PageObject::User.new(@user) end def users_topic topic = create(:topic, with_posts: 3, user: @user) PageObject::Topic.new(topic) end def someone_elses_topic topic = create(:topic, with_posts: 2) PageObject::Topic.new(topic) end end
22.197531
63
0.697998
18ec94d67dfa3449c21688b0acce27d97d87b240
1,399
RSpec.describe 'Escape helper' do before do @user = LinkTo.new @actual = LinkTo::Index.render(format: :html) end it 'renders the title' do expect(@actual).to match(%(<a href="/">Home</a>)) end it 'renders relative link' do expect(@actual).to match(%(<a href="relative">Relative</a>)) end it 'renders link using html content' do expect(@actual).to match(%(<a href="/">\n<p>Home with html content</p>\n</a>)) end it 'renders link using html content, id and class' do expect(@actual).to match(%(<a id="home__link" class="first" href="/">\n<p>Home with html content, id and class</p>\n</a>)) end it 'renders link using content' do expect(@actual).to match(%(<a href="http://external.com">External</a>)) end it 'renders link using html content' do expect(@actual).to match(%(<a href="http://external.com">\n<strong>External with html content</strong>\n</a>)) end it 'escapes content' do expect(@actual).to include(%(<a href="/">&lt;script&gt;alert(&apos;xss&apos;)&lt;&#x2F;script&gt;</a>)) end it 'escapes raw block content' do expect(@actual).to include(%(<a href="/">\n&lt;script&gt;alert(&apos;xss2&apos;)&lt;&#x2F;script&gt;\n</a>)) end it 'escapes html builder block content' do expect(@actual).to include(%(<a href="/">\n<p>&lt;script&gt;alert(&apos;xss3&apos;)&lt;&#x2F;script&gt;</p>\n</a>)) end end
32.534884
126
0.638313
4a1b3956fb33efd3bd67f2e13e4b0400fbe49e30
212
class ManageChallenge < ActiveRecord::Base belongs_to :user belongs_to :set_challenge validates_presence_of :user_id, :set_challenge_id validates_uniqueness_of :user_id, :scope => [:set_challenge_id] end
30.285714
65
0.806604
61a495dec62f43e3a3740b4aad2629d6328f6135
447
# frozen_string_literal: true module Usurper module Pages # / page for library workshops class WorkshopPage < BasePage include Capybara::DSL include CapybaraErrorIntel::DSL def on_page? super && correct_content? end def correct_content? page.has_selector?('.librarian', minimum: 1) && page.has_link?('Library Workshop Registration Portal') end end end end
20.318182
64
0.635347
338776f1d88a949adcab17801dd16ba6454a4cc7
49
require "heroku" module Heroku::Deprecated end
8.166667
25
0.77551
bf8b2bc6b093b43a52a4b0c107920afdc2a88c6a
1,614
# Copyright (c) 2013 Opscode, Inc. # All Rights Reserved # Perform safe cleanup after old packages and services following a # successful Private Chef upgrade. Executables will have been removed # from the package upgrade process, but old data, configuration, logs, # directories, etc. can be left behind. def whyrun_supported? true end use_inline_resources action :clean do remove_service if new_resource.is_service remove_files remove_links remove_users remove_groups remove_directories end def remove_directory(dir) directory dir do action :delete recursive true end end def remove_directories new_resource.directories.each do |dir| remove_directory(dir) end end # Our runit services have a standardized structure; this ensures that # we completely remove everything. def remove_service unlink "#{new_resource.service_link_root}/#{new_resource.package}" unlink "#{new_resource.service_init_link_root}/#{new_resource.package}" remove_directory "#{new_resource.service_root}/#{new_resource.package}" end def remove_files new_resource.files.each do |f| file f do action :delete backup false # We're removing cruft from the system; we don't # want to leave backup cruft end end end def unlink(l) link l do action :delete end end def remove_links new_resource.links.each do |l| unlink(l) end end def remove_users new_resource.users.each do |u| user u do action :remove end end end def remove_groups new_resource.groups.each do |g| group g do action :remove end end end
19.682927
73
0.73544
39544a3d5833ce46c161138fe4952e6c8ecf3116
884
automaticVersion = '1.0.0' Pod::Spec.new do |s| s.name = 'PhyKitCocoapod' s.version = automaticVersion s.summary = 'Swift/Objc wrapper for Bullet Physics Engine with SceneKit support.' s.description = <<-DESC PhyKit wraps the popular Bullet physics library for Swift/Objc, providing additional functionality to attach the physics simulation's output to a SceneKit scene's nodes. DESC s.homepage = 'https://github.com/AdamEisfeld/PhyKit' s.license = { :type => 'zlib', :file => 'LICENSE' } s.author = { 'AdamEisfeld' => '[email protected]' } s.source = { :git => 'https://github.com/AdamEisfeld/PhyKit.git', :tag => s.version.to_s } s.ios.deployment_target = '11.0' s.osx.deployment_target = '11.0' s.vendored_frameworks = "Framework/PhyKit.xcframework" end
38.434783
108
0.635747
38c153f5e73a70e29ca8a03124b463b3ce4655e3
1,725
class Pth < Formula desc "GNU Portable THreads" homepage "https://www.gnu.org/software/pth/" url "https://ftp.gnu.org/gnu/pth/pth-2.0.7.tar.gz" mirror "https://ftpmirror.gnu.org/pth/pth-2.0.7.tar.gz" sha256 "72353660c5a2caafd601b20e12e75d865fd88f6cf1a088b306a3963f0bc77232" bottle do rebuild 2 sha256 cellar: :any, arm64_big_sur: "746ea3501c80f444585f9e8c532815ff97cc94e050d1f5672307451abfb1bcfa" sha256 cellar: :any, big_sur: "ce0bf2885f2ff76922d2306e84e328b3bcbe5b3c8365806a66f75d5fce0568fb" sha256 cellar: :any, catalina: "4e468eea8984b9eb265dcd2f1e10a12ec5827088986042cea278b24f1a4dc1d4" sha256 cellar: :any, mojave: "e7ed86c562756b07fcf9bb148c76f17c6cb4f3b02bf84ffe82285e3b279e7836" sha256 cellar: :any, high_sierra: "da4549f9e89a71478b47f4454f9a259dc3a56a109f24083ce8f4ea69b11ac9c5" sha256 cellar: :any, sierra: "583d6ae1681974c7461650151253c5a302f33fb16dae74b5546a4a693cec71d1" sha256 cellar: :any, el_capitan: "bac7f73c061797768be28e21bec2e7773cfd70ff7c3f46eafd464b9632d5eae4" sha256 cellar: :any, yosemite: "7b31c6d65a97c722e661feb4c73a59a9025f1eac6b297ff181931bbdbc894ff3" sha256 cellar: :any, mavericks: "4271f5c483e95641caa088059669dad1ab6d95774ff66eecae2af1c5c0ddaf0a" sha256 cellar: :any, x86_64_linux: "a1e2eafca56d3449338a0d2455b268329d11280dddb91db21864f0082390fe47" end def install ENV.deparallelize # NOTE: The shared library will not be build with --disable-debug, so don't add that flag system "./configure", "--prefix=#{prefix}", "--mandir=#{man}" system "make" system "make", "test" system "make", "install" end test do system "#{bin}/pth-config", "--all" end end
47.916667
106
0.764638
38acef81f4beae3bfa39c46f38383ed3c20f965f
3,771
# frozen_string_literal: true gem "google-cloud-storage", "~> 1.11" require "google/cloud/storage" require "net/http" require "active_support/core_ext/object/to_query" require "active_storage/filename" module ActiveStorage # Wraps the Google Cloud Storage as an Active Storage service. See ActiveStorage::Service for the generic API # documentation that applies to all services. class Service::GCSService < Service def initialize(**config) @config = config end def upload(key, io, checksum: nil) instrument :upload, key: key, checksum: checksum do begin # The official GCS client library doesn't allow us to create a file with no Content-Type metadata. # We need the file we create to have no Content-Type so we can control it via the response-content-type # param in signed URLs. Workaround: let the GCS client create the file with an inferred # Content-Type (usually "application/octet-stream") then clear it. bucket.create_file(io, key, md5: checksum).update do |file| file.content_type = nil end rescue Google::Cloud::InvalidArgumentError raise ActiveStorage::IntegrityError end end end def download(key, &block) if block_given? instrument :streaming_download, key: key do stream(key, &block) end else instrument :download, key: key do file_for(key).download.string end end end def download_chunk(key, range) instrument :download_chunk, key: key, range: range do file_for(key).download(range: range).string end end def delete(key) instrument :delete, key: key do begin file_for(key).delete rescue Google::Cloud::NotFoundError # Ignore files already deleted end end end def delete_prefixed(prefix) instrument :delete_prefixed, prefix: prefix do bucket.files(prefix: prefix).all(&:delete) end end def exist?(key) instrument :exist, key: key do |payload| answer = file_for(key).exists? payload[:exist] = answer answer end end def url(key, expires_in:, filename:, content_type:, disposition:) instrument :url, key: key do |payload| generated_url = file_for(key).signed_url expires: expires_in, query: { "response-content-disposition" => content_disposition_with(type: disposition, filename: filename), "response-content-type" => content_type } payload[:url] = generated_url generated_url end end def url_for_direct_upload(key, expires_in:, checksum:, **) instrument :url, key: key do |payload| generated_url = bucket.signed_url key, method: "PUT", expires: expires_in, content_md5: checksum payload[:url] = generated_url generated_url end end def headers_for_direct_upload(key, checksum:, **) { "Content-MD5" => checksum } end private attr_reader :config def file_for(key, skip_lookup: true) bucket.file(key, skip_lookup: skip_lookup) end # Reads the file for the given key in chunks, yielding each to the block. def stream(key) file = file_for(key, skip_lookup: false) chunk_size = 5.megabytes offset = 0 while offset < file.size yield file.download(range: offset..(offset + chunk_size - 1)).string offset += chunk_size end end def bucket @bucket ||= client.bucket(config.fetch(:bucket)) end def client @client ||= Google::Cloud::Storage.new(config.except(:bucket)) end end end
28.353383
113
0.63511
38e2c6514fc82ba84c5827707ed2e8fe38fc9911
204
class EmailValidator < ActiveModel::Validator def validate(record) return if record.email.blank? || record.email.match?(URI::MailTo::EMAIL_REGEXP) record.errors.add(:email, :invalid) end end
25.5
83
0.735294
e958b3ea85cf67a4a9e8147753cfe447ab18f4f2
18,864
# Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'date' require 'google/apis/core/base_service' require 'google/apis/core/json_representation' require 'google/apis/core/hashable' require 'google/apis/errors' module Google module Apis module MonitoringV3 class Metric class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class ListGroupMembersResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class TimeInterval class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Group class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class ListTimeSeriesResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Point class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class CollectdValue class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class TimeSeries class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class MetricDescriptor class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Exponential class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Explicit class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Linear class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class CollectdPayload class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class ListMetricDescriptorsResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Distribution class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class MonitoredResource class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class LabelDescriptor class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class MonitoredResourceDescriptor class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class TypedValue class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class ListMonitoredResourceDescriptorsResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Field class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Option class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Empty class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class SourceContext class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Range class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class CreateTimeSeriesRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class BucketOptions class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class CreateCollectdTimeSeriesRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Type class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class ListGroupsResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Metric # @private class Representation < Google::Apis::Core::JsonRepresentation hash :labels, as: 'labels' property :type, as: 'type' end end class ListGroupMembersResponse # @private class Representation < Google::Apis::Core::JsonRepresentation collection :members, as: 'members', class: Google::Apis::MonitoringV3::MonitoredResource, decorator: Google::Apis::MonitoringV3::MonitoredResource::Representation property :next_page_token, as: 'nextPageToken' property :total_size, as: 'totalSize' end end class TimeInterval # @private class Representation < Google::Apis::Core::JsonRepresentation property :end_time, as: 'endTime' property :start_time, as: 'startTime' end end class Group # @private class Representation < Google::Apis::Core::JsonRepresentation property :display_name, as: 'displayName' property :parent_name, as: 'parentName' property :is_cluster, as: 'isCluster' property :filter, as: 'filter' property :name, as: 'name' end end class ListTimeSeriesResponse # @private class Representation < Google::Apis::Core::JsonRepresentation collection :time_series, as: 'timeSeries', class: Google::Apis::MonitoringV3::TimeSeries, decorator: Google::Apis::MonitoringV3::TimeSeries::Representation property :next_page_token, as: 'nextPageToken' end end class Point # @private class Representation < Google::Apis::Core::JsonRepresentation property :value, as: 'value', class: Google::Apis::MonitoringV3::TypedValue, decorator: Google::Apis::MonitoringV3::TypedValue::Representation property :interval, as: 'interval', class: Google::Apis::MonitoringV3::TimeInterval, decorator: Google::Apis::MonitoringV3::TimeInterval::Representation end end class CollectdValue # @private class Representation < Google::Apis::Core::JsonRepresentation property :value, as: 'value', class: Google::Apis::MonitoringV3::TypedValue, decorator: Google::Apis::MonitoringV3::TypedValue::Representation property :data_source_name, as: 'dataSourceName' property :data_source_type, as: 'dataSourceType' end end class TimeSeries # @private class Representation < Google::Apis::Core::JsonRepresentation property :metric, as: 'metric', class: Google::Apis::MonitoringV3::Metric, decorator: Google::Apis::MonitoringV3::Metric::Representation collection :points, as: 'points', class: Google::Apis::MonitoringV3::Point, decorator: Google::Apis::MonitoringV3::Point::Representation property :value_type, as: 'valueType' property :resource, as: 'resource', class: Google::Apis::MonitoringV3::MonitoredResource, decorator: Google::Apis::MonitoringV3::MonitoredResource::Representation property :metric_kind, as: 'metricKind' end end class MetricDescriptor # @private class Representation < Google::Apis::Core::JsonRepresentation property :description, as: 'description' property :unit, as: 'unit' collection :labels, as: 'labels', class: Google::Apis::MonitoringV3::LabelDescriptor, decorator: Google::Apis::MonitoringV3::LabelDescriptor::Representation property :metric_kind, as: 'metricKind' property :value_type, as: 'valueType' property :display_name, as: 'displayName' property :name, as: 'name' property :type, as: 'type' end end class Exponential # @private class Representation < Google::Apis::Core::JsonRepresentation property :growth_factor, as: 'growthFactor' property :scale, as: 'scale' property :num_finite_buckets, as: 'numFiniteBuckets' end end class Explicit # @private class Representation < Google::Apis::Core::JsonRepresentation collection :bounds, as: 'bounds' end end class Linear # @private class Representation < Google::Apis::Core::JsonRepresentation property :width, as: 'width' property :offset, as: 'offset' property :num_finite_buckets, as: 'numFiniteBuckets' end end class CollectdPayload # @private class Representation < Google::Apis::Core::JsonRepresentation property :end_time, as: 'endTime' hash :metadata, as: 'metadata', class: Google::Apis::MonitoringV3::TypedValue, decorator: Google::Apis::MonitoringV3::TypedValue::Representation collection :values, as: 'values', class: Google::Apis::MonitoringV3::CollectdValue, decorator: Google::Apis::MonitoringV3::CollectdValue::Representation property :plugin_instance, as: 'pluginInstance' property :start_time, as: 'startTime' property :type_instance, as: 'typeInstance' property :type, as: 'type' property :plugin, as: 'plugin' end end class ListMetricDescriptorsResponse # @private class Representation < Google::Apis::Core::JsonRepresentation collection :metric_descriptors, as: 'metricDescriptors', class: Google::Apis::MonitoringV3::MetricDescriptor, decorator: Google::Apis::MonitoringV3::MetricDescriptor::Representation property :next_page_token, as: 'nextPageToken' end end class Distribution # @private class Representation < Google::Apis::Core::JsonRepresentation collection :bucket_counts, as: 'bucketCounts' property :bucket_options, as: 'bucketOptions', class: Google::Apis::MonitoringV3::BucketOptions, decorator: Google::Apis::MonitoringV3::BucketOptions::Representation property :count, as: 'count' property :sum_of_squared_deviation, as: 'sumOfSquaredDeviation' property :mean, as: 'mean' property :range, as: 'range', class: Google::Apis::MonitoringV3::Range, decorator: Google::Apis::MonitoringV3::Range::Representation end end class MonitoredResource # @private class Representation < Google::Apis::Core::JsonRepresentation hash :labels, as: 'labels' property :type, as: 'type' end end class LabelDescriptor # @private class Representation < Google::Apis::Core::JsonRepresentation property :description, as: 'description' property :value_type, as: 'valueType' property :key, as: 'key' end end class MonitoredResourceDescriptor # @private class Representation < Google::Apis::Core::JsonRepresentation property :display_name, as: 'displayName' property :description, as: 'description' collection :labels, as: 'labels', class: Google::Apis::MonitoringV3::LabelDescriptor, decorator: Google::Apis::MonitoringV3::LabelDescriptor::Representation property :type, as: 'type' property :name, as: 'name' end end class TypedValue # @private class Representation < Google::Apis::Core::JsonRepresentation property :bool_value, as: 'boolValue' property :string_value, as: 'stringValue' property :int64_value, as: 'int64Value' property :double_value, as: 'doubleValue' property :distribution_value, as: 'distributionValue', class: Google::Apis::MonitoringV3::Distribution, decorator: Google::Apis::MonitoringV3::Distribution::Representation end end class ListMonitoredResourceDescriptorsResponse # @private class Representation < Google::Apis::Core::JsonRepresentation property :next_page_token, as: 'nextPageToken' collection :resource_descriptors, as: 'resourceDescriptors', class: Google::Apis::MonitoringV3::MonitoredResourceDescriptor, decorator: Google::Apis::MonitoringV3::MonitoredResourceDescriptor::Representation end end class Field # @private class Representation < Google::Apis::Core::JsonRepresentation property :default_value, as: 'defaultValue' property :json_name, as: 'jsonName' collection :options, as: 'options', class: Google::Apis::MonitoringV3::Option, decorator: Google::Apis::MonitoringV3::Option::Representation property :oneof_index, as: 'oneofIndex' property :cardinality, as: 'cardinality' property :type_url, as: 'typeUrl' property :name, as: 'name' property :packed, as: 'packed' property :number, as: 'number' property :kind, as: 'kind' end end class Option # @private class Representation < Google::Apis::Core::JsonRepresentation hash :value, as: 'value' property :name, as: 'name' end end class Empty # @private class Representation < Google::Apis::Core::JsonRepresentation end end class SourceContext # @private class Representation < Google::Apis::Core::JsonRepresentation property :file_name, as: 'fileName' end end class Range # @private class Representation < Google::Apis::Core::JsonRepresentation property :max, as: 'max' property :min, as: 'min' end end class CreateTimeSeriesRequest # @private class Representation < Google::Apis::Core::JsonRepresentation collection :time_series, as: 'timeSeries', class: Google::Apis::MonitoringV3::TimeSeries, decorator: Google::Apis::MonitoringV3::TimeSeries::Representation end end class BucketOptions # @private class Representation < Google::Apis::Core::JsonRepresentation property :explicit_buckets, as: 'explicitBuckets', class: Google::Apis::MonitoringV3::Explicit, decorator: Google::Apis::MonitoringV3::Explicit::Representation property :exponential_buckets, as: 'exponentialBuckets', class: Google::Apis::MonitoringV3::Exponential, decorator: Google::Apis::MonitoringV3::Exponential::Representation property :linear_buckets, as: 'linearBuckets', class: Google::Apis::MonitoringV3::Linear, decorator: Google::Apis::MonitoringV3::Linear::Representation end end class CreateCollectdTimeSeriesRequest # @private class Representation < Google::Apis::Core::JsonRepresentation collection :collectd_payloads, as: 'collectdPayloads', class: Google::Apis::MonitoringV3::CollectdPayload, decorator: Google::Apis::MonitoringV3::CollectdPayload::Representation property :collectd_version, as: 'collectdVersion' property :resource, as: 'resource', class: Google::Apis::MonitoringV3::MonitoredResource, decorator: Google::Apis::MonitoringV3::MonitoredResource::Representation end end class Type # @private class Representation < Google::Apis::Core::JsonRepresentation collection :oneofs, as: 'oneofs' collection :options, as: 'options', class: Google::Apis::MonitoringV3::Option, decorator: Google::Apis::MonitoringV3::Option::Representation property :source_context, as: 'sourceContext', class: Google::Apis::MonitoringV3::SourceContext, decorator: Google::Apis::MonitoringV3::SourceContext::Representation collection :fields, as: 'fields', class: Google::Apis::MonitoringV3::Field, decorator: Google::Apis::MonitoringV3::Field::Representation property :name, as: 'name' property :syntax, as: 'syntax' end end class ListGroupsResponse # @private class Representation < Google::Apis::Core::JsonRepresentation collection :group, as: 'group', class: Google::Apis::MonitoringV3::Group, decorator: Google::Apis::MonitoringV3::Group::Representation property :next_page_token, as: 'nextPageToken' end end end end end
36.487427
217
0.640479
7af004b84e0b80d41cda752fe4424f2b4a2470da
127
require 'test_helper' class TaskKeyResultTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
15.875
49
0.716535
f78f24e617b7c54640d7cc188651d05bbbe8f6c2
1,104
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'elasticsearch/bulk_indexer/version' Gem::Specification.new do |spec| spec.name = 'elasticsearch-bulk_indexer' spec.version = Elasticsearch::BulkIndexer::VERSION spec.authors = ['Alex Tatarnikov'] spec.email = ['[email protected]'] spec.summary = %q{BulkIndexer for elasticsearch-rails} spec.description = %q{BulkIndexer for elasticsearch-rails} spec.homepage = '' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^spec/}) spec.require_paths = ['lib'] spec.add_runtime_dependency 'elasticsearch-model', '~> 0.1' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3.1' spec.add_development_dependency 'sqlite3' spec.add_development_dependency 'activemodel', '> 4.0' spec.add_development_dependency 'test_construct', '~> 2.0' end
39.428571
74
0.682065
ab30cd104b0bf588cd5fad08442d6f1faff95d04
978
# frozen_string_literal: true module AliexpressAPI class DsProduct < Base class << self def find(id, options = {}) params = options.symbolize_keys params[:product_id] = id params[:method] = 'aliexpress.postproduct.redefining.findaeproductbyidfordropshipper' response = post(service_endpoint, params) result = response['aliexpress_postproduct_redefining_findaeproductbyidfordropshipper_response']['result'] if result['error_code'].present? raise ResultError.new(result, message: result['error_message']) end new(result) end def simple_find(id, options = {}) params = options.symbolize_keys params[:product_id] = id params[:method] = 'aliexpress.offer.ds.product.simplequery' response = post(service_endpoint, params) result = response['aliexpress_offer_ds_product_simplequery_response'] new(result) end end end end
29.636364
113
0.671779
4abca622dfc01f652f8d5072c5d600831a83ce2c
927
class Ndenv < Formula desc "Node version manager" homepage "https://github.com/riywo/ndenv" url "https://github.com/riywo/ndenv/archive/v0.4.0.tar.gz" sha256 "1a85e4c0c0eee24d709cbc7b5c9d50709bf51cf7fe996a1548797a4079e0b6e4" license "MIT" head "https://github.com/riywo/ndenv.git" bottle :unneeded depends_on "node-build" def install inreplace "libexec/ndenv" do |s| if HOMEBREW_PREFIX.to_s != "/usr/local" s.gsub! ":/usr/local/etc/ndenv.d", \ ":#{HOMEBREW_PREFIX}/etc/ndenv.d\\0" end end if build.head? git_revision = `git rev-parse --short HEAD`.chomp inreplace "libexec/rbenv---version", /^(version=)"([^"]+)"/, \ %Q(\\1"\\2-g#{git_revision}") end prefix.install "bin", "completions", "libexec" system "#{bin}/ndenv", "rehash" end test do shell_output "eval \"$(#{bin}/ndenv init -)\" && ndenv versions" end end
26.485714
75
0.632147
bb9f2783d397fca57d80e90f7446d839354cac23
750
Pod::Spec.new do |s| s.name = "WebRTC" s.version = "86.4240.10.0" s.summary = "WebRTC library for WebRTC SFU Sora" s.description = <<-DESC WebRTC library for WebRTC SFU Sora DESC s.homepage = "https://github.com/shiguredo/shiguredo-webrtc-ios" s.license = { :type => "BSD" } s.authors = { "WebRTC" => "http://www.webrtc.org", "Shiguredo Inc." => "[email protected]" } s.platform = :ios, "10.0" s.source = { :http => "https://github.com/shiguredo/sora-ios-sdk-specs/releases/download/#{s.name}-#{s.version}/WebRTC.framework.zip" } s.source_files = "WebRTC.framework/Headers/*.h" s.vendored_frameworks = "WebRTC.framework" end
44.117647
143
0.578667
21e4c91b507fc93eda8919246d4950b5106a5af0
709
# frozen_string_literal: true module Spree class Promotion module Rules class Store < PromotionRule has_many :promotion_rule_stores, class_name: "Spree::PromotionRuleStore", foreign_key: :promotion_rule_id, dependent: :destroy has_many :stores, through: :promotion_rule_stores, class_name: "Spree::Store" def preload_relations [:stores] end def applicable?(promotable) promotable.is_a?(Spree::Order) end def eligible?(order, _options = {}) stores.none? || stores.include?(order.store) end end end end end
26.259259
85
0.568406
6145627e8fba2ff500febeba5ba6814300811ed8
180
module FMOD module Core module WindowType RECT = 0 TRIANGLE = 1 HAMMING = 2 HANNING = 3 BLACKMAN = 4 BLACKMAN_HARRIS = 5 end end end
15
25
0.555556
387131ac5bfc774dcc2c7528926861cf4689d592
2,699
Dashboard::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false config.cache_store = :null_store # Cache assets in memory instead of on disk if CDO.with_default(true).cache_assets_in_memory config.assets.configure do |env| env.cache = Sprockets::Cache::MemoryStore.new(1000) end end # Do not eager load code on boot. config.eager_load = false # Always reload static js and css. config.public_file_server.headers = {'Cache-Control' => 'must-revalidate, max-age=0'} # Show full error reports config.consider_all_requests_local = true config.action_mailer.delivery_method = Poste2::DeliveryMethod # if you don't want to send mail in development. Messages will be logged in # development.log if you want to look at them #config.action_mailer.perform_deliveries = false #config.action_mailer.raise_delivery_errors = false # If you want to use mailcatcher, specify `use_mailcatcher: true` in locals.yml. if CDO.use_mailcatcher config.action_mailer.perform_deliveries = true config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = {address: 'localhost', port: 1025} end # and run: # `gem install mailcatcher` # `mailcatcher --ip=0.0.0.0` # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. # config.assets.debug = true config.assets.quiet = true # skip precompiling of all assets on the first request for any asset. config.assets.check_precompiled_asset = false # Whether or not to skip script preloading. Setting this to true # significantly speeds up server startup time config.skip_script_preload = true # Set to :debug to see everything in the log. config.log_level = :debug # See stack traces around sql queries in the log. # ActiveRecordQueryTrace.enabled = true # Set "levelbuilder_mode: true" in locals.yml if you want to be able to create # levels or test levelbuilder functionality. config.levelbuilder_mode = CDO.with_default(false).levelbuilder_mode config.experiment_cache_time_seconds = 0 end
35.986667
87
0.758059
394dc0d87e5d7e4c9b1d87f3c0271f535231e666
3,958
class ErlangAT20 < Formula desc "Programming language for highly scalable real-time systems" homepage "https://www.erlang.org/" # Download tarball from GitHub; it is served faster than the official tarball. url "https://github.com/erlang/otp/archive/OTP-20.3.8.7.tar.gz" sha256 "2f74dcf66194be28b0faab29d2fbc7a27bd97e042286d619f172124b9089dc26" bottle do cellar :any sha256 "3a5e72cef00539c35375edef231064ace2144316f0949e450fcb8b2c0e46b571" => :mojave sha256 "789f3a15d6601206ddbd69e7652edd4a0269d2dec00d107e3c7a2e375783e4ee" => :high_sierra sha256 "0dcf0a39c5ca19d2704660d2b551ddaed5cfd6569f50d6a5b550dac792409426" => :sierra sha256 "2e1e808ded4d154a35cd06820474024c06a4ab820c2f7dc5e3f2352088df603a" => :el_capitan end keg_only :versioned_formula option "without-hipe", "Disable building hipe; fails on various macOS systems" option "with-native-libs", "Enable native library compilation" option "with-dirty-schedulers", "Enable experimental dirty schedulers" option "with-java", "Build jinterface application" option "without-docs", "Do not install documentation" deprecated_option "disable-hipe" => "without-hipe" deprecated_option "no-docs" => "without-docs" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build depends_on "openssl" depends_on "fop" => :optional # enables building PDF docs depends_on :java => :optional depends_on "wxmac" => :recommended # for GUI apps like observer resource "man" do url "https://www.erlang.org/download/otp_doc_man_20.3.tar.gz" mirror "https://fossies.org/linux/misc/legacy/otp_doc_man_20.3.tar.gz" sha256 "17e0b2f94f11576a12526614a906ecad629b8804c25e6c18523f7c4346607112" end resource "html" do url "https://www.erlang.org/download/otp_doc_html_20.3.tar.gz" mirror "https://fossies.org/linux/misc/legacy/otp_doc_html_20.3.tar.gz" sha256 "8099b62e9fa24b3f90eaeda151fa23ae729c8297e7d3fd8adaca865b35a3125d" end def install # Unset these so that building wx, kernel, compiler and # other modules doesn't fail with an unintelligable error. %w[LIBS FLAGS AFLAGS ZFLAGS].each { |k| ENV.delete("ERL_#{k}") } ENV["FOP"] = "#{HOMEBREW_PREFIX}/bin/fop" if build.with? "fop" # Do this if building from a checkout to generate configure system "./otp_build", "autoconf" if File.exist? "otp_build" args = %W[ --disable-debug --disable-silent-rules --prefix=#{prefix} --enable-kernel-poll --enable-threads --enable-sctp --enable-dynamic-ssl-lib --with-ssl=#{Formula["openssl"].opt_prefix} --enable-shared-zlib --enable-smp-support ] args << "--enable-darwin-64bit" if MacOS.prefer_64_bit? args << "--enable-native-libs" if build.with? "native-libs" args << "--enable-dirty-schedulers" if build.with? "dirty-schedulers" args << "--enable-wx" if build.with? "wxmac" args << "--with-dynamic-trace=dtrace" if MacOS::CLT.installed? if build.without? "hipe" # HIPE doesn't strike me as that reliable on macOS # https://syntatic.wordpress.com/2008/06/12/macports-erlang-bus-error-due-to-mac-os-x-1053-update/ # https://www.erlang.org/pipermail/erlang-patches/2008-September/000293.html args << "--disable-hipe" else args << "--enable-hipe" end if build.with? "java" args << "--with-javac" else args << "--without-javac" end system "./configure", *args system "make" system "make", "install" if build.with? "docs" (lib/"erlang").install resource("man").files("man") doc.install resource("html") end end def caveats; <<~EOS Man pages can be found in: #{opt_lib}/erlang/man Access them with `erl -man`, or add this directory to MANPATH. EOS end test do system "#{bin}/erl", "-noshell", "-eval", "crypto:start().", "-s", "init", "stop" end end
35.026549
104
0.696059
1df6000d2dd1fa3624cb15316004c07f0a41d572
6,063
require "so_stub_very_test" require "excon" require "minitest" require "minitest/autorun" require "minitest/pride" require "minitest/unit" class TestSoStubVeryTest < Minitest::Test include SoStubVeryTest def teardown SoStubVeryTest.default_host = nil SoStubVeryTest.clear_custom_stubs Excon.stubs.clear end def test_can_stub_get stub_get "/foo", body: [true] assert_equal Excon.stubs, [[{ path: /\A\/foo\Z/, method: :get }, body: [true]]] end def test_can_stub_post stub_post "/foo", body: [true] assert_equal Excon.stubs, [[{ path: /\A\/foo\Z/, method: :post }, body: [true]]] end def test_can_stub_put stub_put "/foo", body: [true] assert_equal Excon.stubs, [[{ path: /\A\/foo\Z/, method: :put }, body: [true]]] end def test_can_stub_patch stub_patch "/foo", body: [true] assert_equal Excon.stubs, [[{ path: /\A\/foo\Z/, method: :patch }, body: [true]]] end def test_can_stub_delete stub_delete "/foo", body: [true] assert_equal Excon.stubs, [[{ path: /\A\/foo\Z/, method: :delete }, body: [true]]] end def test_can_pass_request_params stub_get({ path: "/foo", headers: { "Accept" => "bar" } }, [true]) assert_equal Excon.stubs, [[{ path: /\A\/foo\Z/, headers: { "Accept" => "bar" }, method: :get }, body: [true]]] end def test_performs_param_substitution stub_get "/foo/:bar", body: [true] assert_equal Excon.stubs, [[{ path: Regexp.new('\A/foo/[^\/]+\Z'), method: :get }, body: [true]]] end def test_can_have_default_host SoStubVeryTest.default_host = "example.com" stub_get "/foo", body: [true] assert_equal Excon.stubs, [[{ path: /\A\/foo\Z/, method: :get, host: "example.com" }, body: [true]]] end def test_can_set_response_options stub_get "/foo", body: [true], status: 201 assert_equal Excon.stubs, [[{ path: /\A\/foo\Z/, method: :get }, body: [true], status: 201]] end def test_need_not_pass_body_param stub_get "/foo", [true] assert_equal Excon.stubs, [[{ path: /\A\/foo\Z/, method: :get }, body: [true]]] end def test_can_pass_block_as_response stub_get "/foo" do [true] end assert_equal Excon.stubs[0][0], { path: /\A\/foo\Z/, method: :get } assert_equal Excon.stubs[0][1].call, [true] end def test_raises_exception_when_given_response_and_block assert_raises SoStubVeryTest::AmbiguousResponseError do stub_get "/foo", "bar" do [true] end end end def test_raises_exception_when_given_response_and_block_with_no_path assert_raises SoStubVeryTest::AmbiguousResponseError do namespace "/foo" do stub_get true do [true] end end end end def test_can_use_namespaces namespace "/foo" do stub_get "/bar", true end assert_equal Excon.stubs, [[{ path: /\A\/foo\/bar\Z/, method: :get }, { body: true }]] end def test_can_nest_namespaces namespace "/foo" do namespace "/bar" do stub_get "/baz", true end end assert_equal Excon.stubs, [[{ path: /\A\/foo\/bar\/baz\Z/, method: :get }, { body: true }]] end def test_can_nest_default_host_namespace # Will not raise MixedNamespacesError SoStubVeryTest.default_host = "foo.example.com" namespace "/foo" do namespace "/bar" do end end end def test_can_use_no_path_when_in_namespace namespace "/foo" do stub_get true end assert_equal Excon.stubs, [[{ path: /\A\/foo\Z/, method: :get }, { body: true }]] end def test_raises_no_path_when_not_given_path_outside_of_namespace assert_raises SoStubVeryTest::NoPathGivenError do stub_get true end end def test_clears_namespaces_each_block namespace "/foo" do end namespace "/bar" do stub_get true end assert_equal Excon.stubs, [[{ path: /\A\/bar\Z/, method: :get }, { body: true }]] end def test_can_define_more_namespaces SoStubVeryTest.register_host :foo, "foo.example.com" foo_namespace "/foo" do stub_get true end assert_equal Excon.stubs, [[{ path: /\A\/foo\Z/, host: "foo.example.com", method: :get }, { body: true }]] end def test_new_namespaces_come_with_http_verb_methods SoStubVeryTest.register_host :foo, "foo.example.com" foo_stub_get "/foo", true assert_equal Excon.stubs, [[{ path: /\A\/foo\Z/, host: "foo.example.com", method: :get }, { body: true }]] end def test_passing_string_body_to_namespaced_stub SoStubVeryTest.register_host :foo, "foo.example.com" foo_stub_get "/foo", "bar" assert_equal Excon.stubs, [[{ path: /\A\/foo\Z/, host: "foo.example.com", method: :get }, { body: "bar" }]] end def test_can_not_mismatch_namespaces SoStubVeryTest.register_host :foo, "foo.example.com" assert_raises SoStubVeryTest::MixedNamespacesError do namespace "/foo" do foo_namespace "bar" do end end end end def test_can_not_mismatch_namespaces_and_http_verb_methods SoStubVeryTest.register_host :foo, "foo.example.com" assert_raises SoStubVeryTest::MixedNamespacesError do namespace "/foo" do foo_stub_get true end end end def test_unsets_stub_host_after_each_namespace SoStubVeryTest.register_host :foo, "foo.example.com" foo_namespace "/foo" do stub_get true end stub_get "/bar", true assert_equal Excon.stubs[0], [{ path: /\A\/bar\Z/, method: :get }, body: true] end def test_can_have_default_stubs SoStubVeryTest.defaults do stub_get "/bar", true end assert_equal Excon.stubs, [[{ path: /\A\/bar\Z/, method: :get }, body: true]] end def test_can_clear_stubs stub_get "/bar", true SoStubVeryTest.clear_custom_stubs assert_empty Excon.stubs end def test_does_not_clear_default_stubs SoStubVeryTest.defaults do stub_get "/foo", true end stub_get "/bar", true SoStubVeryTest.clear_custom_stubs assert_equal Excon.stubs, [[{ path: /\A\/foo\Z/, method: :get }, body: true]] end end
27.066964
115
0.662708
615ae2e768d9f323f0da753b3d78932535076ba9
303
require_relative "./model_logic/user_logic" require_relative "./role_object" require 'ostruct' class UserObject < OpenStruct include UserLogic def initialize(hash) super(hash) self.roles = [] hash['roles'].each do |role| self.roles << RoleObject.new(role) end end end
18.9375
43
0.686469
5d1af0b617c901347ecdf2745f78289b177df237
1,518
# 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 Security module Actions # Allows a new node to enroll to an existing cluster with security enabled. # # @option arguments [Hash] :headers Custom HTTP headers # # @see https://www.elastic.co/guide/en/elasticsearch/reference/master/security-api-node-enrollment.html # def enroll_node(arguments = {}) headers = arguments.delete(:headers) || {} body = nil arguments = arguments.clone method = Elasticsearch::API::HTTP_GET path = "_security/enroll/node" params = {} perform_request(method, path, params, body, headers).body end end end end end
33.733333
111
0.688406
79054c2bfa23ba8a28103bcc16d82fe42857c119
1,042
# frozen_string_literal: true module Dip class RunVars attr_reader :argv, :env class << self attr_accessor :env def call(*args) new(*args).call end end self.env = {} def initialize(argv, env = ENV) @argv = argv @env = env end def call populate_env_vars parse_argv end private def populate_env_vars return if early_envs.empty? (env.keys - early_envs).each do |key| next if ignore_var?(key) self.class.env[key] = env[key] end end def parse_argv stop_parse = false argv.each_with_object([]) do |arg, memo| if !stop_parse && arg.include?("=") key, val = arg.split("=", 2) self.class.env[key] = val else memo << arg stop_parse ||= true end end end def early_envs @early_envs ||= env["DIP_EARLY_ENVS"].to_s.split(",") end def ignore_var?(key) key.start_with?("DIP_", "_") end end end
16.806452
59
0.541267
6ab763de6ab9f54d741d16039fe2bf1b62278d38
3,026
#!/opt/puppetlabs/puppet/bin/ruby require_relative '../lib/puppet/util/task_helper' require 'json' require 'puppet' require 'openssl' # require 'pry-remote'; binding.remote_pry # class PowerstoreImportVnxArrayInstanceQueryTask class PowerstoreImportVnxArrayInstanceQueryTask < TaskHelper def task(arg_hash) header_params = {} # Remove task name from arguments - should contain all necessary parameters for URI arg_hash.delete('_task') namevar = '' namevar = 'id' if namevar.empty? operation_verb = 'Get' operation_path = '/import_vnx_array/%{id}' parent_consumes = 'application/json' # parent_produces = 'application/json' query_params, body_params, path_params = format_params(arg_hash) result = transport.call_op(path_params, query_params, header_params, body_params, operation_path, operation_verb, parent_consumes) raise result.body unless result.is_a? Net::HTTPSuccess return nil if result.body.nil? return result.body if result.to_hash['content-type'].include? 'document/text' body = JSON.parse(result.body) return body.map { |i| [i[namevar], i] }.to_h if body.class == Array body end def op_param(name, location, paramalias, namesnake) { name: name, location: location, paramalias: paramalias, namesnake: namesnake } end def format_params(key_values) query_params = {} body_params = {} path_params = {} key_values.each do |key, value| next unless value.respond_to?(:include) && value.include?('=>') value.include?('=>') Puppet.debug("Running hash from string on #{value}") value.tr!('=>', ':') value.tr!("'", '"') key_values[key] = JSON.parse(value) Puppet.debug("Obtained hash #{key_values[key].inspect}") end if key_values.key?('body') if File.file?(key_values['body']) body_params['file_content'] = if key_values['body'].include?('json') File.read(key_values['body']) else JSON.pretty_generate(YAML.load_file(key_values['body'])) end end end op_params = [ op_param('id', 'path', 'id', 'id'), op_param('query_string', 'query', 'query_string', 'query_string'), ] op_params.each do |i| location = i[:location] name = i[:name] # paramalias = i[:paramalias] name_snake = i[:namesnake] if location == 'query' query_params[name] = key_values[name_snake.to_sym] unless key_values[name_snake.to_sym].nil? elsif location == 'body' body_params[name] = key_values[name_snake.to_sym] unless key_values[name_snake.to_sym].nil? else path_params[name_snake.to_sym] = key_values[name_snake.to_sym] unless key_values[name_snake.to_sym].nil? end end [query_params, body_params, path_params] end if $PROGRAM_NAME == __FILE__ PowerstoreImportVnxArrayInstanceQueryTask.run end end
34.781609
134
0.64805
b982196778977a115c0b75a0a834149aa7a1e5d6
341
cask :v1 => 'popkey' do version :latest sha256 :no_check # amazonaws.com is the official download host per the vendor homepage url 'https://popkey-downloads.s3.amazonaws.com/releases/darwin/PopKeySetup.dmg' name 'PopKey' homepage 'http://popkey.co/send-gifs?ref=header_app_nav_section' license :gratis app 'PopKey.app' end
26.230769
81
0.744868
bf4ae5c559d7da93f3b5c910c021142c9a76ecda
1,864
# frozen_string_literal: true require 'airborne' module QA RSpec.describe 'Enablement:Search' do describe 'When using elasticsearch API to search for a public note', :orchestrated, :elasticsearch, :requires_admin do let(:api_client) { Runtime::API::Client.new(:gitlab) } let(:issue) do Resource::Issue.fabricate_via_api! do |issue| issue.title = 'Issue for note index test' end end let(:note) do Resource::ProjectIssueNote.fabricate_via_api! do |project_issue_note| project_issue_note.project = issue.project project_issue_note.issue = issue project_issue_note.body = "This is a comment with a unique number #{SecureRandom.hex(8)}" end end let(:elasticsearch_original_state_on?) { Runtime::Search.elasticsearch_on?(api_client) } before do unless elasticsearch_original_state_on? QA::EE::Resource::Settings::Elasticsearch.fabricate_via_api! end end after do if !elasticsearch_original_state_on? && !api_client.nil? Runtime::Search.disable_elasticsearch(api_client) end issue.project.remove_via_api! end it 'finds note that matches note body', testcase: 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/347634' do QA::Support::Retrier.retry_on_exception(max_attempts: Runtime::Search::RETRY_MAX_ITERATION, sleep_interval: Runtime::Search::RETRY_SLEEP_INTERVAL) do get Runtime::Search.create_search_request(api_client, 'notes', note.body).url expect_status(QA::Support::API::HTTP_STATUS_OK) raise 'Empty search result returned' if json_body.empty? expect(json_body[0][:body]).to eq(note.body) expect(json_body[0][:noteable_id]).to eq(issue.id) end end end end end
34.518519
157
0.677039
38469ee25d08d00102d19f352569e2c4e84d00ac
1,490
# frozen_string_literal: true require 'byebug' require_relative 'lib/clients/bitbucket' require_relative 'lib/commands/fetch' require_relative 'lib/commands/update' require_relative 'lib/options' require_relative 'lib/vcs/repository' $VERBOSE = nil unless RUBY_VERSION.to_f >= 2.5 puts 'Octopus requires Ruby 2.5.0 and above' exit 1 end options_parser = Octopus::Options.new unless options_parser.valid? puts options_parser.errors.values.join("\n") exit 1 end options = options_parser.options vcs_client = case options[:scm_provider].downcase when 'bitbucket' Octopus::Clients::Bitbucket.new(options[:base_url], options[:username], options[:password]) else puts "Unknown SCM provider #{options[:scm_provider]}. Available values are: " \ "#{Octopus::Options::SCM_PROVIDERS.join(', ')}." exit 1 end command = case options[:command] when Octopus::Options::COMMAND_FETCH Octopus::Commands::Fetch.new(options[:files], options[:directory], vcs_client, options[:thread_count], options[:branch]) when Octopus::Options::COMMAND_UPDATE Octopus::Commands::Update.new(options[:files], options[:directory], vcs_client, options_parser.pr_options, options[:thread_count]) end begin command.run rescue StandardError => e puts e.message exit 1 end
31.041667
118
0.651007
289ff3fd26927759807aa26d9a6fcfb4ea8bf18e
190
class AddEmailToDeveloper < ActiveRecord::Migration def self.up add_column :developers, :email, :string end def self.down remove_column :developers, :email, :string end end
19
51
0.731579
3825558e44195301598fc7e1fdad5028d5822380
401
=begin * Created by PSU Beeminder Capstone Team on 3/12/2017. * Copyright (c) 2017 PSU Beeminder Capstone Team * This code is available under the "MIT License". * Please see the file LICENSE in this distribution for license terms. =end require "whenever" set :output, "#{path}/log/cron_log.log" set :environment, @environment every '55 * * * *' do runner "BeeminderWorker.perform_async" end
23.588235
70
0.733167
18d1642df34082ed26ad9c5a9d7b2e6a938894cc
38
module Edison VERSION = '2.0.0' end
9.5
19
0.657895
edb778c27c8f8d545f43c2c1c0fa6b49130e86f9
1,898
#!/usr/bin/ruby -w ############################################################################## # # File x11/RPMGenericBuildAll.rb # # Author Andy Southgate 2007 # # This file contains original work by Andy Southgate. The author and his # employer (Mushware Limited) irrevocably waive all of their copyright rights # vested in this particular version of this file to the furthest extent # permitted. The author and Mushware Limited also irrevocably waive any and # all of their intellectual property rights arising from said file and its # creation that would otherwise restrict the rights of any party to use and/or # distribute the use of, the techniques and methods used herein. A written # waiver can be obtained via http://www.mushware.com/. # # This software carries NO WARRANTY of any kind. # ############################################################################## # $Id: GenericBuildAll.rb,v 1.3 2007/06/30 16:05:49 southa Exp $ # $Log: GenericBuildAll.rb,v $ # Revision 1.3 2007/06/30 16:05:49 southa # Generic packaging # # Revision 1.2 2007/06/30 16:04:05 southa # Generic packaging # commands = [ "rm -rf ~/rpm/BUILD/*/* ~/rpm/RPMS/*/* ~/rpm/tmp/* ~/rpm/SOURCES/* ~/rpm/SPECS/* ~/rpm/SRPMS/*", "echo `test -f Makefile && make distclean`", "rm -rf *.spec *.tar.gz *.tar.bz2 ~/rpm/BUILD/*/* ~/rpm/tmp/*", "perl autogen.pl adanaxis --type=full --dist=genericrpm", "./configure", "make rpm", "make distclean", "rm -rf *.spec *.tar.gz *.tar.bz2 ~/rpm/BUILD/*/* ~/rpm/tmp/*", "perl autogen.pl adanaxis --type=demo --dist=genericrpm", "./configure", "make rpm", "make distclean", "rm -rf *.spec *.tar.gz *.tar.bz2 ~/rpm/BUILD/*/* ~/rpm/tmp/*", "perl autogen.pl adanaxis --type=gpl --dist=genericrpm", "./configure", "make rpm", "ls -lR ~/rpm/RPMS/*", "echo Done." ] for command in commands puts "+++ Executing #{command}" system(command) or raise "+++Command failed" end
35.148148
96
0.635933
ab9f5093e6044a33e8b40106ac9f1f74f0fcba88
807
require 'spec_helper' describe 'supermarket_instance_test::working_ssl' do let(:chef_run) do ChefSpec::SoloRunner.new( step_into: 'supermarket_instance', platform: 'ubuntu', version: '14.04', log_level: :error ) do |_node| end.converge(described_recipe) end context 'inside of supermarket_instance' do it 'creates an ssl directory' do expect(chef_run).to create_directory('/etc/supermarket/ssl') end it 'installs the ssl key' do expect(chef_run).to render_file('/etc/supermarket/ssl/ssl.key') \ .with_content('-----BEGIN RSA PRIVATE KEY-----') end it 'installs the ssl cert' do expect(chef_run).to render_file('/etc/supermarket/ssl/ssl.crt') \ .with_content('-----BEGIN CERTIFICATE-----') end end end
26.9
71
0.656753
1122129154c98e6d61f491595fe6cbeaeb289073
720
# Copyright 2016, SUSE LINUX GmbH # # 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. # class SaharaController < BarclampController protected def initialize_service @service_object = SaharaService.new logger end end
31.304348
74
0.768056
bb6e89ebe21c5ea43583f926fd0e2316ad1ae604
2,876
require __DIR__.parent + 'associations' require __DIR__ + 'relationship' module DataMapper module Associations module ManyToOne def many_to_one(name, options = {}) raise ArgumentError, "+name+ should be a Symbol, but was #{name.class}", caller unless Symbol === name raise ArgumentError, "+options+ should be a Hash, but was #{options.class}", caller unless Hash === options child_model_name = DataMapper::Inflection.demodulize(self.name) parent_model_name = options[:class_name] || DataMapper::Inflection.classify(name) relationships[name] = Relationship.new( name, options[:repository_name] || repository.name, child_model_name, nil, parent_model_name, nil ) class_eval <<-EOS, __FILE__, __LINE__ def #{name} #{name}_association.parent end def #{name}=(value) #{name}_association.parent = value end private def #{name}_association @#{name}_association ||= begin relationship = self.class.relationships[:#{name}] association = relationship.with_child(self, Instance) do |repository, child_key, parent_key, parent_model, child_resource| repository.all(parent_model, parent_key.to_query(child_key.get(child_resource))).first end child_associations << association association end end EOS relationships[name] end class Instance def parent @parent_resource ||= @parent_loader.call end def parent=(parent_resource) @parent_resource = parent_resource @relationship.attach_parent(@child_resource, @parent_resource) if @parent_resource.nil? || !@parent_resource.new_record? end def loaded? !defined?(@parent_resource) end def save if parent.new_record? repository(@relationship.repository_name).save(parent) @relationship.attach_parent(@child_resource, parent) end end private def initialize(relationship, child_resource, &parent_loader) # raise ArgumentError, "+relationship+ should be a DataMapper::Association::Relationship, but was #{relationship.class}", caller unless Relationship === relationship # raise ArgumentError, "+child_resource+ should be a DataMapper::Resource, but was #{child_resource.class}", caller unless Resource === child_resource @relationship = relationship @child_resource = child_resource @parent_loader = parent_loader end end # class Instance end # module ManyToOne end # module Associations end # module DataMapper
32.681818
176
0.620654
79d9d0fef1b775206d89e778e9c231f6995f8f86
379
class Sms77HookListener < Redmine::Hook::ViewListener def view_account_left_bottom(context = {}) mobile = Sms77Controller.user_mobile(context[:user]) if mobile.present? link_to(l('sms77.menu.sms'), use_route: 'sms77_sms', to: mobile) + tag('br', nil, true) + link_to(l('sms77.menu.voice'), use_route: 'sms77_voice', to: mobile) end end end
31.583333
76
0.670185
1af391a175e18de9322609fd62cdb54e0c8945b0
139
class AddStatusToUsers < ActiveRecord::Migration[6.0] def change change_table :users do |u| u.string :status end end end
17.375
53
0.683453
e2faff631fcd1871338b14a12e067736d6703cd8
1,733
def test_case {"RawParseTree"=> [:block, [:lasgn, :var1, [:lit, 1]], [:lasgn, :var2, [:lit, 2]], [:lasgn, :result, [:nil]], [:case, [:lvar, :var1], [:when, [:array, [:lit, 1]], [:case, [:lvar, :var2], [:when, [:array, [:lit, 1]], [:lasgn, :result, [:lit, 1]]], [:when, [:array, [:lit, 2]], [:lasgn, :result, [:lit, 2]]], [:lasgn, :result, [:lit, 3]]]], [:when, [:array, [:lit, 2]], [:case, [:lvar, :var2], [:when, [:array, [:lit, 1]], [:lasgn, :result, [:lit, 4]]], [:when, [:array, [:lit, 2]], [:lasgn, :result, [:lit, 5]]], [:lasgn, :result, [:lit, 6]]]], [:lasgn, :result, [:lit, 7]]]], "Ruby"=> "var1 = 1\nvar2 = 2\nresult = nil\ncase var1\nwhen 1 then\n case var2\n when 1 then\n result = 1\n when 2 then\n result = 2\n else\n result = 3\n end\nwhen 2 then\n case var2\n when 1 then\n result = 4\n when 2 then\n result = 5\n else\n result = 6\n end\nelse\n result = 7\nend\n", "RubyParser"=> s(:block, s(:lasgn, :var1, s(:lit, 1)), s(:lasgn, :var2, s(:lit, 2)), s(:lasgn, :result, s(:nil)), s(:case, s(:lvar, :var1), s(:when, s(:array, s(:lit, 1)), s(:case, s(:lvar, :var2), s(:when, s(:array, s(:lit, 1)), s(:lasgn, :result, s(:lit, 1))), s(:when, s(:array, s(:lit, 2)), s(:lasgn, :result, s(:lit, 2))), s(:lasgn, :result, s(:lit, 3)))), s(:when, s(:array, s(:lit, 2)), s(:case, s(:lvar, :var2), s(:when, s(:array, s(:lit, 1)), s(:lasgn, :result, s(:lit, 4))), s(:when, s(:array, s(:lit, 2)), s(:lasgn, :result, s(:lit, 5))), s(:lasgn, :result, s(:lit, 6)))), s(:lasgn, :result, s(:lit, 7))))} end
35.367347
313
0.465089
8731927691431d3c5e9e0d39d26c0c1822c6cf35
132
class AddSortNoToSurveyForms < ActiveRecord::Migration[4.2] def change add_column :survey_forms, :sort_no, :integer end end
22
59
0.765152
61ebec38900baac519cbc7e6ee935baa214195c6
736
# frozen_string_literal: true module Compute # Represents the Service class Service < Core::ServiceLayer::Model validates :reason, presence: { message: 'Please give a reason' }, on: :disable def disableable? valid? :disable end def name read('binary') end def enabled? status == 'enabled' end def enable rescue_api_errors do service.enable_service(id, 'nova-compute') end end def disable return false unless disableable? rescue_api_errors do if reason service.disable_service_reason(id, 'nova-compute', reason) else service.disable_service(id, 'nova-compute') end end end end end
19.368421
82
0.620924
ffc8e641b186f338c082478cadbea0c0a1bc64e8
896
Pod::Spec.new do |s| s.name = "GCTUIModalPresentationViewController" s.version = "0.0.1" s.summary = "自定义 modal presentation vc" s.description = <<-DESC 自定义 modal presentation vc 控件: 支持 xib 自定义控件布局约束; 支持 present 动画、dismiss 动画; 支持 TextField、TextView 跟随键盘一起 present 显示 DESC s.homepage = "https://github.com/GCTec/GCTUIModalPresentationViewController" s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { "Later" => "[email protected]" } s.platform = :ios, "8.0" s.source = { :git => "https://github.com/GCTec/GCTUIModalPresentationViewController.git", :tag => s.version } s.frameworks = 'UIKit', 'Foundation' s.requires_arc = true s.public_header_files = 'GCTUIModalPresentationViewController/Classes/*.h' s.source_files = 'GCTUIModalPresentationViewController/Classes/*.{h,m}' end
37.333333
117
0.651786
f78925a61dd093784957c53a12dad0eb64a51a61
1,877
# This file is intended to be 'require'd by plugin authors who are developing a # plugin outside of the Train source tree. # Load Train. We certainly need the plugin system, and also several other parts # that are tightly coupled. Train itself is fairly light, and non-invasive. require_relative "../train" # You can select from a number of test harnesses. Since Train is closely related # to InSpec, and InSpec uses Spec-style controls in profile code, you will # probably want to use something like minitest/spec, which provides Spec-style # tests. require "minitest/spec" require "minitest/autorun" # Data formats commonly used in testing require "json" unless defined?(JSON) require "ostruct" unless defined?(OpenStruct) # Utilities often needed require "fileutils" unless defined?(FileUtils) require "tmpdir" unless defined?(Dir.mktmpdir) require "pathname" unless defined?(Pathname) # You might want to put some debugging tools here. We run tests to find bugs, # after all. require "byebug" # Configure MiniTest to expose things like `let` class Module include Minitest::Spec::DSL end # Finally, let's make some modules that can help us out. module TrainPluginBaseHelper # Sneakily detect the location of the plugin # source code when they include this Module def self.included(base) plugin_test_helper_path = Pathname.new(caller_locations(4, 1).first.absolute_path) plugin_src_root = plugin_test_helper_path.parent.parent base.let(:plugin_src_path) { plugin_src_root } base.let(:plugin_fixtures_path) { File.join(plugin_src_root, "test", "fixtures") } end let(:train_src_path) { File.expand_path(File.join(__FILE__, "..", "..")) } let(:train_fixtures_path) { File.join(train_src_path, "test", "fixtures") } let(:registry) { Train::Plugins.registry } end module TrainPluginFunctionalHelper include TrainPluginBaseHelper end
36.096154
86
0.764518
1a0ea64942a01666bd9c945b1c73f8018d027ce6
321
cask :v1 => 'baygenie' do version :latest sha256 :no_check url 'https://www.baygenie.com/Download/BayGenie4Mac.dmg' name 'BayGenie' homepage 'http://www.baygenie.com/' license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder app 'BayGenie.app' end
26.75
115
0.719626
6a17b73531c98038d9f690017344e618bc27765a
3,764
# 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: 1) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "addresses", force: :cascade do |t| t.string "street" t.string "city" t.string "country" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" t.index ["user_id"], name: "index_addresses_on_user_id", unique: true, using: :btree end create_table "microposts", force: :cascade do |t| t.text "content", null: false t.integer "user_id", null: false t.integer "likes", default: 0, null: false t.integer "reposts", default: 0, null: false t.integer "status", default: 0, null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["user_id"], name: "index_microposts_on_user_id", using: :btree end create_table "post_translations", force: :cascade do |t| t.integer "post_id", null: false t.string "locale", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "title" t.text "content" t.index ["locale"], name: "index_post_translations_on_locale", using: :btree t.index ["post_id"], name: "index_post_translations_on_post_id", using: :btree end create_table "posts", force: :cascade do |t| t.integer "user_id", null: false t.boolean "published", default: false, null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["user_id"], name: "index_posts_on_user_id", using: :btree end create_table "relationships", force: :cascade do |t| t.integer "follower_id" t.integer "followed_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["followed_id"], name: "index_relationships_on_followed_id", using: :btree t.index ["follower_id", "followed_id"], name: "index_relationships_on_follower_id_and_followed_id", unique: true, using: :btree t.index ["follower_id"], name: "index_relationships_on_follower_id", using: :btree end create_table "users", force: :cascade do |t| t.string "name" t.string "email", null: false t.boolean "admin", default: false t.boolean "verified", default: false t.string "token", null: false t.integer "microposts_count", default: 0, null: false t.integer "followers_count", default: 0, null: false t.integer "followings_count", default: 0, null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["email"], name: "index_users_on_email", unique: true, using: :btree end add_foreign_key "microposts", "users" add_foreign_key "posts", "users" end
44.282353
131
0.656217
0801c0cf47c10b55790d4bc325b648892cd086e8
6,879
require 'corelib/enumerable' class Struct include Enumerable def self.new(const_name, *args, keyword_init: false, &block) if const_name begin const_name = Opal.const_name!(const_name) rescue TypeError, NameError args.unshift(const_name) const_name = nil end end args.map do |arg| Opal.coerce_to!(arg, String, :to_str) end klass = Class.new(self) do args.each { |arg| define_struct_attribute(arg) } class << self def new(*args) instance = allocate `#{instance}.$$data = {}` instance.initialize(*args) instance end alias_method :[], :new end end klass.module_eval(&block) if block `klass.$$keyword_init = keyword_init` if const_name Struct.const_set(const_name, klass) end klass end def self.define_struct_attribute(name) if self == Struct raise ArgumentError, 'you cannot define attributes to the Struct class' end members << name define_method name do `self.$$data[name]` end define_method "#{name}=" do |value| `self.$$data[name] = value` end end def self.members if self == Struct raise ArgumentError, 'the Struct class has no members' end @members ||= [] end def self.inherited(klass) members = @members klass.instance_eval do @members = members end end def initialize(*args) if `#{self.class}.$$keyword_init` kwargs = args.last || {} if args.length > 1 || `(args.length === 1 && !kwargs.$$is_hash)` raise ArgumentError, "wrong number of arguments (given #{args.length}, expected 0)" end extra = kwargs.keys - self.class.members if extra.any? raise ArgumentError, "unknown keywords: #{extra.join(', ')}" end self.class.members.each do |name| self[name] = kwargs[name] end else if args.length > self.class.members.length raise ArgumentError, 'struct size differs' end self.class.members.each_with_index do |name, index| self[name] = args[index] end end end def members self.class.members end def hash Hash.new(`self.$$data`).hash end def [](name) if Integer === name raise IndexError, "offset #{name} too small for struct(size:#{self.class.members.size})" if name < -self.class.members.size raise IndexError, "offset #{name} too large for struct(size:#{self.class.members.size})" if name >= self.class.members.size name = self.class.members[name] elsif String === name %x{ if(!self.$$data.hasOwnProperty(name)) { #{raise NameError.new("no member '#{name}' in struct", name)} } } else raise TypeError, "no implicit conversion of #{name.class} into Integer" end name = Opal.coerce_to!(name, String, :to_str) `self.$$data[name]` end def []=(name, value) if Integer === name raise IndexError, "offset #{name} too small for struct(size:#{self.class.members.size})" if name < -self.class.members.size raise IndexError, "offset #{name} too large for struct(size:#{self.class.members.size})" if name >= self.class.members.size name = self.class.members[name] elsif String === name raise NameError.new("no member '#{name}' in struct", name) unless self.class.members.include?(name.to_sym) else raise TypeError, "no implicit conversion of #{name.class} into Integer" end name = Opal.coerce_to!(name, String, :to_str) `self.$$data[name] = value` end def ==(other) return false unless other.instance_of?(self.class) %x{ var recursed1 = {}, recursed2 = {}; function _eqeq(struct, other) { var key, a, b; recursed1[#{`struct`.__id__}] = true; recursed2[#{`other`.__id__}] = true; for (key in struct.$$data) { a = struct.$$data[key]; b = other.$$data[key]; if (#{Struct === `a`}) { if (!recursed1.hasOwnProperty(#{`a`.__id__}) || !recursed2.hasOwnProperty(#{`b`.__id__})) { if (!_eqeq(a, b)) { return false; } } } else { if (!#{`a` == `b`}) { return false; } } } return true; } return _eqeq(self, other); } end def eql?(other) return false unless other.instance_of?(self.class) %x{ var recursed1 = {}, recursed2 = {}; function _eqeq(struct, other) { var key, a, b; recursed1[#{`struct`.__id__}] = true; recursed2[#{`other`.__id__}] = true; for (key in struct.$$data) { a = struct.$$data[key]; b = other.$$data[key]; if (#{Struct === `a`}) { if (!recursed1.hasOwnProperty(#{`a`.__id__}) || !recursed2.hasOwnProperty(#{`b`.__id__})) { if (!_eqeq(a, b)) { return false; } } } else { if (!#{`a`.eql?(`b`)}) { return false; } } } return true; } return _eqeq(self, other); } end def each return enum_for(:each) { size } unless block_given? self.class.members.each { |name| yield self[name] } self end def each_pair return enum_for(:each_pair) { size } unless block_given? self.class.members.each { |name| yield [name, self[name]] } self end def length self.class.members.length end alias size length def to_a self.class.members.map { |name| self[name] } end alias values to_a def inspect result = '#<struct ' if Struct === self && self.class.name result += "#{self.class} " end result += each_pair.map do |name, value| "#{name}=#{value.inspect}" end.join ', ' result += '>' result end alias to_s inspect def to_h self.class.members.each_with_object({}) { |name, h| h[name] = self[name] } end def values_at(*args) args = args.map { |arg| `arg.$$is_range ? #{arg.to_a} : arg` }.flatten %x{ var result = []; for (var i = 0, len = args.length; i < len; i++) { if (!args[i].$$is_number) { #{raise TypeError, "no implicit conversion of #{`args[i]`.class} into Integer"} } result.push(#{self[`args[i]`]}); } return result; } end def dig(key, *keys) item = if `key.$$is_string && self.$$data.hasOwnProperty(key)` `self.$$data[key] || nil` end %x{ if (item === nil || keys.length === 0) { return item; } } unless item.respond_to?(:dig) raise TypeError, "#{item.class} does not have #dig method" end item.dig(*keys) end end
22.93
129
0.556476
bb78156845760e39adedb9c961f40fb456714cb1
1,222
# -*- encoding: utf-8 -*- require File.expand_path('../lib/sidekiq/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Mike Perham"] gem.email = ["[email protected]"] gem.description = gem.summary = "Simple, efficient background processing for Ruby" gem.homepage = "http://sidekiq.org" gem.license = "LGPL-3.0" gem.executables = ['sidekiq', 'sidekiqctl'] gem.files = `git ls-files | grep -Ev '^(myapp|examples)'`.split("\n") gem.test_files = `git ls-files -- test/*`.split("\n") gem.name = "sidekiq" gem.require_paths = ["lib"] gem.version = Sidekiq::VERSION gem.add_dependency 'redis', '>= 3.0.6' gem.add_dependency 'redis-namespace', '>= 1.3.1' gem.add_dependency 'connection_pool', '>= 2.0.0' gem.add_dependency 'celluloid', '>= 0.15.2' gem.add_dependency 'json' gem.add_development_dependency 'sinatra' gem.add_development_dependency 'minitest', '~> 5.3.3' gem.add_development_dependency 'rake' gem.add_development_dependency 'rails', '~> 4.1.1' gem.add_development_dependency 'coveralls' end
43.642857
86
0.596563
1a4dc38cab70dae16a8f4a40c643cbd758a28cd1
16,929
# frozen_string_literal: true require "ipaddr" require "active_support/core_ext/kernel/reporting" require "active_support/file_update_checker" require "active_support/configuration_file" require "rails/engine/configuration" require "rails/source_annotation_extractor" module Rails class Application class Configuration < ::Rails::Engine::Configuration attr_accessor :allow_concurrency, :asset_host, :autoflush_log, :cache_classes, :cache_store, :consider_all_requests_local, :console, :eager_load, :exceptions_app, :file_watcher, :filter_parameters, :force_ssl, :helpers_paths, :hosts, :host_authorization, :logger, :log_formatter, :log_tags, :railties_order, :relative_url_root, :secret_key_base, :ssl_options, :public_file_server, :session_options, :time_zone, :reload_classes_only_on_change, :beginning_of_week, :filter_redirect, :x, :enable_dependency_loading, :read_encrypted_secrets, :log_level, :content_security_policy_report_only, :content_security_policy_nonce_generator, :content_security_policy_nonce_directives, :require_master_key, :credentials, :disable_sandbox, :add_autoload_paths_to_load_path, :rake_eager_load, :server_timing attr_reader :encoding, :api_only, :loaded_config_version def initialize(*) super self.encoding = Encoding::UTF_8 @allow_concurrency = nil @consider_all_requests_local = false @filter_parameters = [] @filter_redirect = [] @helpers_paths = [] if Rails.env.development? @hosts = ActionDispatch::HostAuthorization::ALLOWED_HOSTS_IN_DEVELOPMENT + ENV["RAILS_DEVELOPMENT_HOSTS"].to_s.split(",").map(&:strip) else @hosts = [] end @host_authorization = {} @public_file_server = ActiveSupport::OrderedOptions.new @public_file_server.enabled = true @public_file_server.index_name = "index" @force_ssl = false @ssl_options = {} @session_store = nil @time_zone = "UTC" @beginning_of_week = :monday @log_level = :debug @generators = app_generators @cache_store = [ :file_store, "#{root}/tmp/cache/" ] @railties_order = [:all] @relative_url_root = ENV["RAILS_RELATIVE_URL_ROOT"] @reload_classes_only_on_change = true @file_watcher = ActiveSupport::FileUpdateChecker @exceptions_app = nil @autoflush_log = true @log_formatter = ActiveSupport::Logger::SimpleFormatter.new @eager_load = nil @secret_key_base = nil @api_only = false @debug_exception_response_format = nil @x = Custom.new @enable_dependency_loading = false @read_encrypted_secrets = false @content_security_policy = nil @content_security_policy_report_only = false @content_security_policy_nonce_generator = nil @content_security_policy_nonce_directives = nil @require_master_key = false @loaded_config_version = nil @credentials = ActiveSupport::OrderedOptions.new @credentials.content_path = default_credentials_content_path @credentials.key_path = default_credentials_key_path @disable_sandbox = false @add_autoload_paths_to_load_path = true @permissions_policy = nil @rake_eager_load = false @server_timing = false end # Loads default configurations. See {the result of the method for each version}[https://guides.rubyonrails.org/configuring.html#results-of-config-load-defaults]. def load_defaults(target_version) case target_version.to_s when "5.0" if respond_to?(:action_controller) action_controller.per_form_csrf_tokens = true action_controller.forgery_protection_origin_check = true action_controller.urlsafe_csrf_tokens = false end ActiveSupport.to_time_preserves_timezone = true if respond_to?(:active_record) active_record.belongs_to_required_by_default = true end self.ssl_options = { hsts: { subdomains: true } } when "5.1" load_defaults "5.0" if respond_to?(:assets) assets.unknown_asset_fallback = false end if respond_to?(:action_view) action_view.form_with_generates_remote_forms = true end when "5.2" load_defaults "5.1" if respond_to?(:active_record) active_record.cache_versioning = true end if respond_to?(:action_dispatch) action_dispatch.use_authenticated_cookie_encryption = true end if respond_to?(:active_support) active_support.use_authenticated_message_encryption = true active_support.hash_digest_class = OpenSSL::Digest::SHA1 end if respond_to?(:action_controller) action_controller.default_protect_from_forgery = true end if respond_to?(:action_view) action_view.form_with_generates_ids = true end when "6.0" load_defaults "5.2" if respond_to?(:action_view) action_view.default_enforce_utf8 = false end if respond_to?(:action_dispatch) action_dispatch.use_cookies_with_metadata = true end if respond_to?(:action_mailer) action_mailer.delivery_job = "ActionMailer::MailDeliveryJob" end if respond_to?(:active_storage) active_storage.queues.analysis = :active_storage_analysis active_storage.queues.purge = :active_storage_purge active_storage.replace_on_assign_to_many = true end if respond_to?(:active_record) active_record.collection_cache_versioning = true end when "6.1" load_defaults "6.0" if respond_to?(:active_record) active_record.has_many_inversing = true active_record.legacy_connection_handling = false end if respond_to?(:active_job) active_job.retry_jitter = 0.15 end if respond_to?(:action_dispatch) action_dispatch.cookies_same_site_protection = :lax action_dispatch.ssl_default_redirect_status = 308 end if respond_to?(:action_controller) action_controller.delete(:urlsafe_csrf_tokens) end if respond_to?(:action_view) action_view.form_with_generates_remote_forms = false action_view.preload_links_header = true end if respond_to?(:active_storage) active_storage.track_variants = true active_storage.queues.analysis = nil active_storage.queues.purge = nil end if respond_to?(:action_mailbox) action_mailbox.queues.incineration = nil action_mailbox.queues.routing = nil end if respond_to?(:action_mailer) action_mailer.deliver_later_queue_name = nil end ActiveSupport.utc_to_local_returns_utc_offset_times = true when "7.0" load_defaults "6.1" if respond_to?(:action_dispatch) action_dispatch.default_headers = { "X-Frame-Options" => "SAMEORIGIN", "X-XSS-Protection" => "0", "X-Content-Type-Options" => "nosniff", "X-Download-Options" => "noopen", "X-Permitted-Cross-Domain-Policies" => "none", "Referrer-Policy" => "strict-origin-when-cross-origin" } action_dispatch.return_only_request_media_type_on_content_type = false action_dispatch.cookies_serializer = :json end if respond_to?(:action_view) action_view.button_to_generates_button_tag = true action_view.apply_stylesheet_media_default = false end if respond_to?(:active_support) active_support.hash_digest_class = OpenSSL::Digest::SHA256 active_support.key_generator_hash_digest_class = OpenSSL::Digest::SHA256 active_support.remove_deprecated_time_with_zone_name = true active_support.cache_format_version = 7.0 active_support.use_rfc4122_namespaced_uuids = true active_support.executor_around_test_case = true active_support.isolation_level = :thread active_support.disable_to_s_conversion = true end if respond_to?(:action_mailer) action_mailer.smtp_timeout = 5 end if respond_to?(:active_storage) active_storage.video_preview_arguments = "-vf 'select=eq(n\\,0)+eq(key\\,1)+gt(scene\\,0.015),loop=loop=-1:size=2,trim=start_frame=1'" \ " -frames:v 1 -f image2" active_storage.variant_processor = :vips active_storage.multiple_file_field_include_hidden = true end if respond_to?(:active_record) active_record.verify_foreign_keys_for_fixtures = true active_record.partial_inserts = false active_record.automatic_scope_inversing = true end if respond_to?(:action_controller) action_controller.raise_on_open_redirects = true action_controller.wrap_parameters_by_default = true end else raise "Unknown version #{target_version.to_s.inspect}" end @loaded_config_version = target_version end def encoding=(value) @encoding = value silence_warnings do Encoding.default_external = value Encoding.default_internal = value end end def api_only=(value) @api_only = value generators.api_only = value @debug_exception_response_format ||= :api end def debug_exception_response_format @debug_exception_response_format || :default end attr_writer :debug_exception_response_format def paths @paths ||= begin paths = super paths.add "config/database", with: "config/database.yml" paths.add "config/secrets", with: "config", glob: "secrets.yml{,.enc}" paths.add "config/environment", with: "config/environment.rb" paths.add "lib/templates" paths.add "log", with: "log/#{Rails.env}.log" paths.add "public" paths.add "public/javascripts" paths.add "public/stylesheets" paths.add "tmp" paths end end # Load the database YAML without evaluating ERB. This allows us to # create the rake tasks for multiple databases without filling in the # configuration values or loading the environment. Do not use this # method. # # This uses a DummyERB custom compiler so YAML can ignore the ERB # tags and load the database.yml for the rake tasks. def load_database_yaml # :nodoc: if path = paths["config/database"].existent.first require "rails/application/dummy_erb_compiler" yaml = DummyERB.new(Pathname.new(path).read).result if YAML.respond_to?(:unsafe_load) YAML.unsafe_load(yaml) || {} else YAML.load(yaml) || {} end else {} end end # Loads and returns the entire raw configuration of database from # values stored in <tt>config/database.yml</tt>. def database_configuration path = paths["config/database"].existent.first yaml = Pathname.new(path) if path config = if yaml&.exist? loaded_yaml = ActiveSupport::ConfigurationFile.parse(yaml) if (shared = loaded_yaml.delete("shared")) loaded_yaml.each do |_k, values| values.reverse_merge!(shared) end end Hash.new(shared).merge(loaded_yaml) elsif ENV["DATABASE_URL"] # Value from ENV['DATABASE_URL'] is set to default database connection # by Active Record. {} else raise "Could not load database configuration. No such file - #{paths["config/database"].instance_variable_get(:@paths)}" end config rescue => e raise e, "Cannot load database configuration:\n#{e.message}", e.backtrace end def colorize_logging ActiveSupport::LogSubscriber.colorize_logging end def colorize_logging=(val) ActiveSupport::LogSubscriber.colorize_logging = val generators.colorize_logging = val end def session_store(new_session_store = nil, **options) if new_session_store if new_session_store == :active_record_store begin ActionDispatch::Session::ActiveRecordStore rescue NameError raise "`ActiveRecord::SessionStore` is extracted out of Rails into a gem. " \ "Please add `activerecord-session_store` to your Gemfile to use it." end end @session_store = new_session_store @session_options = options || {} else case @session_store when :disabled nil when :active_record_store ActionDispatch::Session::ActiveRecordStore when Symbol ActionDispatch::Session.const_get(@session_store.to_s.camelize) else @session_store end end end def session_store? # :nodoc: @session_store end def annotations Rails::SourceAnnotationExtractor::Annotation end def content_security_policy(&block) if block_given? @content_security_policy = ActionDispatch::ContentSecurityPolicy.new(&block) else @content_security_policy end end def permissions_policy(&block) if block_given? @permissions_policy = ActionDispatch::PermissionsPolicy.new(&block) else @permissions_policy end end def default_log_file path = paths["log"].first unless File.exist? File.dirname path FileUtils.mkdir_p File.dirname path end f = File.open path, "a" f.binmode f.sync = autoflush_log # if true make sure every write flushes f end class Custom # :nodoc: def initialize @configurations = Hash.new end def method_missing(method, *args) if method.end_with?("=") @configurations[:"#{method[0..-2]}"] = args.first else @configurations.fetch(method) { @configurations[method] = ActiveSupport::OrderedOptions.new } end end def respond_to_missing?(symbol, *) true end end private def default_credentials_content_path if credentials_available_for_current_env? root.join("config", "credentials", "#{Rails.env}.yml.enc") else root.join("config", "credentials.yml.enc") end end def default_credentials_key_path if credentials_available_for_current_env? root.join("config", "credentials", "#{Rails.env}.key") else root.join("config", "master.key") end end def credentials_available_for_current_env? File.exist?(root.join("config", "credentials", "#{Rails.env}.yml.enc")) end end end end
36.250535
167
0.583319
d505af3f9082a74c0cf9c378443d34f0292ca10b
7,881
module Searchable extend ActiveSupport::Concern included do include Elasticsearch::Model UNREAD_REGEX = /(?<=\s|^)is:\s*unread(?=\s|$)/ READ_REGEX = /(?<=\s|^)is:\s*read(?=\s|$)/ STARRED_REGEX = /(?<=\s|^)is:\s*starred(?=\s|$)/ UNSTARRED_REGEX = /(?<=\s|^)is:\s*unstarred(?=\s|$)/ SORT_REGEX = /(?<=\s|^)sort:\s*(asc|desc|relevance)(?=\s|$)/i TAG_ID_REGEX = /tag_id:\s*(\d+)/ TAG_GROUP_REGEX = /tag_id:\((.*?)\)/ search_settings = { "analysis": { "analyzer": { "lower_exact": { "tokenizer": "whitespace", "filter": ["lowercase"], }, }, }, } settings search_settings do mappings _source: {enabled: false} do indexes :id, type: "long", index: :not_analyzed indexes :title, analyzer: "snowball", fields: {exact: {type: "string", analyzer: "lower_exact"}} indexes :content, analyzer: "snowball", fields: {exact: {type: "string", analyzer: "lower_exact"}} indexes :emoji, analyzer: "whitespace", fields: {exact: {type: "string", analyzer: "whitespace"}} indexes :author, analyzer: "lower_exact", fields: {exact: {type: "string", analyzer: "lower_exact"}} indexes :url, analyzer: "keyword", fields: {exact: {type: "string", analyzer: "keyword"}} indexes :feed_id, type: "long", index: :not_analyzed, include_in_all: false indexes :published, type: "date", include_in_all: false indexes :updated, type: "date", include_in_all: false indexes :twitter_screen_name, analyzer: "whitespace" indexes :twitter_name, analyzer: "whitespace" indexes :twitter_retweet, type: "boolean" indexes :twitter_media, type: "boolean" indexes :twitter_image, type: "boolean" indexes :twitter_link, type: "boolean" end end def self.saved_search_count(user) saved_searches = user.saved_searches if saved_searches.length < 10 unread_entries = user.unread_entries.pluck(:entry_id) searches = build_multi_search(user, saved_searches) queries = searches.map { |search| { index: Entry.index_name, search: search.query, } } if queries.present? result = Entry.__elasticsearch__.client.msearch body: queries entry_ids = result["responses"].map { |response| hits = response.dig("hits", "hits") || [] hits.map do |hit| hit["_id"].to_i end } search_ids = searches.map { |search| search.id } Hash[search_ids.zip(entry_ids)] end end end def self.build_multi_search(user, saved_searches) saved_searches.map { |saved_search| query_string = saved_search.query next if query_string =~ READ_REGEX query_string = query_string.gsub(UNREAD_REGEX, "") query_string = {query: "#{query_string} is:unread"} options = build_search(query_string, user) options[:size] = 50 query = build_query(options) query[:fields] = ["id", "feed_id"] OpenStruct.new({id: saved_search.id, query: query}) }.compact end def self.scoped_search(params, user) options = build_search(params, user) query = build_query(options) result = $search[:main].indices.validate_query({ index: Entry.index_name, body: {query: query[:query]} }) if result["valid"] == false Entry.search(nil).records else Entry.search(query).page(params[:page]).records(includes: :feed) end end def self.build_query(options) {}.tap do |hash| hash[:fields] = ["id"] if options[:sort] if %w[desc asc].include?(options[:sort]) hash[:sort] = [{published: options[:sort]}] end else hash[:sort] = [{published: "desc"}] end if size = options[:size] hash[:from] = 0 hash[:size] = size end hash[:query] = { bool: { filter: { bool: { should: [ {terms: {feed_id: options[:feed_ids]}}, {terms: {id: options[:starred_ids]}}, ], }, }, }, } if options[:query].present? hash[:query][:bool][:must] = { query_string: { fields: ["_all", "title.*", "content.*", "emoji", "author", "url"], quote_field_suffix: ".exact", default_operator: "AND", query: options[:query], }, } end if options[:ids].present? hash[:query][:bool][:filter][:bool][:must] = { terms: {id: options[:ids]}, } end if options[:not_ids].present? hash[:query][:bool][:filter][:bool][:must_not] = { terms: {id: options[:not_ids]}, } end end end def self.build_search(params, user) if UNREAD_REGEX.match?(params[:query]) params[:query] = params[:query].gsub(UNREAD_REGEX, "") params[:read] = false elsif READ_REGEX.match?(params[:query]) params[:query] = params[:query].gsub(READ_REGEX, "") params[:read] = true end if STARRED_REGEX.match?(params[:query]) params[:query] = params[:query].gsub(STARRED_REGEX, "") params[:starred] = true elsif UNSTARRED_REGEX.match?(params[:query]) params[:query] = params[:query].gsub(UNSTARRED_REGEX, "") params[:starred] = false end if SORT_REGEX.match?(params[:query]) params[:sort] = params[:query].match(SORT_REGEX)[1].downcase params[:query] = params[:query].gsub(SORT_REGEX, "") end if params[:query] params[:query] = params[:query].gsub(TAG_ID_REGEX) do |s| tag_id = Regexp.last_match[1] feed_ids = user.taggings.where(tag_id: tag_id).pluck(:feed_id) id_string = feed_ids.join(" OR ") "feed_id:(#{id_string})" end params[:query] = params[:query].gsub(TAG_GROUP_REGEX) do |s| tag_group = Regexp.last_match[1] tag_ids = tag_group.split(" OR ") feed_ids = user.taggings.where(tag_id: tag_ids).pluck(:feed_id).uniq id_string = feed_ids.join(" OR ") "feed_id:(#{id_string})" end end params[:query] = FeedbinUtils.escape_search(params[:query]) options = { query: params[:query], sort: "desc", starred_ids: [], ids: [], not_ids: [], feed_ids: [], } if params[:sort] && %w[desc asc relevance].include?(params[:sort]) options[:sort] = params[:sort] end if params[:read] == false ids = [0] ids.concat(user.unread_entries.pluck(:entry_id)) options[:ids].push(ids) elsif params[:read] == true options[:not_ids].push(user.unread_entries.pluck(:entry_id)) end if params[:starred] == true options[:ids].push(user.starred_entries.pluck(:entry_id)) elsif params[:starred] == false options[:not_ids].push(user.starred_entries.pluck(:entry_id)) end if params[:feed_ids].present? subscribed_ids = user.subscriptions.pluck(:feed_id) requested_ids = params[:feed_ids] options[:feed_ids] = (requested_ids & subscribed_ids) else options[:feed_ids] = user.subscriptions.pluck(:feed_id) options[:starred_ids] = user.starred_entries.pluck(:entry_id) end if options[:ids].present? options[:ids] = options[:ids].inject(:&) end if options[:not_ids].present? options[:not_ids] = options[:not_ids].flatten.uniq end options end end end
32.432099
111
0.560208
e2a942b343a793530a756e05eaf669c4a98ac353
2,964
# Copyright (C) 2009-2014 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/delete' require 'mongo/operation/write/insert' require 'mongo/operation/write/update' require 'mongo/operation/write/drop_index' require 'mongo/operation/write/ensure_index' require 'mongo/operation/write/create_user' require 'mongo/operation/write/remove_user' require 'mongo/operation/write/command' module Mongo module Operation module Write # The write errors field in the response, 2.6 and higher. # # @since 2.0.0 WRITE_ERRORS = 'writeErrors'.freeze # Constant for the errmsg field. # # @since 2.0.0 ERROR_MESSAGE = 'errmsg'.freeze # The write concern error field in the response. 2.4 and lower. # # @since 2.0.0 WRITE_CONCERN_ERROR = 'writeConcernError'.freeze # Raised when a write failes for some reason. # # @since 2.0.0 class Failure < RuntimeError attr_reader :document # Initialize the exception with the document that triggered the error. # # @example Initialize the new exception. # Write::Failure.new({ 'ok' => 0.0 }) # # @param [ Hash ] document The document that triggered the error. # # @since 2.0.0 def initialize(document) @document = document super(generate_message) end private def errors error_message(Operation::ERROR) do "#{document[Operation::ERROR_CODE]}: #{document[Operation::ERROR]}" end end def error_messages error_message(ERROR_MESSAGE) do document[ERROR_MESSAGE] end end def error_message(key) document.has_key?(key) ? yield : '' end def generate_message errors + error_messages + write_errors + write_concern_errors end def write_errors error_message(WRITE_ERRORS) do document[WRITE_ERRORS].map do |e| "#{e[Operation::ERROR_CODE]}: #{e[ERROR_MESSAGE]}" end.join(', ') end end def write_concern_errors error_message(WRITE_CONCERN_ERROR) do document[WRITE_CONCERN_ERROR].map do |e| "#{e[Operation::ERROR_CODE]}: #{e[ERROR_MESSAGE]}" end.join(', ') end end end end end end
28.5
79
0.628205
39e064ab8f8e7a0bdc8fc54536f4831804271046
1,542
require 'rubygems' require 'ev3' require 'ev3/connections/bluetooth' class Ev3Bot attr_accessor :brick, :left_leg, :right_leg, :gun attr_accessor :left_forward, :right_forward def initialize puts "Connecting to EV3" @brick = EV3::Brick.new(EV3::Connections::Bluetooth.new) @brick.connect @left_leg = brick.motor('b') @right_leg = brick.motor('c') @gun = brick.motor('a') puts "Connected to EV3" define_values end def disconnect self.brick.disconnect end # gun def shoot num_balls self.gun.start sleep num_balls * 1.5 self.gun.stop end # beep def beep self.brick.beep end # movement def turn_left reverse_left_leg if left_forward reverse_right_leg unless right_forward run end def turn_right reverse_left_leg unless left_forward reverse_right_leg if right_forward run end def reverse reverse_left_leg if left_forward reverse_right_leg if right_forward run end def forward reverse_left_leg unless left_forward reverse_right_leg unless right_forward run end def stop self.left_leg.stop self.right_leg.stop end def run self.stop self.left_leg.start self.right_leg.start end def reverse_left_leg self.left_leg.reverse self.left_forward = self.left_forward ? false : true end def reverse_right_leg self.right_leg.reverse self.right_forward = self.right_forward ? false : true end # values def define_values left_leg.speed = 25 right_leg.speed = 25 gun.speed = 50 left_forward = true right_forward = true end end
15.267327
58
0.742542
621e280f3cba53070f17ecc5fb84315aa78cc2cb
2,519
=begin = PEDAC Template == (Understand the) Problem First, identify the inputs and the outputs of the problem * Inputs: 1. A year (integer) * Output: 1. The century of the given year (string) --- *Problem Domain:* Calendar problem. A bit of English. --- *Implicit Requirements:* Can be more than the current year. Seems positive year only. --- *Clarifying Questions:* 1. Negative year? (No) 2. Integer only? (Yes) --- *Mental Model:* Take a number and return it's associated century as a string, formated with the correct English notation ('st', 'nd', 'rd' or 'th') --- == Examples / Test Cases / Edge Cases *Examples:* * Example 1 * Inputs: 1. 2000 * Output 1. '20th' * Example 2 * Inputs: 1. 2001 * Output 1. '21st' * Example 3 * Inputs: 1. 1965 * Output 1. '20th' * Example 4 * Inputs: 1. 256 * Output 1. '3rd' * Example 5 * Inputs: 1. 5 * Output 1. '1st' * Example 6 * Inputs: 1. 10103 * Output 1. '102nd' * Example 7 * Inputs: 1. 1052 * Output 1. '11th' * Example 8 * Inputs: 1. 1127 * Output 1. '12th' * Example 9 * Inputs: 1. 11201 * Output 1. '113th' --- == Data Structure *Your Data Structure:* Integer --- == Algorithm *Your Algorith:* MAIN: 1. Create a new variable `century_num = 0` 2. Divise the given number by 100 3. Check the last number of the given number 1. If it's 0, continue 2. If it's something else, add 1 4. Save the result in `century_num` 5. Pass the result in the `suffix(century)` method 6. Return the result SUFFIX METHOD: 1. Create a `suffix = ''` method 2. Pass the given `year` in a case statement 1. `year` ends with 1: `st` 2. `year` ends with 2: `nd` 3. `year` is 3: `rd` 4. Else: `th` 3. Return `year` + `suffix` as a string == Code =end def add_suffix(century) ones = century % 10 tens = (century / 10) % 10 if tens == 1 suffix = 'th' else suffix = case ones when 1 then 'st' when 2 then 'nd' when 3 then 'rd' else 'th' end end century.to_s + suffix end def century(year) century_num = year / 100 century_num += 1 unless year.to_s.end_with?('0') century = add_suffix(century_num) century end p century(2000) == '20th' p century(2001) == '21st' p century(1965) == '20th' p century(256) == '3rd' p century(5) == '1st' p century(10103) == '102nd' p century(1052) == '11th' p century(1127) == '12th' p century(11201) == '113th'
15.645963
79
0.603811
7a6e6b708ccbce5d605b1ac75b238d681f8a2843
99
class Project < ApplicationRecord belongs_to :employer has_many :tasks has_many :workers end
16.5
33
0.787879
610edaad3cdd2c5c1ed2368c9e34e6db773f91a7
8,282
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Enum do let(:enum) { Jazz::Family } describe ".path" do it "is the name" do assert_equal "Family", enum.path end end describe "type info" do it "tells about the definition" do assert_equal "Family", enum.graphql_name assert_equal 29, enum.description.length assert_equal 7, enum.values.size end it "returns defined enum values" do v = nil Class.new(enum) do graphql_name "TestEnum" v = value :PERCUSSION, "new description" end assert_instance_of Jazz::BaseEnumValue, v end it "inherits values and description" do new_enum = Class.new(enum) do value :Nonsense value :PERCUSSION, "new description" end # Description was inherited assert_equal 29, new_enum.description.length # values were inherited without modifying the parent assert_equal 7, enum.values.size assert_equal 8, new_enum.values.size perc_value = new_enum.values["PERCUSSION"] assert_equal "new description", perc_value.description end it "accepts a block" do assert_equal "Neither here nor there, really", enum.values["KEYS"].description end it "is the #owner of its values" do value = enum.values["STRING"] assert_equal enum, value.owner end it "disallows invalid names" do err = assert_raises GraphQL::InvalidNameError do Class.new(GraphQL::Schema::Enum) do graphql_name "Thing" value "IN/VALID" end end assert_includes err.message, "but 'IN/VALID' does not" end end it "uses a custom enum value class" do enum_type = enum.deprecated_to_graphql value = enum_type.values["STRING"] assert_equal 1, value.metadata[:custom_setting] end describe ".to_graphql" do it "creates an EnumType" do enum_type = enum.deprecated_to_graphql assert_equal "Family", enum_type.name assert_equal "Groups of musical instruments", enum_type.description string_val = enum_type.values["STRING"] didg_val = enum_type.values["DIDGERIDOO"] silence_val = enum_type.values["SILENCE"] assert_equal "STRING", string_val.name assert_equal :str, string_val.value assert_equal false, silence_val.value assert_equal "DIDGERIDOO", didg_val.name assert_equal "Merged into BRASS", didg_val.deprecation_reason end end describe "in queries" do it "works as return values" do query_str = "{ instruments { family } }" expected_families = ["STRING", "WOODWIND", "BRASS", "KEYS", "KEYS", "PERCUSSION"] result = Jazz::Schema.execute(query_str) assert_equal expected_families, result["data"]["instruments"].map { |i| i["family"] } end it "works as input" do query_str = "query($family: Family!) { instruments(family: $family) { name } }" expected_names = ["Piano", "Organ"] result = Jazz::Schema.execute(query_str, variables: { family: "KEYS" }) assert_equal expected_names, result["data"]["instruments"].map { |i| i["name"] } end end describe "multiple values with the same name" do class MultipleNameTestEnum < GraphQL::Schema::Enum value "A" value "B", value: :a value "B", value: :b end it "doesn't allow it from enum_values" do err = assert_raises GraphQL::Schema::DuplicateNamesError do MultipleNameTestEnum.enum_values end expected_message = "Found two visible definitions for `MultipleNameTestEnum.B`: #<GraphQL::Schema::EnumValue MultipleNameTestEnum.B @value=:a>, #<GraphQL::Schema::EnumValue MultipleNameTestEnum.B @value=:b>" assert_equal expected_message, err.message end it "returns them all in all_enum_value_definitions" do assert_equal 3, MultipleNameTestEnum.all_enum_value_definitions.size end end describe "legacy tests" do let(:enum) { Dummy::DairyAnimal } it "coerces names to underlying values" do assert_equal("YAK", enum.coerce_isolated_input("YAK")) assert_equal(1, enum.coerce_isolated_input("COW")) end it "coerces invalid names to nil" do assert_equal(nil, enum.coerce_isolated_input("YAKKITY")) end it "coerces result values to value's value" do assert_equal("YAK", enum.coerce_isolated_result("YAK")) assert_equal("COW", enum.coerce_isolated_result(1)) assert_equal("REINDEER", enum.coerce_isolated_result('reindeer')) assert_equal("DONKEY", enum.coerce_isolated_result(:donkey)) end it "raises a helpful error when a result value can't be coerced" do err = assert_raises(GraphQL::EnumType::UnresolvedValueError) { enum.coerce_result(:nonsense, OpenStruct.new(current_path: ["thing", 0, "name"], current_field: OpenStruct.new(path: "Thing.name"))) } expected_context_message = "`Thing.name` returned `:nonsense` at `thing.0.name`, but this isn't a valid value for `DairyAnimal`. Update the field or resolver to return one of `DairyAnimal`'s values instead." assert_equal expected_context_message, err.message err2 = assert_raises(GraphQL::EnumType::UnresolvedValueError) { enum.coerce_isolated_result(:nonsense) } expected_isolated_message = "`:nonsense` was returned for `DairyAnimal`, but this isn't a valid value for `DairyAnimal`. Update the field or resolver to return one of `DairyAnimal`'s values instead." assert_equal expected_isolated_message, err2.message end describe "resolving with a warden" do it "gets values from the warden" do # OK assert_equal("YAK", enum.coerce_isolated_result("YAK")) # NOT OK assert_raises(GraphQL::EnumType::UnresolvedValueError) { enum.coerce_result("YAK", OpenStruct.new(warden: NothingWarden)) } end end describe "invalid values" do it "rejects value names with a space" do assert_raises(GraphQL::InvalidNameError) { Class.new(GraphQL::Schema::Enum) do graphql_name "InvalidEnumValueTest" value("SPACE IN VALUE", "Invalid enum because it contains spaces", value: 1) end } end end describe "invalid name" do it "reject names with invalid format" do assert_raises(GraphQL::InvalidNameError) do Class.new(GraphQL::Schema::Enum) do graphql_name "Some::Invalid::Name" end end end end describe "values that are Arrays" do let(:schema) { Class.new(GraphQL::Schema) do plural = Class.new(GraphQL::Schema::Enum) do graphql_name "Plural" value 'PETS', value: ["dogs", "cats"] value 'FRUITS', value: ["apples", "oranges"] value 'PLANETS', value: ["Earth"] end query = Class.new(GraphQL::Schema::Object) do graphql_name "Query" field :names, [String], null: false do argument :things, [plural] end def names(things:) things.reduce(&:+) end end query(query) end } it "accepts them as inputs" do res = schema.execute("{ names(things: [PETS, PLANETS]) }") assert_equal ["dogs", "cats", "Earth"], res["data"]["names"] end end it "accepts a symbol as a value, but stringifies it" do enum = Class.new(GraphQL::Schema::Enum) do graphql_name 'MessageFormat' value :markdown end variant = enum.values['markdown'] assert_equal('markdown', variant.graphql_name) assert_equal('markdown', variant.value) end it "has value description" do assert_equal("Animal with horns", enum.values["GOAT"].description) end describe "validate_input with bad input" do it "returns an invalid result" do result = enum.validate_input("bad enum", GraphQL::Query::NullContext) assert(!result.valid?) assert_equal( result.problems.first['explanation'], "Expected \"bad enum\" to be one of: COW, DONKEY, GOAT, REINDEER, SHEEP, YAK" ) end end end end
33.530364
213
0.650809
61d0b97c3b85104a8871967ae97544b9baf792c1
310
require "test_helper" class ArgsControllerTest < Minitest::Capybara::Spec it "run Song::Create,current_user: Module" do visit "/args/with_args" _(page.body).must_match ">{:fake=&gt;&quot;bla&quot;} Module<" _(page.body).must_match ">my_model<" _(page.body).must_match ">my_form<" end end
25.833333
66
0.693548
03fd3143d3f670538edebef3b8878ddd0c650240
5,370
# -*- encoding: utf-8 -*- # stub: mime-types 3.1 ruby lib Gem::Specification.new do |s| s.name = "mime-types".freeze s.version = "3.1" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["Austin Ziegler".freeze] s.date = "2016-05-22" s.description = "The mime-types library provides a library and registry for information about\nMIME content type definitions. It can be used to determine defined filename\nextensions for MIME types, or to use filename extensions to look up the likely\nMIME type definitions.\n\nVersion 3.0 is a major release that requires Ruby 2.0 compatibility and removes\ndeprecated functions. The columnar registry format introduced in 2.6 has been\nmade the primary format; the registry data has been extracted from this library\nand put into {mime-types-data}[https://github.com/mime-types/mime-types-data].\nAdditionally, mime-types is now licensed exclusively under the MIT licence and\nthere is a code of conduct in effect. There are a number of other smaller\nchanges described in the History file.".freeze s.email = ["[email protected]".freeze] s.extra_rdoc_files = ["Code-of-Conduct.rdoc".freeze, "Contributing.rdoc".freeze, "History.rdoc".freeze, "Licence.rdoc".freeze, "Manifest.txt".freeze, "README.rdoc".freeze] s.files = ["Code-of-Conduct.rdoc".freeze, "Contributing.rdoc".freeze, "History.rdoc".freeze, "Licence.rdoc".freeze, "Manifest.txt".freeze, "README.rdoc".freeze] s.homepage = "https://github.com/mime-types/ruby-mime-types/".freeze s.licenses = ["MIT".freeze] s.rdoc_options = ["--main".freeze, "README.rdoc".freeze] s.required_ruby_version = Gem::Requirement.new(">= 2.0".freeze) s.rubygems_version = "2.6.14".freeze s.summary = "The mime-types library provides a library and registry for information about MIME content type definitions".freeze s.installed_by_version = "2.6.14" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<mime-types-data>.freeze, ["~> 3.2015"]) s.add_development_dependency(%q<minitest>.freeze, ["~> 5.9"]) s.add_development_dependency(%q<rdoc>.freeze, ["~> 4.0"]) s.add_development_dependency(%q<hoe-doofus>.freeze, ["~> 1.0"]) s.add_development_dependency(%q<hoe-gemspec2>.freeze, ["~> 1.1"]) s.add_development_dependency(%q<hoe-git>.freeze, ["~> 1.6"]) s.add_development_dependency(%q<hoe-rubygems>.freeze, ["~> 1.0"]) s.add_development_dependency(%q<hoe-travis>.freeze, ["~> 1.2"]) s.add_development_dependency(%q<minitest-autotest>.freeze, ["~> 1.0"]) s.add_development_dependency(%q<minitest-focus>.freeze, ["~> 1.0"]) s.add_development_dependency(%q<minitest-bonus-assertions>.freeze, ["~> 2.0"]) s.add_development_dependency(%q<minitest-hooks>.freeze, ["~> 1.4"]) s.add_development_dependency(%q<rake>.freeze, ["~> 10.0"]) s.add_development_dependency(%q<fivemat>.freeze, ["~> 1.3"]) s.add_development_dependency(%q<minitest-rg>.freeze, ["~> 5.2"]) s.add_development_dependency(%q<simplecov>.freeze, ["~> 0.7"]) s.add_development_dependency(%q<hoe>.freeze, ["~> 3.15"]) else s.add_dependency(%q<mime-types-data>.freeze, ["~> 3.2015"]) s.add_dependency(%q<minitest>.freeze, ["~> 5.9"]) s.add_dependency(%q<rdoc>.freeze, ["~> 4.0"]) s.add_dependency(%q<hoe-doofus>.freeze, ["~> 1.0"]) s.add_dependency(%q<hoe-gemspec2>.freeze, ["~> 1.1"]) s.add_dependency(%q<hoe-git>.freeze, ["~> 1.6"]) s.add_dependency(%q<hoe-rubygems>.freeze, ["~> 1.0"]) s.add_dependency(%q<hoe-travis>.freeze, ["~> 1.2"]) s.add_dependency(%q<minitest-autotest>.freeze, ["~> 1.0"]) s.add_dependency(%q<minitest-focus>.freeze, ["~> 1.0"]) s.add_dependency(%q<minitest-bonus-assertions>.freeze, ["~> 2.0"]) s.add_dependency(%q<minitest-hooks>.freeze, ["~> 1.4"]) s.add_dependency(%q<rake>.freeze, ["~> 10.0"]) s.add_dependency(%q<fivemat>.freeze, ["~> 1.3"]) s.add_dependency(%q<minitest-rg>.freeze, ["~> 5.2"]) s.add_dependency(%q<simplecov>.freeze, ["~> 0.7"]) s.add_dependency(%q<hoe>.freeze, ["~> 3.15"]) end else s.add_dependency(%q<mime-types-data>.freeze, ["~> 3.2015"]) s.add_dependency(%q<minitest>.freeze, ["~> 5.9"]) s.add_dependency(%q<rdoc>.freeze, ["~> 4.0"]) s.add_dependency(%q<hoe-doofus>.freeze, ["~> 1.0"]) s.add_dependency(%q<hoe-gemspec2>.freeze, ["~> 1.1"]) s.add_dependency(%q<hoe-git>.freeze, ["~> 1.6"]) s.add_dependency(%q<hoe-rubygems>.freeze, ["~> 1.0"]) s.add_dependency(%q<hoe-travis>.freeze, ["~> 1.2"]) s.add_dependency(%q<minitest-autotest>.freeze, ["~> 1.0"]) s.add_dependency(%q<minitest-focus>.freeze, ["~> 1.0"]) s.add_dependency(%q<minitest-bonus-assertions>.freeze, ["~> 2.0"]) s.add_dependency(%q<minitest-hooks>.freeze, ["~> 1.4"]) s.add_dependency(%q<rake>.freeze, ["~> 10.0"]) s.add_dependency(%q<fivemat>.freeze, ["~> 1.3"]) s.add_dependency(%q<minitest-rg>.freeze, ["~> 5.2"]) s.add_dependency(%q<simplecov>.freeze, ["~> 0.7"]) s.add_dependency(%q<hoe>.freeze, ["~> 3.15"]) end end
63.176471
802
0.66648
f7984a9ae568a01948be1e6228a5e255a87b92e3
938
# frozen_string_literal: true class MyConfigPreferences def self.set_preferences Spree::Avatax::Config.reset Spree::Avatax::Config.configure do |config| config.company_code = 'DEFAULT' config.license_key = '12345' config.account = '12345' config.refuse_checkout_address_validation_error = false config.log_to_stdout = false config.raise_exceptions = false config.log = true config.address_validation = true config.tax_calculation = true config.document_commit = true config.customer_can_validate = true config.address_validation_enabled_countries = ['United States', 'Canada'] config.origin = "{\"line1\":\"915 S Jackson St\",\"line2\":\"\",\"city\":\"Montgomery\",\"region\":\"AL\",\"postalCode\":\"36104\",\"country\":\"US\"}" end end end RSpec.configure do |config| config.before do MyConfigPreferences.set_preferences end end
28.424242
157
0.684435
7a5bf6b8534c3e34456e167288edb9fb573fbf42
4,219
require "rails_helper" RSpec.describe "Accounts" do it "List and filter accounts", :js do carrier = create(:carrier) user = create(:user, :carrier, carrier: carrier) create( :account, name: "Rocket Rides", carrier: carrier, created_at: Time.utc(2021, 12, 1), metadata: { "customer" => { "id" => "RR1234" } } ) create(:account, name: "Garry Gas", carrier: carrier, created_at: Time.utc(2021, 12, 10)) create(:account, name: "Alice Apples", carrier: carrier, created_at: Time.utc(2021, 10, 1)) create(:account, :disabled, name: "Disabled Account", carrier: carrier, created_at: Time.utc(2021, 12, 10)) sign_in(user) visit dashboard_accounts_path( filter: { from_date: "01/12/2021", to_date: "15/12/2021" } ) click_button("Filter") check("Status") select("Enabled", from: "filter[status]") check("Metadata") fill_in("Key", with: "customer.id") fill_in("Value", with: "RR1234") click_button("Done") expect(page).to have_content("Filter 3") expect(page).to have_content("Rocket Rides") expect(page).not_to have_content("Garry Gas") expect(page).not_to have_content("Alice Apples") expect(page).not_to have_content("Disabled Account") expect(page).not_to have_content("Carrier Account") end it "Create an account" do user = create(:user, :carrier) sign_in(user) visit dashboard_accounts_path click_link("New") fill_in "Name", with: "Rocket Rides" click_button "Create Account" expect(page).to have_content("Account was successfully created") expect(page).to have_content("Rocket Rides") expect(page).to have_content("Enabled") expect(page).to have_link("Edit") expect(page).to have_content("Auth Token") expect(page).to have_content("Carrier managed") end it "Handle validation errors" do user = create(:user, :carrier) sign_in(user) visit new_dashboard_account_path click_button "Create Account" expect(page).to have_content("can't be blank") end it "Update an account", :js do user = create(:user, :carrier) account = create( :account, :enabled, carrier: user.carrier ) outbound_sip_trunk = create(:outbound_sip_trunk, carrier: user.carrier, name: "Main SIP Trunk") sign_in(user) visit dashboard_account_path(account) click_link("Edit") uncheck("Enabled") select("Main SIP Trunk", from: "Outbound SIP trunk") fill_in("Owner's name", with: "John Doe") fill_in("Owner's email", with: "[email protected]") perform_enqueued_jobs do click_button "Update Account" end expect(page).to have_content("Account was successfully updated") expect(page).to have_link( "Main SIP Trunk", href: dashboard_outbound_sip_trunk_path(outbound_sip_trunk) ) expect(page).to have_content("Disabled") expect(page).to have_content("Customer managed") expect(page).to have_content("John Doe") expect(page).to have_content("[email protected]") expect(last_email_sent).to deliver_to("[email protected]") end it "Resend invitation" do user = create(:user, :carrier, :admin) account = create(:account, carrier: user.carrier) invited_user = create(:user, :invited, email: "[email protected]") create(:account_membership, :owner, account: account, user: invited_user) sign_in(user) visit dashboard_account_path(account) expect(page).to have_content("The account owner has not yet accepted their invite.") perform_enqueued_jobs do click_link("Resend") end expect(page).to have_content("An invitation email has been sent to [email protected].") expect(page).to have_current_path(dashboard_account_path(account)) expect(last_email_sent).to deliver_to("[email protected]") end it "Delete an account" do user = create(:user, :carrier) account = create( :account, name: "Rocket Rides", carrier: user.carrier ) sign_in(user) visit dashboard_account_path(account) click_link "Delete" expect(page).not_to have_content("Rocket Rides") end end
29.711268
111
0.671486
ab904d51d98326b58ba54f87f5000eafdced623b
207
$: << '.' require File.dirname(__FILE__) + '/../test_helper' class CountriesControllerTest < ActionController::TestCase # Replace this with your real tests. def test_truth assert true end end
14.785714
58
0.705314
acc2e570c2ee98d0db4f2de54f01db147d95ad1b
8,978
require "spec_helper" describe "Rails::Mongoid" do before(:all) do require "rails/mongoid" end describe ".create_indexes" do let(:pattern) do "spec/app/models/**/*.rb" end let(:logger) do stub end let(:klass) do User end let(:model_paths) do [ "spec/app/models/user.rb" ] end let(:indexes) do Rails::Mongoid.create_indexes(pattern) end before do Dir.expects(:glob).with(pattern).returns(model_paths).once Logger.expects(:new).returns(logger).twice end context "with ordinary Rails models" do it "creates the indexes for the models" do klass.expects(:create_indexes).once logger.expects(:info).once indexes end end context "with a model without indexes" do let(:model_paths) do [ "spec/app/models/account.rb" ] end let(:klass) do Account end it "does nothing" do klass.expects(:create_indexes).never indexes end end context "when an exception is raised" do it "is not swallowed" do Rails::Mongoid.expects(:determine_model).returns(klass) klass.expects(:create_indexes).raises(ArgumentError) expect { indexes }.to raise_error(ArgumentError) end end context "when index is defined on embedded model" do let(:klass) do Address end let(:model_paths) do [ "spec/app/models/address.rb" ] end before do klass.index_options = { city: {} } end it "does nothing, but logging" do klass.expects(:create_indexes).never logger.expects(:info).once indexes end end end describe ".remove_indexes" do let(:pattern) do "spec/app/models/**/*.rb" end let(:logger) do stub end let(:klass) do User end let(:model_paths) do [ "spec/app/models/user.rb" ] end before do Dir.expects(:glob).with(pattern).returns(model_paths).times(2) Logger.expects(:new).returns(logger).times(4) logger.expects(:info).times(2) end let(:indexes) do klass.collection.indexes end before :each do Rails::Mongoid.create_indexes(pattern) Rails::Mongoid.remove_indexes(pattern) end it "removes indexes from klass" do indexes.reject{ |doc| doc["name"] == "_id_" }.should be_empty end it "leaves _id index untouched" do indexes.select{ |doc| doc["name"] == "_id_" }.should_not be_empty end end describe ".models" do let(:pattern) do "spec/app/models/**/*.rb" end let(:logger) do stub end let(:klass) do User end let(:model_paths) do [ "spec/app/models/user.rb" ] end let(:models) do Rails::Mongoid.models(pattern) end before do Dir.expects(:glob).with(pattern).returns(model_paths).once end it "returns models which files matching the pattern" do models.should eq([klass]) end end describe ".determine_model" do let(:logger) do stub end let(:klass) do User end let(:file) do "app/models/user.rb" end let(:model) do Rails::Mongoid.send(:determine_model, file, logger) end module Twitter class Follow include Mongoid::Document end module List class Tweet include Mongoid::Document end end end context "when file is nil" do let(:file) do nil end it "returns nil" do model.should be_nil end end context "when logger is nil" do let(:logger) do nil end it "returns nil" do model.should be_nil end end context "when path is invalid" do let(:file) do "fu/bar.rb" end it "returns nil" do model.should be_nil end end context "when file is not in a subdir" do context "when file is from normal model" do it "returns klass" do model.should eq(klass) end end context "when file is in a module" do let(:klass) do Twitter::Follow end let(:file) do "app/models/follow.rb" end it "raises NameError" do logger.expects(:info) expect { model.should eq(klass) }.to raise_error(NameError) end end end context "when file is in a subdir" do context "with file from normal model" do let(:file) do "app/models/fu/user.rb" end it "returns klass" do logger.expects(:info) model.should eq(klass) end end context "when file is in a module" do let(:klass) do Twitter::Follow end let(:file) do "app/models/twitter/follow.rb" end it "returns klass in module" do model.should eq(klass) end end context "when file is in two modules" do let(:klass) do Twitter::List::Tweet end let(:file) do "app/models/twitter/list/tweet.rb" end it "returns klass in module" do model.should eq(klass) end end end context "with models present in Rails engines" do let(:file) do "/gem_path/engines/some_engine_gem/app/models/user.rb" end let(:klass) do User end it "requires the models by base name from the engine's app/models dir" do model.should eq(klass) end end end describe ".preload_models" do let(:app) do stub(config: config) end let(:config) do stub(paths: paths) end let(:paths) do { "app/models" => [ "/rails/root/app/models" ] } end context "when preload models config is false" do let(:files) do [ "/rails/root/app/models/user.rb", "/rails/root/app/models/address.rb" ] end before(:all) do Mongoid.preload_models = false Dir.stubs(:glob).with("/rails/root/app/models/**/*.rb").returns(files) end it "does not load any models" do Rails::Mongoid.expects(:load_model).never Rails::Mongoid.preload_models(app) end end context "when preload models config is true" do before(:all) do Mongoid.preload_models = true end context "when all models are in the models directory" do let(:files) do [ "/rails/root/app/models/user.rb", "/rails/root/app/models/address.rb" ] end before do Dir.expects(:glob).with("/rails/root/app/models/**/*.rb").returns(files) end it "requires the models by basename" do Rails::Mongoid.expects(:load_model).with("address") Rails::Mongoid.expects(:load_model).with("user") Rails::Mongoid.preload_models(app) end end context "when models exist in subdirectories" do let(:files) do [ "/rails/root/app/models/mongoid/behaviour.rb" ] end before do Dir.expects(:glob).with("/rails/root/app/models/**/*.rb").returns(files) end it "requires the models by subdirectory and basename" do Rails::Mongoid.expects(:load_model).with("mongoid/behaviour") Rails::Mongoid.preload_models(app) end end end end describe ".load_models" do let(:app) do stub(config: config) end let(:config) do stub(paths: paths) end let(:paths) do { "app/models" => [ "/rails/root/app/models" ] } end context "even when preload models config is false" do let(:files) do [ "/rails/root/app/models/user.rb", "/rails/root/app/models/address.rb" ] end before(:all) do Mongoid.preload_models = false Dir.stubs(:glob).with("/rails/root/app/models/**/*.rb").returns(files) end it "loads all models" do Rails::Mongoid.expects(:load_model).with("address") Rails::Mongoid.expects(:load_model).with("user") Rails::Mongoid.load_models(app) end end context "when list of models to load was configured" do let(:files) do [ "/rails/root/app/models/user.rb", "/rails/root/app/models/address.rb" ] end before(:all) do Mongoid.preload_models = ["user"] Dir.stubs(:glob).with("/rails/root/app/models/**/*.rb").returns(files) end it "loads selected models only" do Rails::Mongoid.expects(:load_model).with("user") Rails::Mongoid.expects(:load_model).with("address").never Rails::Mongoid.load_models(app) end end end end
19.906874
82
0.565828
bf56c50382aefab8b1283ea73a9c8516df21ce05
126
module Spud module Photos require 'spud_photos/configuration' require 'spud_photos/engine' if defined?(Rails) end end
21
49
0.769841
87d02a1f6f059d42e430bb02c8a3cf1425bec546
225
class PostsController < ApplicationController respond_to :json def show @blog = Blog.find params[:blog_id] @post = @blog.posts.find params[:id] respond_with(@post, responder: Hypermodel::Responder) end end
22.5
57
0.72
18c818c6de74090aa29ba2a9012906130246d799
4,792
require 'webrick/httputils' module DAV4Rack class FileResource < Resource include WEBrick::HTTPUtils # If this is a collection, return the child resources. def children Dir[file_path + '/*'].map do |path| child File.basename(path) end end # Is this resource a collection? def collection? File.directory?(file_path) end # Does this recource exist? def exist? File.exist?(file_path) end # Return the creation time. def creation_date stat.ctime end # Return the time of last modification. def last_modified stat.mtime end # Set the time of last modification. def last_modified=(time) File.utime(Time.now, time, file_path) end # Return an Etag, an unique hash value for this resource. def etag sprintf('%x-%x-%x', stat.ino, stat.size, stat.mtime.to_i) end # Return the mime type of this resource. def content_type if stat.directory? "text/html" else mime_type(file_path, DefaultMimeTypes) end end # Return the size in bytes for this resource. def content_length stat.size end # HTTP GET request. # # Write the content of the resource to the response.body. def get(request, response) raise NotFound unless exist? if stat.directory? response.body = "" Rack::Directory.new(root).call(request.env)[2].each do |line| response.body << line end response['Content-Length'] = response.body.bytesize.to_s else file = Rack::File.new(root) response.body = file end OK end # HTTP PUT request. # # Save the content of the request.body. def put(request, response) write(request.body) Created end # HTTP POST request. # # Usually forbidden. def post(request, response) raise HTTPStatus::Forbidden end # HTTP DELETE request. # # Delete this resource. def delete if stat.directory? FileUtils.rm_rf(file_path) else File.unlink(file_path) end NoContent end # HTTP COPY request. # # Copy this resource to given destination resource. # Copy this resource to given destination resource. def copy(dest, overwrite) if(collection?) if(dest.exist?) if(dest.collection? && overwrite) FileUtils.cp_r(file_path, dest.send(:file_path)) Created else if(overwrite) FileUtils.rm(dest.send(:file_path)) FileUtils.cp_r(file_path, dest.send(:file_path)) NoContent else PreconditionFailed end end else FileUtils.cp_r(file_path, dest.send(:file_path)) Created end else if(dest.exist? && !overwrite) PreconditionFailed else if(File.directory?(File.dirname(dest.send(:file_path)))) new = !dest.exist? if(dest.collection? && dest.exist?) FileUtils.rm_rf(dest.send(:file_path)) end FileUtils.cp(file_path, dest.send(:file_path).sub(/\/$/, '')) new ? Created : NoContent else Conflict end end end end # HTTP MOVE request. # # Move this resource to given destination resource. def move(*args) result = copy(*args) delete if [Created, NoContent].include?(result) result end # HTTP MKCOL request. # # Create this resource as collection. def make_collection if(request.body.read.to_s == '') if(File.directory?(file_path)) MethodNotAllowed else if(File.directory?(File.dirname(file_path))) Dir.mkdir(file_path) Created else Conflict end end else UnsupportedMediaType end end # Write to this resource from given IO. def write(io) tempfile = "#{file_path}.#{Process.pid}.#{object_id}" open(tempfile, "wb") do |file| while part = io.read(8192) file << part end end File.rename(tempfile, file_path) ensure File.unlink(tempfile) rescue nil end protected def authenticate(user, pass) if(options[:username]) options[:username] == user && options[:password] == pass else true end end def root @options[:root] end def file_path root + '/' + path end def stat @stat ||= File.stat(file_path) end end end
22.288372
73
0.56323
bfc8aede540b1dacc1888c176f1a27425441f5d0
340
# See http://doc.gitlab.com/ce/development/migration_style_guide.html # for more information on how to write migrations for GitLab. class RemoveUserEmailProviderColumn < ActiveRecord::Migration[4.2] include Gitlab::Database::MigrationHelpers DOWNTIME = false def change remove_column :users, :email_provider, :string end end
26.153846
69
0.782353
87418d174db4fa0ad376a7f1674605908d3c9037
575
cask 'beatunes' do version '5.0.4' sha256 '786962231564b260adae3ccac4726260cb63d3cb41581a82215add009d3d7358' url "http://coxy.beatunes.com/download/beaTunes-#{version.dots_to_hyphens}.dmg" name 'beaTunes' homepage 'https://www.beatunes.com/' depends_on macos: '>= :lion' app "beaTunes#{version.major}.app" zap delete: [ '~/Library/Application Support/beaTunes', '~/Library/Caches/beaTunes', '~/Library/Logs/beaTunes', '~/Library/Preferences/com.tagtraum.beatunes.plist', ] end
28.75
81
0.64
38920d19e9acefa8d36c88e69de7a7b0ebead038
4,623
require File.dirname(__FILE__) + '/../../spec_helper' module Cucumber module Formatters describe PrettyFormatter do def mock_step(stubs={}) stub('step', { :keyword => 'Given', :format => 'formatted yes', :name => 'example', :error => nil, :row? => false}.merge(stubs)) end def mock_scenario(stubs={}) stub('scenario', { :name => 'test', :row? => false }.merge(stubs)) end def mock_feature(stubs={}) stub("feature", stubs) end def mock_error(stubs={}) stub('error', { :message => 'failed', :backtrace => 'example backtrace'}.merge(stubs)) end def mock_proc stub(Proc, :to_comment_line => '# steps/example_steps.rb:11') end it "should print step file and line when passed" do io = StringIO.new formatter = PrettyFormatter.new io, StepMother.new step = stub('step', :error => nil, :row? => false, :keyword => 'Given', :format => 'formatted yes' ) formatter.step_passed(step, nil, nil) io.string.should == " Given formatted yes\n" end describe "show source option true" do before(:each) do @io = StringIO.new step_mother = mock('step_mother') @formatter = PrettyFormatter.new @io, step_mother, :source => true end %w{passed failed skipped}.each do |result| it "should display step source for #{result} step" do @formatter.send("step_#{result}".to_sym, mock_step(:regexp_args_proc => [nil, nil, mock_proc], :error => StandardError.new, :padding_length => 2), nil, nil) @io.string.should include("Given formatted yes # steps/example_steps.rb:11") end end it "should display feature file and line for pending step" do @formatter.step_pending(mock_step(:name => 'test', :file => 'features/example.feature', :line => 5, :padding_length => 2), nil, nil) @io.string.should include("Given test # features/example.feature:5") end it "should display file and line for scenario" do @formatter.scenario_executing(mock_scenario(:name => "title", :file => 'features/example.feature', :line => 2 , :padding_length => 2)) @io.string.should include("Scenario: title # features/example.feature:2") end it "should display file for feature" do @formatter.visit_feature(mock_feature(:file => 'features/example.feature', :padding_length => 2)) @formatter.header_executing("Feature: test\n In order to ...\n As a ...\n I want to ...\n") @io.string.should include("Feature: test # features/example.feature\n") @io.string.should include("In order to ...\n") @io.string.should include("As a ...\n") @io.string.should include("I want to ...\n") end it "should align step comments" do step_1 = mock_step(:regexp_args_proc => [nil, nil, mock_proc], :format => "1", :padding_length => 10) step_4 = mock_step(:regexp_args_proc => [nil, nil, mock_proc], :format => "4444", :padding_length => 7) step_9 = mock_step(:regexp_args_proc => [nil, nil, mock_proc], :format => "999999999", :padding_length => 2) @formatter.step_passed(step_1, nil, nil) @formatter.step_passed(step_4, nil, nil) @formatter.step_passed(step_9, nil, nil) @io.string.should include("Given 1 # steps/example_steps.rb:11") @io.string.should include("Given 4444 # steps/example_steps.rb:11") @io.string.should include("Given 999999999 # steps/example_steps.rb:11") end it "should align step comments with respect to their scenario's comment" do step = mock_step(:regexp_args_proc => [nil, nil, mock_proc], :error => StandardError.new, :padding_length => 6) @formatter.scenario_executing(mock_scenario(:name => "very long title", :file => 'features/example.feature', :line => 5, :steps => [step], :padding_length => 2)) @formatter.step_passed(step, nil, nil) @io.string.should include("Scenario: very long title # features/example.feature:5") @io.string.should include(" Given formatted yes # steps/example_steps.rb:11") end end end end end
41.276786
171
0.572788
1d5fa6883b262e38264185d50bc78795707fb88e
916
class ComedyShows::Shows BASE_PATH = "https://www.dcimprov.com/" attr_accessor :name, :description, :date, :month, :url, :price, :showtime, :spotlight, :address @@all = [] #incorporate all scraped data here def initialize(show_hash) show_hash.each{|k,v| self.send("#{k}=", v)} @@all << self end def self.create_shows(shows_array) #creates show instances from the schedule page using scraper hash shows_array.each do |s| ComedyShows::Shows.new(s) #they are automatically pushed into @@all end end def self.add_details_to_show(url) details = ComedyShows::Scraper.scrape_show_details(BASE_PATH + "#{url}") #creates a hash of details ComedyShows::Shows.all.detect do |s| if s.url == url details.each{|k,v| s.send("#{k}=", v)} #adds the individual details hash to the correct instance of show end end end def self.all @@all end end
26.941176
112
0.670306
3947affbcf7e42e3b4e29421218f1fe979cae8f8
1,136
require 'inifile' # Stores configuration file. class BotConfig def initialize(ini_filename) @ini_filename = ini_filename reload end def reload @ini_file = IniFile.load(@ini_filename) if @ini_file == nil raise "#{@ini_filename} not found." end end def get_common_section get_section('common') end def has_section?(name) @ini_file.has_section?(name) end def get_section(name) section = {} if has_section?(name) section = @ini_file[name] end section end def get_socket_path File.expand_path(self.get_common_section.fetch('socket_path', '/tmp/endobot.sock')) end def get_pid_directory File.expand_path(self.get_common_section.fetch('pid_dir', '/tmp')) end def get_log_path File.expand_path(self.get_common_section.fetch('log_path', '/var/log/endobot.log')) end def get_log_level self.get_common_section.fetch('log_level', 'INFO').to_sym end def get_user_mappings user_mappings = {} if @ini_file.has_section?('user-mappings') user_mappings = @ini_file['user-mappings'] end user_mappings end end
19.254237
87
0.691021
d5d17e4c57cb785402dfdf3c233ec8c9b7557622
1,035
# coding: utf-8 lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "ar_enum_i18n/version" Gem::Specification.new do |spec| spec.name = "ar_enum_i18n" spec.version = ArEnumI18n::VERSION spec.authors = ["Andrea Dal Ponte"] spec.email = ["[email protected]"] spec.summary = %q{ActiveRecord Enum I18n support} spec.description = %q{ActiveRecord Enum I18n support} spec.homepage = "https://github.com/dalpo/ar_enum_i18n" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.15" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.0" spec.add_development_dependency "rubocop", "~> 0.50" end
34.5
74
0.651208
33f1f3739e6bd378be3fa1b90bff5275db754ec9
426
class AddDescriptionToTraffic < ActiveRecord::Migration def change a = Game.find_by_slug('traffic') a.description = "Traffic -- look both way or you are going to be as flat as a board! This game require a little bit of luck and a whole lot of good timing. Navigate across lanes of busy traffic to reach the other side. How many lanes of traffic can you cross before your luck runs out?" a.save end end
53.25
297
0.734742
03b65074f4444073f64da1f724fbcf6f37e465b3
28,817
module ActionController #:nodoc: module Filters #:nodoc: def self.included(base) base.extend(ClassMethods) base.send(:include, ActionController::Filters::InstanceMethods) end # Filters enable controllers to run shared pre and post processing code for its actions. These filters can be used to do # authentication, caching, or auditing before the intended action is performed. Or to do localization or output # compression after the action has been performed. Filters have access to the request, response, and all the instance # variables set by other filters in the chain or by the action (in the case of after filters). # # == Filter inheritance # # Controller inheritance hierarchies share filters downwards, but subclasses can also add or skip filters without # affecting the superclass. For example: # # class BankController < ActionController::Base # before_filter :audit # # private # def audit # # record the action and parameters in an audit log # end # end # # class VaultController < BankController # before_filter :verify_credentials # # private # def verify_credentials # # make sure the user is allowed into the vault # end # end # # Now any actions performed on the BankController will have the audit method called before. On the VaultController, # first the audit method is called, then the verify_credentials method. If the audit method returns false, then # verify_credentials and the intended action are never called. # # == Filter types # # A filter can take one of three forms: method reference (symbol), external class, or inline method (proc). The first # is the most common and works by referencing a protected or private method somewhere in the inheritance hierarchy of # the controller by use of a symbol. In the bank example above, both BankController and VaultController use this form. # # Using an external class makes for more easily reused generic filters, such as output compression. External filter classes # are implemented by having a static +filter+ method on any class and then passing this class to the filter method. Example: # # class OutputCompressionFilter # def self.filter(controller) # controller.response.body = compress(controller.response.body) # end # end # # class NewspaperController < ActionController::Base # after_filter OutputCompressionFilter # end # # The filter method is passed the controller instance and is hence granted access to all aspects of the controller and can # manipulate them as it sees fit. # # The inline method (using a proc) can be used to quickly do something small that doesn't require a lot of explanation. # Or just as a quick test. It works like this: # # class WeblogController < ActionController::Base # before_filter { |controller| false if controller.params["stop_action"] } # end # # As you can see, the block expects to be passed the controller after it has assigned the request to the internal variables. # This means that the block has access to both the request and response objects complete with convenience methods for params, # session, template, and assigns. Note: The inline method doesn't strictly have to be a block; any object that responds to call # and returns 1 or -1 on arity will do (such as a Proc or an Method object). # # Please note that around_filters function a little differently than the normal before and after filters with regard to filter # types. Please see the section dedicated to around_filters below. # # == Filter chain ordering # # Using <tt>before_filter</tt> and <tt>after_filter</tt> appends the specified filters to the existing chain. That's usually # just fine, but some times you care more about the order in which the filters are executed. When that's the case, you # can use <tt>prepend_before_filter</tt> and <tt>prepend_after_filter</tt>. Filters added by these methods will be put at the # beginning of their respective chain and executed before the rest. For example: # # class ShoppingController < ActionController::Base # before_filter :verify_open_shop # # class CheckoutController < ShoppingController # prepend_before_filter :ensure_items_in_cart, :ensure_items_in_stock # # The filter chain for the CheckoutController is now <tt>:ensure_items_in_cart, :ensure_items_in_stock,</tt> # <tt>:verify_open_shop</tt>. So if either of the ensure filters return false, we'll never get around to see if the shop # is open or not. # # You may pass multiple filter arguments of each type as well as a filter block. # If a block is given, it is treated as the last argument. # # == Around filters # # Around filters wrap an action, executing code both before and after. # They may be declared as method references, blocks, or objects responding # to #filter or to both #before and #after. # # To use a method as an around_filter, pass a symbol naming the Ruby method. # Yield (or block.call) within the method to run the action. # # around_filter :catch_exceptions # # private # def catch_exceptions # yield # rescue => exception # logger.debug "Caught exception! #{exception}" # raise # end # # To use a block as an around_filter, pass a block taking as args both # the controller and the action block. You can't call yield directly from # an around_filter block; explicitly call the action block instead: # # around_filter do |controller, action| # logger.debug "before #{controller.action_name}" # action.call # logger.debug "after #{controller.action_name}" # end # # To use a filter object with around_filter, pass an object responding # to :filter or both :before and :after. With a filter method, yield to # the block as above: # # around_filter BenchmarkingFilter # # class BenchmarkingFilter # def self.filter(controller, &block) # Benchmark.measure(&block) # end # end # # With before and after methods: # # around_filter Authorizer.new # # class Authorizer # # This will run before the action. Returning false aborts the action. # def before(controller) # if user.authorized? # return true # else # redirect_to login_url # return false # end # end # # # This will run after the action if and only if before returned true. # def after(controller) # end # end # # If the filter has before and after methods, the before method will be # called before the action. If before returns false, the filter chain is # halted and after will not be run. See Filter Chain Halting below for # an example. # # == Filter chain skipping # # Declaring a filter on a base class conveniently applies to its subclasses, # but sometimes a subclass should skip some of its superclass' filters: # # class ApplicationController < ActionController::Base # before_filter :authenticate # around_filter :catch_exceptions # end # # class WeblogController < ApplicationController # # Will run the :authenticate and :catch_exceptions filters. # end # # class SignupController < ApplicationController # # Skip :authenticate, run :catch_exceptions. # skip_before_filter :authenticate # end # # class ProjectsController < ApplicationController # # Skip :catch_exceptions, run :authenticate. # skip_filter :catch_exceptions # end # # class ClientsController < ApplicationController # # Skip :catch_exceptions and :authenticate unless action is index. # skip_filter :catch_exceptions, :authenticate, :except => :index # end # # == Filter conditions # # Filters may be limited to specific actions by declaring the actions to # include or exclude. Both options accept single actions (:only => :index) # or arrays of actions (:except => [:foo, :bar]). # # class Journal < ActionController::Base # # Require authentication for edit and delete. # before_filter :authorize, :only => [:edit, :delete] # # # Passing options to a filter with a block. # around_filter(:except => :index) do |controller, action_block| # results = Profiler.run(&action_block) # controller.response.sub! "</body>", "#{results}</body>" # end # # private # def authorize # # Redirect to login unless authenticated. # end # end # # == Filter Chain Halting # # <tt>before_filter</tt> and <tt>around_filter</tt> may halt the request # before a controller action is run. This is useful, for example, to deny # access to unauthenticated users or to redirect from http to https. # Simply return false from the filter or call render or redirect. # After filters will not be executed if the filter chain is halted. # # Around filters halt the request unless the action block is called. # Given these filters # after_filter :after # around_filter :around # before_filter :before # # The filter chain will look like: # # ... # . \ # . #around (code before yield) # . . \ # . . #before (actual filter code is run) # . . . \ # . . . execute controller action # . . . / # . . ... # . . / # . #around (code after yield) # . / # #after (actual filter code is run, unless the around filter does not yield) # # If #around returns before yielding, #after will still not be run. The #before # filter and controller action will not be run. If #before returns false, # the second half of #around and will still run but #after and the # action will not. If #around fails to yield, #after will not be run. module ClassMethods # The passed <tt>filters</tt> will be appended to the filter_chain and # will execute before the action on this controller is performed. def append_before_filter(*filters, &block) append_filter_to_chain(filters, :before, &block) end # The passed <tt>filters</tt> will be prepended to the filter_chain and # will execute before the action on this controller is performed. def prepend_before_filter(*filters, &block) prepend_filter_to_chain(filters, :before, &block) end # Shorthand for append_before_filter since it's the most common. alias :before_filter :append_before_filter # The passed <tt>filters</tt> will be appended to the array of filters # that run _after_ actions on this controller are performed. def append_after_filter(*filters, &block) append_filter_to_chain(filters, :after, &block) end # The passed <tt>filters</tt> will be prepended to the array of filters # that run _after_ actions on this controller are performed. def prepend_after_filter(*filters, &block) prepend_filter_to_chain(filters, :after, &block) end # Shorthand for append_after_filter since it's the most common. alias :after_filter :append_after_filter # If you append_around_filter A.new, B.new, the filter chain looks like # # B#before # A#before # # run the action # A#after # B#after # # With around filters which yield to the action block, #before and #after # are the code before and after the yield. def append_around_filter(*filters, &block) filters, conditions = extract_conditions(filters, &block) filters.map { |f| proxy_before_and_after_filter(f) }.each do |filter| append_filter_to_chain([filter, conditions]) end end # If you prepend_around_filter A.new, B.new, the filter chain looks like: # # A#before # B#before # # run the action # B#after # A#after # # With around filters which yield to the action block, #before and #after # are the code before and after the yield. def prepend_around_filter(*filters, &block) filters, conditions = extract_conditions(filters, &block) filters.map { |f| proxy_before_and_after_filter(f) }.each do |filter| prepend_filter_to_chain([filter, conditions]) end end # Shorthand for append_around_filter since it's the most common. alias :around_filter :append_around_filter # Removes the specified filters from the +before+ filter chain. Note that this only works for skipping method-reference # filters, not procs. This is especially useful for managing the chain in inheritance hierarchies where only one out # of many sub-controllers need a different hierarchy. # # You can control the actions to skip the filter for with the <tt>:only</tt> and <tt>:except</tt> options, # just like when you apply the filters. def skip_before_filter(*filters) skip_filter_in_chain(*filters, &:before?) end # Removes the specified filters from the +after+ filter chain. Note that this only works for skipping method-reference # filters, not procs. This is especially useful for managing the chain in inheritance hierarchies where only one out # of many sub-controllers need a different hierarchy. # # You can control the actions to skip the filter for with the <tt>:only</tt> and <tt>:except</tt> options, # just like when you apply the filters. def skip_after_filter(*filters) skip_filter_in_chain(*filters, &:after?) end # Removes the specified filters from the filter chain. This only works for method reference (symbol) # filters, not procs. This method is different from skip_after_filter and skip_before_filter in that # it will match any before, after or yielding around filter. # # You can control the actions to skip the filter for with the <tt>:only</tt> and <tt>:except</tt> options, # just like when you apply the filters. def skip_filter(*filters) skip_filter_in_chain(*filters) end # Returns an array of Filter objects for this controller. def filter_chain read_inheritable_attribute("filter_chain") || [] end # Returns all the before filters for this class and all its ancestors. # This method returns the actual filter that was assigned in the controller to maintain existing functionality. def before_filters #:nodoc: filter_chain.select(&:before?).map(&:filter) end # Returns all the after filters for this class and all its ancestors. # This method returns the actual filter that was assigned in the controller to maintain existing functionality. def after_filters #:nodoc: filter_chain.select(&:after?).map(&:filter) end # Returns a mapping between filters and the actions that may run them. def included_actions #:nodoc: @included_actions ||= read_inheritable_attribute("included_actions") || {} end # Returns a mapping between filters and actions that may not run them. def excluded_actions #:nodoc: @excluded_actions ||= read_inheritable_attribute("excluded_actions") || {} end # Find a filter in the filter_chain where the filter method matches the _filter_ param # and (optionally) the passed block evaluates to true (mostly used for testing before? # and after? on the filter). Useful for symbol filters. # # The object of type Filter is passed to the block when yielded, not the filter itself. def find_filter(filter, &block) #:nodoc: filter_chain.select { |f| f.filter == filter && (!block_given? || yield(f)) }.first end # Returns true if the filter is excluded from the given action def filter_excluded_from_action?(filter,action) #:nodoc: case when ia = included_actions[filter] !ia.include?(action) when ea = excluded_actions[filter] ea.include?(action) end end # Filter class is an abstract base class for all filters. Handles all of the included/excluded actions but # contains no logic for calling the actual filters. class Filter #:nodoc: attr_reader :filter, :included_actions, :excluded_actions def initialize(filter) @filter = filter end def type :around end def before? type == :before end def after? type == :after end def around? type == :around end def run(controller) raise ActionControllerError, 'No filter type: Nothing to do here.' end def call(controller, &block) run(controller) end end # Abstract base class for filter proxies. FilterProxy objects are meant to mimic the behaviour of the old # before_filter and after_filter by moving the logic into the filter itself. class FilterProxy < Filter #:nodoc: def filter @filter.filter end end class BeforeFilterProxy < FilterProxy #:nodoc: def type :before end def run(controller) # only filters returning false are halted. if false == @filter.call(controller) controller.send :halt_filter_chain, @filter, :returned_false end end def call(controller) yield unless run(controller) end end class AfterFilterProxy < FilterProxy #:nodoc: def type :after end def run(controller) @filter.call(controller) end def call(controller) yield run(controller) end end class SymbolFilter < Filter #:nodoc: def call(controller, &block) controller.send(@filter, &block) end end class ProcFilter < Filter #:nodoc: def call(controller) @filter.call(controller) rescue LocalJumpError # a yield from a proc... no no bad dog. raise(ActionControllerError, 'Cannot yield from a Proc type filter. The Proc must take two arguments and execute #call on the second argument.') end end class ProcWithCallFilter < Filter #:nodoc: def call(controller, &block) @filter.call(controller, block) rescue LocalJumpError # a yield from a proc... no no bad dog. raise(ActionControllerError, 'Cannot yield from a Proc type filter. The Proc must take two arguments and execute #call on the second argument.') end end class MethodFilter < Filter #:nodoc: def call(controller, &block) @filter.call(controller, &block) end end class ClassFilter < Filter #:nodoc: def call(controller, &block) @filter.filter(controller, &block) end end class ClassBeforeFilter < Filter #:nodoc: def call(controller, &block) @filter.before(controller) end end class ClassAfterFilter < Filter #:nodoc: def call(controller, &block) @filter.after(controller) end end protected def append_filter_to_chain(filters, filter_type = :around, &block) pos = find_filter_append_position(filters, filter_type) update_filter_chain(filters, filter_type, pos, &block) end def prepend_filter_to_chain(filters, filter_type = :around, &block) pos = find_filter_prepend_position(filters, filter_type) update_filter_chain(filters, filter_type, pos, &block) end def update_filter_chain(filters, filter_type, pos, &block) new_filters = create_filters(filters, filter_type, &block) new_chain = filter_chain.insert(pos, new_filters).flatten write_inheritable_attribute('filter_chain', new_chain) end def find_filter_append_position(filters, filter_type) # appending an after filter puts it at the end of the call chain # before and around filters go before the first after filter in the chain unless filter_type == :after filter_chain.each_with_index do |f,i| return i if f.after? end end return -1 end def find_filter_prepend_position(filters, filter_type) # prepending a before or around filter puts it at the front of the call chain # after filters go before the first after filter in the chain if filter_type == :after filter_chain.each_with_index do |f,i| return i if f.after? end return -1 end return 0 end def create_filters(filters, filter_type, &block) #:nodoc: filters, conditions = extract_conditions(filters, &block) filters.map! { |filter| find_or_create_filter(filter, filter_type) } update_conditions(filters, conditions) filters end def find_or_create_filter(filter, filter_type) if found_filter = find_filter(filter) { |f| f.type == filter_type } found_filter else f = class_for_filter(filter, filter_type).new(filter) # apply proxy to filter if necessary case filter_type when :before BeforeFilterProxy.new(f) when :after AfterFilterProxy.new(f) else f end end end # The determination of the filter type was once done at run time. # This method is here to extract as much logic from the filter run time as possible def class_for_filter(filter, filter_type) #:nodoc: case when filter.is_a?(Symbol) SymbolFilter when filter.respond_to?(:call) if filter.is_a?(Method) MethodFilter elsif filter.arity == 1 ProcFilter else ProcWithCallFilter end when filter.respond_to?(:filter) ClassFilter when filter.respond_to?(:before) && filter_type == :before ClassBeforeFilter when filter.respond_to?(:after) && filter_type == :after ClassAfterFilter else raise(ActionControllerError, 'A filter must be a Symbol, Proc, Method, or object responding to filter, after or before.') end end def extract_conditions(*filters, &block) #:nodoc: filters.flatten! conditions = filters.extract_options! filters << block if block_given? return filters, conditions end def update_conditions(filters, conditions) return if conditions.empty? if conditions[:only] write_inheritable_hash('included_actions', condition_hash(filters, conditions[:only])) elsif conditions[:except] write_inheritable_hash('excluded_actions', condition_hash(filters, conditions[:except])) end end def condition_hash(filters, *actions) actions = actions.flatten.map(&:to_s) filters.inject({}) { |h,f| h.update( f => (actions.blank? ? nil : actions)) } end def skip_filter_in_chain(*filters, &test) #:nodoc: filters, conditions = extract_conditions(filters) filters.map! { |f| block_given? ? find_filter(f, &test) : find_filter(f) } filters.compact! if conditions.empty? delete_filters_in_chain(filters) else remove_actions_from_included_actions!(filters,conditions[:only] || []) conditions[:only], conditions[:except] = conditions[:except], conditions[:only] update_conditions(filters,conditions) end end def remove_actions_from_included_actions!(filters,*actions) actions = actions.flatten.map(&:to_s) updated_hash = filters.inject(read_inheritable_attribute('included_actions')||{}) do |hash,filter| ia = (hash[filter] || []) - actions ia.empty? ? hash.delete(filter) : hash[filter] = ia hash end write_inheritable_attribute('included_actions', updated_hash) end def delete_filters_in_chain(filters) #:nodoc: write_inheritable_attribute('filter_chain', filter_chain.reject { |f| filters.include?(f) }) end def filter_responds_to_before_and_after(filter) #:nodoc: filter.respond_to?(:before) && filter.respond_to?(:after) end def proxy_before_and_after_filter(filter) #:nodoc: return filter unless filter_responds_to_before_and_after(filter) Proc.new do |controller, action| if filter.before(controller) == false controller.send :halt_filter_chain, filter, :returned_false else begin action.call ensure filter.after(controller) end end end end end module InstanceMethods # :nodoc: def self.included(base) base.class_eval do alias_method_chain :perform_action, :filters alias_method_chain :process, :filters end end protected def process_with_filters(request, response, method = :perform_action, *arguments) #:nodoc: @before_filter_chain_aborted = false process_without_filters(request, response, method, *arguments) end def perform_action_with_filters call_filters(self.class.filter_chain, 0, 0) end private def call_filters(chain, index, nesting) index = run_before_filters(chain, index, nesting) aborted = @before_filter_chain_aborted perform_action_without_filters unless performed? || aborted return index if nesting != 0 || aborted run_after_filters(chain, index) end def skip_excluded_filters(chain, index) while (filter = chain[index]) && self.class.filter_excluded_from_action?(filter, action_name) index = index.next end [filter, index] end def run_before_filters(chain, index, nesting) while chain[index] filter, index = skip_excluded_filters(chain, index) break unless filter # end of call chain reached case filter.type when :before filter.run(self) # invoke before filter index = index.next break if @before_filter_chain_aborted when :around yielded = false filter.call(self) do yielded = true # all remaining before and around filters will be run in this call index = call_filters(chain, index.next, nesting.next) end halt_filter_chain(filter, :did_not_yield) unless yielded break else break # no before or around filters left end end index end def run_after_filters(chain, index) seen_after_filter = false while chain[index] filter, index = skip_excluded_filters(chain, index) break unless filter # end of call chain reached case filter.type when :after seen_after_filter = true filter.run(self) # invoke after filter else # implementation error or someone has mucked with the filter chain raise ActionControllerError, "filter #{filter.inspect} was in the wrong place!" if seen_after_filter end index = index.next end index.next end def halt_filter_chain(filter, reason) @before_filter_chain_aborted = true logger.info "Filter chain halted as [#{filter.inspect}] #{reason}." if logger false end end end end
38.067371
154
0.636916
1ac09ce11d021308db83580b40af22f6495b09a8
757
# frozen_string_literal: true module Onebox module Engine class AudioOnebox include Engine matches_regexp(/^(https?:)?\/\/.*\.(mp3|ogg|opus|wav|m4a)(\?.*)?$/i) def always_https? AllowlistedGenericOnebox.host_matches(uri, AllowlistedGenericOnebox.https_hosts) end def to_html escaped_url = ::Onebox::Helpers.normalize_url_for_output(@url) <<-HTML <audio controls #{@options[:disable_media_download_controls] ? 'controlslist="nodownload"' : ""}> <source src="#{escaped_url}"> <a href="#{escaped_url}">#{@url}</a> </audio> HTML end def placeholder_html ::Onebox::Helpers.audio_placeholder_html end end end end
24.419355
107
0.610304
e96787af8af6a5165d54b465b749c4043093a90f
846
# encoding: UTF-8 module MongoMapper module Extensions module Boolean Mapping = { true => true, 'true' => true, 'TRUE' => true, 'True' => true, 't' => true, 'T' => true, '1' => true, 1 => true, 1.0 => true, false => false, 'false' => false, 'FALSE' => false, 'False' => false, 'f' => false, 'F' => false, '0' => false, 0 => false, 0.0 => false, nil => nil } def to_mongo(value) Mapping[value] end def from_mongo(value) return nil if value == nil !!value end end end end class Boolean; end unless defined?(Boolean) Boolean.extend MongoMapper::Extensions::Boolean
20.142857
47
0.426714
ffc702bc552b6b5bdb485d490a0bf1b4129b4b16
2,708
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Web::Mgmt::V2016_03_01 module Models # # Triggers for auto-heal. # class AutoHealTriggers include MsRestAzure # @return [RequestsBasedTrigger] A rule based on total requests. attr_accessor :requests # @return [Integer] A rule based on private bytes. attr_accessor :private_bytes_in_kb # @return [Array<StatusCodesBasedTrigger>] A rule based on status codes. attr_accessor :status_codes # @return [SlowRequestsBasedTrigger] A rule based on request execution # time. attr_accessor :slow_requests # # Mapper for AutoHealTriggers class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'AutoHealTriggers', type: { name: 'Composite', class_name: 'AutoHealTriggers', model_properties: { requests: { client_side_validation: true, required: false, serialized_name: 'requests', type: { name: 'Composite', class_name: 'RequestsBasedTrigger' } }, private_bytes_in_kb: { client_side_validation: true, required: false, serialized_name: 'privateBytesInKB', type: { name: 'Number' } }, status_codes: { client_side_validation: true, required: false, serialized_name: 'statusCodes', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'StatusCodesBasedTriggerElementType', type: { name: 'Composite', class_name: 'StatusCodesBasedTrigger' } } } }, slow_requests: { client_side_validation: true, required: false, serialized_name: 'slowRequests', type: { name: 'Composite', class_name: 'SlowRequestsBasedTrigger' } } } } } end end end end
29.758242
78
0.498523
ac46f529a56f7f67797cef497104610a1adbad52
3,158
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Creating a new HTTP Integration' do include GraphqlHelpers let_it_be(:current_user) { create(:user) } let_it_be(:project) { create(:project) } let(:payload_example) do { 'alert' => { 'name' => 'Test alert' }, 'started_at' => Time.current.strftime('%d %B %Y, %-l:%M%p (%Z)') }.to_json end let(:payload_attribute_mappings) do [ { fieldName: 'TITLE', path: %w[alert name], type: 'STRING' }, { fieldName: 'START_TIME', path: %w[started_at], type: 'DATETIME', label: 'Start time' } ] end let(:variables) do { project_path: project.full_path, active: false, name: 'New HTTP Integration', payload_example: payload_example, payload_attribute_mappings: payload_attribute_mappings } end let(:mutation) do graphql_mutation(:http_integration_create, variables) do <<~QL clientMutationId errors integration { id type name active token url apiUrl } QL end end let(:mutation_response) { graphql_mutation_response(:http_integration_create) } shared_examples 'ignoring the custom mapping' do it 'creates integration without the custom mapping params' do post_graphql_mutation(mutation, current_user: current_user) new_integration = ::AlertManagement::HttpIntegration.last! integration_response = mutation_response['integration'] expect(response).to have_gitlab_http_status(:success) expect(integration_response['id']).to eq(GitlabSchema.id_from_object(new_integration).to_s) expect(new_integration.payload_example).to eq({}) expect(new_integration.payload_attribute_mapping).to eq({}) end end before do project.add_maintainer(current_user) stub_licensed_features(multiple_alert_http_integrations: true) end it_behaves_like 'creating a new HTTP integration' it 'stores the custom mapping params' do post_graphql_mutation(mutation, current_user: current_user) new_integration = ::AlertManagement::HttpIntegration.last! expect(new_integration.payload_example).to eq(Gitlab::Json.parse(payload_example)) expect(new_integration.payload_attribute_mapping).to eq( { 'title' => { 'path' => %w[alert name], 'type' => 'string', 'label' => nil }, 'start_time' => { 'path' => %w[started_at], 'type' => 'datetime', 'label' => 'Start time' } } ) end [:project_path, :active, :name].each do |argument| context "without required argument #{argument}" do before do variables.delete(argument) end it_behaves_like 'an invalid argument to the mutation', argument_name: argument end end context 'with the custom mappings feature unavailable' do before do stub_licensed_features(multiple_alert_http_integrations: false) end it_behaves_like 'ignoring the custom mapping' end it_behaves_like 'validating the payload_example' it_behaves_like 'validating the payload_attribute_mappings' end
27.946903
99
0.677011
1adc2b29d9a6afa71c8b6f3518315af34078104e
782
Rails.application.routes.draw do get 'password_resets/new' get 'password_resets/edit' get 'sessions/new' root 'static_pages#home' get '/help', to: 'static_pages#help' get '/about', to: 'static_pages#about' get '/contact', to: 'static_pages#contact' get '/signup', to: 'users#new' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' delete '/logout', to: 'sessions#destroy' resources :users do member do get :following, :followers end end resources :users resources :account_activations, only: [:edit] resources :password_resets, only: [:new, :create, :edit, :update] resources :microposts, only: [:create, :destroy] resources :relationships, only: [:create, :destroy] end
28.962963
71
0.649616
39a54c46f07f363e5691c05c9836f923a8f78c9b
77
Date::DATE_FORMATS[:year_month] = '%Y-%m' Time::DATE_FORMATS[:hm] = '%H:%M'
19.25
41
0.623377
01bab854082aa5f4b9374af103c310c2ae2dbc19
1,242
# frozen_string_literal: true module Gitlab module GitalyClient class BlobsStitcher include Enumerable def initialize(rpc_response) @rpc_response = rpc_response end def each current_blob_data = nil @rpc_response.each do |msg| begin if msg.oid.blank? && msg.data.blank? next elsif msg.oid.present? yield new_blob(current_blob_data) if current_blob_data current_blob_data = msg.to_h.slice(:oid, :path, :size, :revision, :mode) current_blob_data[:data] = msg.data.dup else current_blob_data[:data] << msg.data end end end yield new_blob(current_blob_data) if current_blob_data end private def new_blob(blob_data) Gitlab::Git::Blob.new( id: blob_data[:oid], mode: blob_data[:mode].to_s(8), name: File.basename(blob_data[:path]), path: blob_data[:path], size: blob_data[:size], commit_id: blob_data[:revision], data: blob_data[:data], binary: Gitlab::Git::Blob.binary?(blob_data[:data]) ) end end end end
24.84
86
0.565217
ac9c8283b4bc9fd5a72ccbdf53022ec71ca442ca
1,956
module Github module Representation class PullRequest < Representation::Issuable attr_reader :project delegate :user, :repo, :ref, :sha, to: :source_branch, prefix: true delegate :user, :exists?, :repo, :ref, :sha, :short_sha, to: :target_branch, prefix: true def source_project project end def source_branch_exists? !cross_project? && source_branch.exists? end def source_branch_name @source_branch_name ||= if cross_project? || !source_branch_exists? source_branch_name_prefixed else source_branch_ref end end def target_project project end def target_branch_name @target_branch_name ||= target_branch_exists? ? target_branch_ref : target_branch_name_prefixed end def state return 'merged' if raw['state'] == 'closed' && raw['merged_at'].present? return 'closed' if raw['state'] == 'closed' 'opened' end def opened? state == 'opened' end def valid? source_branch.valid? && target_branch.valid? end private def project @project ||= options.fetch(:project) end def source_branch @source_branch ||= Representation::Branch.new(raw['head'], repository: project.repository) end def source_branch_name_prefixed "gh-#{target_branch_short_sha}/#{iid}/#{source_branch_user}/#{source_branch_ref}" end def target_branch @target_branch ||= Representation::Branch.new(raw['base'], repository: project.repository) end def target_branch_name_prefixed "gl-#{target_branch_short_sha}/#{iid}/#{target_branch_user}/#{target_branch_ref}" end def cross_project? return true if source_branch_repo.nil? source_branch_repo.id != target_branch_repo.id end end end end
24.759494
103
0.624744
18cdc3a38a6b71bb2dad11694f568ff76817bfe2
230
module MixRailsCore class Engine < ::Rails::Engine config.generators do |g| g.test_framework :rspec g.integration_tool :rspec end end end
23
91
0.478261
bbadbcf2c5a69c9b539415c8273071f7d90aeb6f
632
require 'json' package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json'))) Pod::Spec.new do |s| s.name = 'EXDevice' s.version = package['version'] s.summary = package['description'] s.description = package['description'] s.license = package['license'] s.author = package['author'] s.homepage = package['homepage'] s.platform = :ios, '10.0' s.source = { git: 'https://github.com/expo/expo.git' } s.source_files = 'EXDevice/**/*.{h,m}' s.preserve_paths = 'EXDevice/**/*.{h,m}' s.requires_arc = true s.dependency 'UMCore' end
30.095238
73
0.579114
33edea48d984892b24473ebc6a27267ddf6a7305
3,724
class ApmServerFull < Formula desc "Server for shipping APM metrics to Elasticsearch" homepage "https://www.elastic.co/" url "https://artifacts.elastic.co/downloads/apm-server/apm-server-7.12.0-darwin-x86_64.tar.gz?tap=elastic/homebrew-tap" version "7.12.0" sha256 "80bb60dce66a8e2d89d4982a0662d062829a9b119ea8b268d1b8e287d2582a45" conflicts_with "apm-server" conflicts_with "apm-server-oss" bottle :unneeded def install ["fields.yml", "ingest", "kibana", "module"].each { |d| libexec.install d if File.exist?(d) } (libexec/"bin").install "apm-server" (etc/"apm-server").install "apm-server.yml" (etc/"apm-server").install "modules.d" if File.exist?("modules.d") (bin/"apm-server").write <<~EOS #!/bin/sh exec #{libexec}/bin/apm-server \ --path.config #{etc}/apm-server \ --path.home #{libexec} \ --path.logs #{var}/log/apm-server \ --path.data #{var}/lib/apm-server \ "$@" EOS end def post_install (var/"lib/apm-server").mkpath (var/"log/apm-server").mkpath end plist_options :manual => "apm-server" def plist; <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>Program</key> <string>#{opt_bin}/apm-server</string> <key>RunAtLoad</key> <true/> </dict> </plist> EOS end test do require "socket" server = TCPServer.new(0) port = server.addr[1] server.close (testpath/"config/apm-server.yml").write <<~EOS apm-server: host: localhost:#{port} output.file: path: "#{testpath}/apm-server" filename: apm-server codec.format: string: '%{[transaction]}' EOS pid = fork do exec bin/"apm-server", "-path.config", testpath/"config", "-path.data", testpath/"data" end sleep 5 begin (testpath/"event").write <<~EOS {"metadata": {"process": {"pid": 1234}, "system": {"container": {"id": "container-id"}, "kubernetes": {"namespace": "namespace1", "pod": {"uid": "pod-uid", "name": "pod-name"}, "node": {"name": "node-name"}}}, "service": {"name": "1234_service-12a3", "language": {"name": "ecmascript"}, "agent": {"version": "3.14.0", "name": "elastic-node"}, "framework": {"name": "emac"}}}} {"error": {"id": "abcdef0123456789", "timestamp": 1533827045999000, "log": {"level": "custom log level","message": "Cannot read property 'baz' of undefined"}}} {"span": {"id": "0123456a89012345", "trace_id": "0123456789abcdef0123456789abcdef", "parent_id": "ab23456a89012345", "transaction_id": "ab23456a89012345", "parent": 1, "name": "GET /api/types", "type": "request.external", "action": "get", "start": 1.845, "duration": 3.5642981, "stacktrace": [], "context": {}}} {"transaction": {"trace_id": "01234567890123456789abcdefabcdef", "id": "abcdef1478523690", "type": "request", "duration": 32.592981, "timestamp": 1535655207154000, "result": "200", "context": null, "spans": null, "sampled": null, "span_count": {"started": 0}}} {"metricset": {"samples": {"go.memstats.heap.sys.bytes": {"value": 61235}}, "timestamp": 1496170422281000}} EOS system "curl", "-H", "Content-Type: application/x-ndjson", "-XPOST", "localhost:#{port}/intake/v2/events", "--data-binary", "@#{testpath}/event" sleep 5 s = (testpath/"apm-server/apm-server").read assert_match "\"id\":\"abcdef1478523690\"", s ensure Process.kill "SIGINT", pid Process.wait pid end end end
40.478261
383
0.611976
acae72bb893188778accedbb9bf0cd3c1dc41897
484
class UserPolicy class Scope < Struct.new(:user, :scope) def resolve raise NotImplementedError end end attr_reader :user, :record def initialize(user, record) @user = user @record = record end def index? raise NotImplementedError end def show? raise NotImplementedError end def create? raise NotImplementedError end def update? raise NotImplementedError end def destroy? raise NotImplementedError end end
13.828571
41
0.683884
03a887d2e9a1bb98eb77d3e6bed29e5f5c259fe6
7,790
# frozen_string_literal: true describe RuboCop::Cop::Performance::Detect do subject(:cop) { described_class.new(config) } let(:collection_method) { nil } let(:config) do RuboCop::Config.new( 'Style/CollectionMethods' => { 'PreferredMethods' => { 'detect' => collection_method } } ) end # rspec will not let you use a variable assigned using let outside # of `it` select_methods = %i[select find_all].freeze select_methods.each do |method| it "registers an offense when first is called on #{method}" do inspect_source("[1, 2, 3].#{method} { |i| i % 2 == 0 }.first") expect(cop.messages) .to eq(["Use `detect` instead of `#{method}.first`."]) end it "doesn't register an offense when first(n) is called on #{method}" do inspect_source("[1, 2, 3].#{method} { |i| i % 2 == 0 }.first(n)") expect(cop.offenses).to be_empty end it "registers an offense when last is called on #{method}" do inspect_source("[1, 2, 3].#{method} { |i| i % 2 == 0 }.last") expect(cop.messages) .to eq(["Use `reverse.detect` instead of `#{method}.last`."]) end it "doesn't register an offense when last(n) is called on #{method}" do inspect_source("[1, 2, 3].#{method} { |i| i % 2 == 0 }.last(n)") expect(cop.offenses).to be_empty end it "registers an offense when first is called on multiline #{method}" do inspect_source(<<-RUBY.strip_indent) [1, 2, 3].#{method} do |i| i % 2 == 0 end.first RUBY expect(cop.messages).to eq(["Use `detect` instead of `#{method}.first`."]) end it "registers an offense when last is called on multiline #{method}" do inspect_source(<<-RUBY.strip_indent) [1, 2, 3].#{method} do |i| i % 2 == 0 end.last RUBY expect(cop.messages) .to eq(["Use `reverse.detect` instead of `#{method}.last`."]) end it "registers an offense when first is called on #{method} short syntax" do inspect_source("[1, 2, 3].#{method}(&:even?).first") expect(cop.messages).to eq(["Use `detect` instead of `#{method}.first`."]) end it "registers an offense when last is called on #{method} short syntax" do inspect_source("[1, 2, 3].#{method}(&:even?).last") expect(cop.messages) .to eq(["Use `reverse.detect` instead of `#{method}.last`."]) end it "registers an offense when #{method} is called" \ 'on `lazy` without receiver' do inspect_source("lazy.#{method}(&:even?).first") expect(cop.messages).to eq(["Use `detect` instead of `#{method}.first`."]) end it "does not register an offense when #{method} is used " \ 'without first or last' do inspect_source("[1, 2, 3].#{method} { |i| i % 2 == 0 }") expect(cop.messages).to be_empty end it "does not register an offense when #{method} is called" \ 'without block or args' do inspect_source("adapter.#{method}.first") expect(cop.messages).to be_empty end it "does not register an offense when #{method} is called" \ 'with args but without ampersand syntax' do inspect_source("adapter.#{method}('something').first") expect(cop.messages).to be_empty end it "does not register an offense when #{method} is called" \ 'on lazy enumerable' do inspect_source("adapter.lazy.#{method} { 'something' }.first") expect(cop.messages).to be_empty end end it 'does not register an offense when detect is used' do expect_no_offenses('[1, 2, 3].detect { |i| i % 2 == 0 }') end context 'autocorrect' do shared_examples 'detect_autocorrect' do |preferred_method| context "with #{preferred_method}" do let(:collection_method) { preferred_method } select_methods.each do |method| it "corrects #{method}.first to #{preferred_method} (with block)" do source = "[1, 2, 3].#{method} { |i| i % 2 == 0 }.first" new_source = autocorrect_source(source) expect(new_source) .to eq("[1, 2, 3].#{preferred_method} { |i| i % 2 == 0 }") end it "corrects #{method}.last to reverse.#{preferred_method} " \ '(with block)' do source = "[1, 2, 3].#{method} { |i| i % 2 == 0 }.last" new_source = autocorrect_source(source) expect(new_source) .to eq("[1, 2, 3].reverse.#{preferred_method} { |i| i % 2 == 0 }") end it "corrects #{method}.first to #{preferred_method} (short syntax)" do source = "[1, 2, 3].#{method}(&:even?).first" new_source = autocorrect_source(source) expect(new_source).to eq("[1, 2, 3].#{preferred_method}(&:even?)") end it "corrects #{method}.last to reverse.#{preferred_method} " \ '(short syntax)' do source = "[1, 2, 3].#{method}(&:even?).last" new_source = autocorrect_source(source) expect(new_source) .to eq("[1, 2, 3].reverse.#{preferred_method}(&:even?)") end it "corrects #{method}.first to #{preferred_method} (multiline)" do source = <<-RUBY.strip_indent [1, 2, 3].#{method} do |i| i % 2 == 0 end.first RUBY new_source = autocorrect_source(source) expect(new_source).to eq(<<-RUBY.strip_indent) [1, 2, 3].#{preferred_method} do |i| i % 2 == 0 end RUBY end it "corrects #{method}.last to reverse.#{preferred_method} " \ '(multiline)' do source = <<-RUBY.strip_indent [1, 2, 3].#{method} do |i| i % 2 == 0 end.last RUBY new_source = autocorrect_source(source) expect(new_source) .to eq(<<-RUBY.strip_indent) [1, 2, 3].reverse.#{preferred_method} do |i| i % 2 == 0 end RUBY end it "corrects multiline #{method} to #{preferred_method} " \ "with 'first' on the last line" do source = <<-RUBY.strip_indent [1, 2, 3].#{method} { true } .first['x'] RUBY new_source = autocorrect_source(source) expect(new_source) .to eq("[1, 2, 3].#{preferred_method} { true }['x']\n") end it "corrects multiline #{method} to #{preferred_method} " \ "with 'first' on the last line (short syntax)" do source = <<-RUBY.strip_indent [1, 2, 3].#{method}(&:blank?) .first['x'] RUBY new_source = autocorrect_source(source) expect(new_source) .to eq("[1, 2, 3].#{preferred_method}(&:blank?)['x']\n") end end end end it_behaves_like 'detect_autocorrect', 'detect' it_behaves_like 'detect_autocorrect', 'find' end context 'SafeMode true' do let(:config) do RuboCop::Config.new( 'Rails' => { 'Enabled' => true }, 'Style/CollectionMethods' => { 'PreferredMethods' => { 'detect' => collection_method } }, 'Performance/Detect' => { 'SafeMode' => true } ) end select_methods.each do |method| it "doesn't register an offense when first is called on #{method}" do inspect_source("[1, 2, 3].#{method} { |i| i % 2 == 0 }.first") expect(cop.offenses).to be_empty end end end end
30.912698
80
0.543389
f81a11ac0253b87dce8928fabb302f4f0b273e30
262
module Blog module FeedHelper def rss_feed_url Settings.app.feeds.rss rescue blog.feed_path(:format => :rss) end def atom_feed_url Settings.app.feeds.atom rescue blog.feed_path(:format => :atom) end end end
14.555556
38
0.629771
01f3bed3ffc5027bf7d88c87bf10e58aa3525e51
471
# frozen_string_literal: true require "helper" class TestSiteDrop < JekyllUnitTest context "a site drop" do setup do @site = fixture_site( "collections" => ["thanksgiving"] ) @site.process @drop = @site.to_liquid.site end should "respond to `key?`" do assert @drop.respond_to?(:key?) end should "find a key if it's in the collection of the drop" do assert @drop.key?("thanksgiving") end end end
19.625
64
0.622081
e87aaa19546f9afaf3ab92941cb76dd3f8848224
4,695
# frozen_string_literal: true require 'spec_helper' describe RuboCop::Cop::Style::ClassAndModuleChildren, :config do subject(:cop) { described_class.new(config) } context 'nested style' do let(:cop_config) { { 'EnforcedStyle' => 'nested' } } it 'registers an offense for not nested classes' do inspect_source(cop, ['class FooClass::BarClass', 'end']) expect(cop.offenses.size).to eq 1 expect(cop.messages).to eq [ 'Use nested module/class definitions instead of compact style.' ] expect(cop.highlights).to eq ['FooClass::BarClass'] end it 'registers an offense for not nested classes with explicit superclass' do inspect_source(cop, ['class FooClass::BarClass < Super', 'end']) expect(cop.offenses.size).to eq 1 expect(cop.messages).to eq [ 'Use nested module/class definitions instead of compact style.' ] expect(cop.highlights).to eq ['FooClass::BarClass'] end it 'registers an offense for not nested modules' do inspect_source(cop, ['module FooModule::BarModule', 'end']) expect(cop.offenses.size).to eq 1 expect(cop.messages).to eq [ 'Use nested module/class definitions instead of compact style.' ] expect(cop.highlights).to eq ['FooModule::BarModule'] end it 'accepts nested children' do inspect_source(cop, ['class FooClass', ' class BarClass', ' end', 'end', '', 'module FooModule', ' module BarModule', ' end', 'end']) expect(cop.offenses).to be_empty end it 'accepts :: in parent class on inheritance' do inspect_source(cop, ['class FooClass', ' class BarClass', ' end', 'end', '', 'class BazClass < FooClass::BarClass', 'end']) expect(cop.offenses).to be_empty end end context 'compact style' do let(:cop_config) { { 'EnforcedStyle' => 'compact' } } it 'registers a offense for classes with nested children' do inspect_source(cop, ['class FooClass', ' class BarClass', ' end', 'end']) expect(cop.offenses.size).to eq 1 expect(cop.messages).to eq [ 'Use compact module/class definition instead of nested style.' ] expect(cop.highlights).to eq ['FooClass'] end it 'registers a offense for modules with nested children' do inspect_source(cop, ['module FooModule', ' module BarModule', ' end', 'end']) expect(cop.offenses.size).to eq 1 expect(cop.messages).to eq [ 'Use compact module/class definition instead of nested style.' ] expect(cop.highlights).to eq ['FooModule'] end it 'accepts compact style for classes/modules' do inspect_source(cop, ['class FooClass::BarClass', 'end', '', 'module FooClass::BarModule', 'end']) expect(cop.offenses).to be_empty end it 'accepts nesting for classes/modules with more than one child' do inspect_source(cop, ['class FooClass', ' class BarClass', ' end', ' class BazClass', ' end', 'end', '', 'module FooModule', ' module BarModule', ' end', ' class BazModule', ' end', 'end']) expect(cop.offenses).to be_empty end it 'accepts class/module with single method' do inspect_source(cop, ['class FooClass', ' def bar_method', ' end', 'end']) expect(cop.offenses).to be_empty end it 'accepts nesting for classes with an explicit superclass' do inspect_source(cop, ['class FooClass < Super', ' class BarClass', ' end', 'end']) expect(cop.offenses).to be_empty end end end
31.938776
80
0.488179
08dc7d1064070c7e68ed328f1f60326c4c2fefa0
868
# # Cookbook Name:: rssh # Resource:: user # # Copyright 2014, Dan Fruehauf # # 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. # actions :add, :remove default_action :add attribute :name, :kind_of => String, :name_attribute => true attribute :options, :kind_of => String, :default => '' attribute :config_path, :kind_of => String, :default => node['rssh']['config_path']
33.384615
83
0.737327
4a4f42b261a604462fdeb5ae9d89ad4d8e17c1a6
2,608
# GnuTLS has previous, current, and next stable branches, we use current. # From 3.4.0 GnuTLS will be permanently disabling SSLv3. Every brew uses will need a revision with that. # http://nmav.gnutls.org/2014/10/what-about-poodle.html class Gnutls < Formula desc "GNU Transport Layer Security (TLS) Library" homepage "http://gnutls.org/" url "ftp://ftp.gnutls.org/gcrypt/gnutls/v3.3/gnutls-3.3.20.tar.xz" mirror "https://gnupg.org/ftp/gcrypt/gnutls/v3.3/gnutls-3.3.20.tar.xz" mirror "https://www.mirrorservice.org/sites/ftp.gnupg.org/gcrypt/gnutls/v3.3/gnutls-3.3.20.tar.xz" sha256 "4c903e5cde7a8f15318af9a7a6c9b7fc8348594b0a1e9ac767636ef2187399ea" bottle do cellar :any sha256 "cbf86659cf003d97e9ccb8c95fd16993cd72392757c133c98460da015c1fb6c9" => :el_capitan sha256 "79184c2aa6a0861967f3575fde728002cd9bd36f467e70f9232330088a3b9288" => :yosemite sha256 "d9b116e3e6844dde469efc4ec5025e667849d1aa3fc54ca41d93c9f9b6584893" => :mavericks end depends_on "pkg-config" => :build depends_on "libtasn1" depends_on "gmp" depends_on "nettle" depends_on "guile" => :optional depends_on "p11-kit" => :optional depends_on "unbound" => :optional fails_with :llvm do build 2326 cause "Undefined symbols when linking" end def install args = %W[ --disable-dependency-tracking --disable-silent-rules --disable-static --prefix=#{prefix} --sysconfdir=#{etc} --with-default-trust-store-file=#{etc}/openssl/cert.pem --disable-heartbeat-support ] if build.with? "guile" args << "--enable-guile" args << "--with-guile-site-dir=no" end system "./configure", *args system "make", "install" # certtool shadows the OS X certtool utility mv bin/"certtool", bin/"gnutls-certtool" mv man1/"certtool.1", man1/"gnutls-certtool.1" end def post_install keychains = %w[ /Library/Keychains/System.keychain /System/Library/Keychains/SystemRootCertificates.keychain ] certs_list = `security find-certificate -a -p #{keychains.join(" ")}` certs = certs_list.scan( /-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----/m ) valid_certs = certs.select do |cert| IO.popen("openssl x509 -inform pem -checkend 0 -noout", "w") do |openssl_io| openssl_io.write(cert) openssl_io.close_write end $?.success? end openssldir = etc/"openssl" openssldir.mkpath (openssldir/"cert.pem").atomic_write(valid_certs.join("\n")) end if OS.mac? test do system bin/"gnutls-cli", "--version" end end
30.682353
104
0.685966
6aeb48ecc69365f11debfe5a3d5149352a790b59
544
Pod::Spec.new do |s| s.name = 'ANBaseNetwork' s.version = '2.1.0' s.license = 'MIT' s.summary = 'ANBaseNetwork' s.homepage = 'https://github.com/anotheren/ANBaseNetwork' s.authors = { 'anotheren' => '[email protected]', } s.source = { :git => 'https://github.com/anotheren/ANBaseNetwork.git', :tag => s.version } s.ios.deployment_target = '10.0' s.swift_versions = ['5.0', '5.1'] s.source_files = 'Sources/**/*.swift' s.frameworks = 'Foundation' s.dependency 'Alamofire' end
32
94
0.604779
612a9ba93a8218ec3e708d9216f366ba6e274bed
1,116
namespace :gitlab do namespace :import do desc "GITLAB | Add all users to all projects (admin users are added as masters)" task all_users_to_all_projects: :environment do |t, args| user_ids = User.where(admin: false).pluck(:id) admin_ids = User.where(admin: true).pluck(:id) projects_ids = Project.pluck(:id) puts "Importing #{user_ids.size} users into #{projects_ids.size} projects" UsersProject.add_users_into_projects(projects_ids, user_ids, UsersProject::DEVELOPER) puts "Importing #{admin_ids.size} admins into #{projects_ids.size} projects" UsersProject.add_users_into_projects(projects_ids, admin_ids, UsersProject::MASTER) end desc "GITLAB | Add a specific user to all projects (as a developer)" task :user_to_projects, [:email] => :environment do |t, args| user = User.find_by(email: args.email) project_ids = Project.pluck(:id) puts "Importing #{user.email} users into #{project_ids.size} projects" UsersProject.add_users_into_projects(project_ids, Array.wrap(user.id), UsersProject::DEVELOPER) end end end
44.64
101
0.716846
5d13007bb4b7e21586833aa2c89e741cc4ddd08b
766
# Registers a new theme to use for this project. See # http://zen-cms.com/documentation/Zen/Theme.html for more information on all # the available options and working with themes in general. Zen::Theme.add do |theme| # The unique name of the theme specified as a symbol (required). theme.name = :default # The name of the author of the theme (required). theme.author = 'Zen' # A URL that points to a website/web page related to the theme. theme.url = 'http://zen-cms.com/' # A short description of the theme (required). theme.about = 'The default theme for Zen.' # The directory containing all the templates (required). theme.templates = __DIR__ # The directory containing all template partials. theme.partials = __DIR__('partials') end
33.304348
77
0.724543
7a6f5db3ccc3981013dfcf648c3fb8d19d341b93
834
class Sfcgal < Formula desc "C++ wrapper library around CGAL" homepage "http://sfcgal.org/" url "https://github.com/Oslandia/SFCGAL/archive/v1.3.7.tar.gz" sha256 "30ea1af26cb2f572c628aae08dd1953d80a69d15e1cac225390904d91fce031b" bottle do sha256 "91ad496500abf1cac33f959e8008abe7724f642f8dabc28b455efec9948fd917" => :mojave sha256 "e07e7c3eaf40aaf29f288dc7be2bacc725f4376e8cb6c85fd7e1662ef001458f" => :high_sierra sha256 "9ae7e2ab05d3d8dd6331b68ebaf5714f2cf0f69f406029c8089e98d5aba4273b" => :sierra end depends_on "cmake" => :build depends_on "boost" depends_on "cgal" depends_on "gmp" depends_on "mpfr" def install system "cmake", ".", *std_cmake_args system "make", "install" end test do assert_equal prefix.to_s, shell_output("#{bin}/sfcgal-config --prefix").strip end end
29.785714
93
0.757794
ab57d9583f23417e00085d71fcd21db4f69ee93f
796
require 'csv' class PayslipProcessor def process_csv employee_array = [] Dir.glob("csv/*.csv") do |file| basename = File.basename(file, '.csv') CSV.foreach(file, converters: :numeric, headers:true) do |row| employee_info = { first_name: row['first_name'], last_name: row['last_name'], salary: row['annual_salary'], super_rate: row['super_rate'], pay_period: row['pay_period'] } if Validator.valid?(employee_info) employee_array << Employee.new(employee_info) end end end employee_array end def create_payslips(employee_array) employee_array.map do |employee| payslip = Payslip.new(employee) payslip.generate payslip end end end
20.947368
68
0.609296
1d73541450b865e87604aa24bcb6c853f9c8d3c8
2,015
class Darkice < Formula desc "Live audio streamer" homepage "http://www.darkice.org/" url "https://downloads.sourceforge.net/project/darkice/darkice/1.3/darkice-1.3.tar.gz" sha256 "2c0d0faaa627c0273b2ce8b38775a73ef97e34ef866862a398f660ad8f6e9de6" revision 1 bottle do cellar :any sha256 "a35885863f951a6660c82a09158195172df5e8e29b1c02005e8627275a38d080" => :mojave sha256 "e07c9c9beafe2a9fae19ae6570181ef838da42755b9d9677535f8410768c1e7e" => :high_sierra sha256 "f5acac754cda3888160930ff630d33d5a7f134e455b21ad21a40b41150e12f49" => :sierra sha256 "a3a9604162e1dd71c1ec69cfec895e0a92329e57f478a01131a2a00a3c495544" => :el_capitan sha256 "64c3ebd7486589b3e9a216a4be8158ad94b1ceafac15934f97b4b3f3d684ad05" => :yosemite end depends_on "pkg-config" => :build depends_on "libvorbis" depends_on "lame" depends_on "two-lame" depends_on "faac" depends_on "libsamplerate" depends_on "jack" def install # Fixes "invalid conversion from 'const float*' to 'float*' [-fpermissive]" # Upstream issue Oct 25, 2016 https://github.com/rafael2k/darkice/issues/119 # Suggested fix Oct 25, 2016 https://github.com/rafael2k/darkice/pull/120 ["aacPlusEncoder.cpp", "FaacEncoder.cpp", "OpusLibEncoder.cpp", "VorbisLibEncoder.cpp"].each do |f| inreplace "src/#{f}", ", converterData.data_in", ", const_cast<float*>( converterData.data_in )" end system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--sysconfdir=#{etc}", "--with-lame-prefix=#{Formula["lame"].opt_prefix}", "--with-faac-prefix=#{Formula["faac"].opt_prefix}", "--with-twolame", "--with-jack", "--with-vorbis", "--with-samplerate" system "make", "install" end test do assert_match version.to_s, shell_output("#{bin}/darkice -h", 1) end end
41.979167
103
0.660546
e8fca8954481dbcbe137e3304a3133374a60dd2b
872
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'tarot/version' Gem::Specification.new do |spec| spec.name = "tarot" spec.version = Tarot::VERSION spec.authors = ["Dax"] spec.email = ["[email protected]"] spec.summary = %q{tarot spread maker} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency 'bound' spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake" spec.add_development_dependency "minitest" spec.add_development_dependency "minitest-spec" end
31.142857
74
0.651376