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
|
---|---|---|---|---|---|
0877c9dddec114d90f9636a5e03922337c66dee1 | 1,087 | # frozen_string_literal: true
module DiffViewer
module ServerSide
extend ActiveSupport::Concern
included do
self.collapse_limit = 1.megabyte
self.size_limit = 5.megabytes
end
def prepare!
diff_file.old_blob&.load_all_data!
diff_file.new_blob&.load_all_data!
end
def render_error
# Files that are not stored in the repository, like LFS files and
# build artifacts, can only be rendered using a client-side viewer,
# since we do not want to read large amounts of data into memory on the
# server side. Client-side viewers use JS and can fetch the file from
# `diff_file_blob_raw_path` and `diff_file_old_blob_raw_path` using AJAX.
return :server_side_but_stored_externally if diff_file.stored_externally?
super
end
private
def render_error_reason
return super unless render_error == :server_side_but_stored_externally
if diff_file.external_storage == :lfs
_('it is stored in LFS')
else
_('it is stored externally')
end
end
end
end
| 26.512195 | 79 | 0.698252 |
394d3dde79209b4f1fede6aeecc20ea4b646fd80 | 1,001 |
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "tencent_cloud_cos/version"
Gem::Specification.new do |spec|
spec.name = "tencent_cloud_cos"
spec.version = TencentCloudCos::VERSION
spec.authors = ["iamdbc"]
spec.email = [""]
spec.summary = %q{tencent cloud cos sdk.}
spec.description = %q{tencent cloud cos sdk.}
spec.homepage = "https://github.com/iamdbc/tencent_cloud_cos"
spec.license = "MIT"
spec.files = Dir['lib/**/*.rb']
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "rest-client", "~> 2.0"
spec.add_development_dependency "bundler", "~> 1.16"
spec.add_development_dependency "rake", "~> 13.0"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "mocha"
spec.add_development_dependency "pry", "~> 0"
end
| 33.366667 | 74 | 0.651349 |
18e63b283f7bdf0f0b6958a9b71a75c87a1d9bae | 124 | module ProfitAndLoss
class CostEntry < ActiveRecord::Base
include DisplayablePrices
has_many :comments
end
end
| 15.5 | 38 | 0.766129 |
0358fd9976a44223c0e22c93aacf16dede67786b | 1,751 | require "abstract_unit"
require "action_controller/metal/strong_parameters"
class LogOnUnpermittedParamsTest < ActiveSupport::TestCase
def setup
ActionController::Parameters.action_on_unpermitted_parameters = :log
end
def teardown
ActionController::Parameters.action_on_unpermitted_parameters = false
end
test "logs on unexpected param" do
params = ActionController::Parameters.new(
book: { pages: 65 },
fishing: "Turnips")
assert_logged("Unpermitted parameter: fishing") do
params.permit(book: [:pages])
end
end
test "logs on unexpected params" do
params = ActionController::Parameters.new(
book: { pages: 65 },
fishing: "Turnips",
car: "Mersedes")
assert_logged("Unpermitted parameters: fishing, car") do
params.permit(book: [:pages])
end
end
test "logs on unexpected nested param" do
params = ActionController::Parameters.new(
book: { pages: 65, title: "Green Cats and where to find then." })
assert_logged("Unpermitted parameter: title") do
params.permit(book: [:pages])
end
end
test "logs on unexpected nested params" do
params = ActionController::Parameters.new(
book: { pages: 65, title: "Green Cats and where to find then.", author: "G. A. Dog" })
assert_logged("Unpermitted parameters: title, author") do
params.permit(book: [:pages])
end
end
private
def assert_logged(message)
old_logger = ActionController::Base.logger
log = StringIO.new
ActionController::Base.logger = Logger.new(log)
begin
yield
log.rewind
assert_match message, log.read
ensure
ActionController::Base.logger = old_logger
end
end
end
| 25.376812 | 92 | 0.676185 |
01893d0cdac0d4144fa3742f232c6b1869b82d4c | 2,025 | require 'spec_helper'
RSpec.describe Hsquare::Device do
let(:client) { Hsquare.config.default_application.admin_client }
describe '.find_by_user_id' do
let(:user_id) { 123 }
let(:mock_response) { double(parsed_response: []) }
it { expect(client).to receive(:get).with('/v1/push/tokens', query: { uuid: user_id }).and_return(mock_response); Hsquare::Device.find_by_user_id(user_id) }
end
describe '#initialize' do
let(:attributes) { {} }
let(:device) { Hsquare::Device.new(attributes) }
context 'when attributes is set with proper values' do
let(:attributes) { { id: 2, type: 'apns', user_id: 3, token: 'token' } }
it { expect(device.id).to eq(attributes[:id]) }
it { expect(device.type).to eq(attributes[:type]) }
it { expect(device.user_id).to eq(attributes[:user_id]) }
it { expect(device.token).to eq(attributes[:token]) }
end
context 'when attributes is set with values from API response' do
let(:attributes) { { device_id: 2, push_type: 'apns', uuid: 3, push_token: 'token' } }
it { expect(device.id).to eq(attributes[:device_id]) }
it { expect(device.type).to eq(attributes[:push_type]) }
it { expect(device.user_id).to eq(attributes[:uuid]) }
it { expect(device.token).to eq(attributes[:push_token]) }
end
end
describe '#register' do
let(:attributes) { { id: 1, user_id: 2, type: 'apns', token: 'token' } }
let(:device) { Hsquare::Device.new(attributes) }
it { expect(client).to receive(:post).with('/v1/push/register', body: { uuid: device.user_id, device_id: device.id, push_type: device.type, push_token: device.token }); device.register }
end
describe '#unregister' do
let(:attributes) { { id: 1, user_id: 2, type: 'apns', token: 'token' } }
let(:device) { Hsquare::Device.new(attributes) }
it { expect(client).to receive(:post).with('/v1/push/deregister', body: { uuid: device.user_id, device_id: device.id, push_type: device.type }); device.unregister }
end
end
| 40.5 | 190 | 0.658272 |
21c7acc9a5060b423dacf97ab87bb2a5f5959088 | 1,249 | module Whiteprint
module Plugins
module HasAndBelongsToMany
extend ActiveSupport::Concern
class HasAndBelongsToManyModel
class << self
def setup(association: association)
include Whiteprint::Model
@join_table = association.join_table
whiteprint(adapter: :has_and_belongs_to_many, id: false, timestamps: false) do
integer association.foreign_key
integer association.association_foreign_key
end
end
def name
"#{@join_table}_habtm_model"
end
def table_name
@join_table
end
def table_exists?
::ActiveRecord::Base.connection.table_exists?(table_name)
end
end
end
def has_and_belongs_to_many(name, **options)
super(name, **options.merge(virtual: true))
model.send(:has_and_belongs_to_many, name.to_sym, **options) unless model.reflect_on_association(name)
association = model.reflect_on_association(name)
Class.new(HasAndBelongsToManyModel) do
setup association: association
end
end
alias_method :habtm, :has_and_belongs_to_many
end
end
end
| 27.152174 | 110 | 0.627702 |
6a3338989551f733d13cdbb8d58f4d9b928f9e09 | 9,864 | # frozen_string_literal: true
require 'spec_helper'
describe ProjectFeature do
using RSpec::Parameterized::TableSyntax
let(:project) { create(:project) }
let(:user) { create(:user) }
describe 'PRIVATE_FEATURES_MIN_ACCESS_LEVEL_FOR_PRIVATE_PROJECT' do
it 'has higher level than that of PRIVATE_FEATURES_MIN_ACCESS_LEVEL' do
described_class::PRIVATE_FEATURES_MIN_ACCESS_LEVEL_FOR_PRIVATE_PROJECT.each do |feature, level|
if generic_level = described_class::PRIVATE_FEATURES_MIN_ACCESS_LEVEL[feature]
expect(level).to be >= generic_level
end
end
end
end
describe '.quoted_access_level_column' do
it 'returns the table name and quoted column name for a feature' do
expected = '"project_features"."issues_access_level"'
expect(described_class.quoted_access_level_column(:issues)).to eq(expected)
end
end
describe '#feature_available?' do
let(:features) { %w(issues wiki builds merge_requests snippets repository pages) }
context 'when features are disabled' do
it "returns false" do
features.each do |feature|
project.project_feature.update_attribute("#{feature}_access_level".to_sym, ProjectFeature::DISABLED)
expect(project.feature_available?(:issues, user)).to eq(false)
end
end
end
context 'when features are enabled only for team members' do
it "returns false when user is not a team member" do
features.each do |feature|
project.project_feature.update_attribute("#{feature}_access_level".to_sym, ProjectFeature::PRIVATE)
expect(project.feature_available?(:issues, user)).to eq(false)
end
end
it "returns true when user is a team member" do
project.add_developer(user)
features.each do |feature|
project.project_feature.update_attribute("#{feature}_access_level".to_sym, ProjectFeature::PRIVATE)
expect(project.feature_available?(:issues, user)).to eq(true)
end
end
it "returns true when user is a member of project group" do
group = create(:group)
project = create(:project, namespace: group)
group.add_developer(user)
features.each do |feature|
project.project_feature.update_attribute("#{feature}_access_level".to_sym, ProjectFeature::PRIVATE)
expect(project.feature_available?(:issues, user)).to eq(true)
end
end
it "returns true if user is an admin" do
user.update_attribute(:admin, true)
features.each do |feature|
project.project_feature.update_attribute("#{feature}_access_level".to_sym, ProjectFeature::PRIVATE)
expect(project.feature_available?(:issues, user)).to eq(true)
end
end
end
context 'when feature is enabled for everyone' do
it "returns true" do
features.each do |feature|
expect(project.feature_available?(:issues, user)).to eq(true)
end
end
end
context 'when feature is disabled by a feature flag' do
it 'returns false' do
stub_feature_flags(issues: false)
expect(project.feature_available?(:issues, user)).to eq(false)
end
end
context 'when feature is enabled by a feature flag' do
it 'returns true' do
stub_feature_flags(issues: true)
expect(project.feature_available?(:issues, user)).to eq(true)
end
end
end
context 'repository related features' do
before do
project.project_feature.update(
merge_requests_access_level: ProjectFeature::DISABLED,
builds_access_level: ProjectFeature::DISABLED,
repository_access_level: ProjectFeature::PRIVATE
)
end
it "does not allow repository related features have higher level" do
features = %w(builds merge_requests)
project_feature = project.project_feature
features.each do |feature|
field = "#{feature}_access_level".to_sym
project_feature.update_attribute(field, ProjectFeature::ENABLED)
expect(project_feature.valid?).to be_falsy
end
end
end
context 'public features' do
features = %w(issues wiki builds merge_requests snippets repository)
features.each do |feature|
it "does not allow public access level for #{feature}" do
project_feature = project.project_feature
field = "#{feature}_access_level".to_sym
project_feature.update_attribute(field, ProjectFeature::PUBLIC)
expect(project_feature.valid?).to be_falsy
end
end
end
describe '#*_enabled?' do
let(:features) { %w(wiki builds merge_requests) }
it "returns false when feature is disabled" do
features.each do |feature|
project.project_feature.update_attribute("#{feature}_access_level".to_sym, ProjectFeature::DISABLED)
expect(project.public_send("#{feature}_enabled?")).to eq(false)
end
end
it "returns true when feature is enabled only for team members" do
features.each do |feature|
project.project_feature.update_attribute("#{feature}_access_level".to_sym, ProjectFeature::PRIVATE)
expect(project.public_send("#{feature}_enabled?")).to eq(true)
end
end
it "returns true when feature is enabled for everyone" do
features.each do |feature|
expect(project.public_send("#{feature}_enabled?")).to eq(true)
end
end
end
describe 'default pages access level' do
subject { project_feature.pages_access_level }
let(:project_feature) do
# project factory overrides all values in project_feature after creation
project.project_feature.destroy!
project.build_project_feature.save!
project.project_feature
end
context 'when new project is private' do
let(:project) { create(:project, :private) }
it { is_expected.to eq(ProjectFeature::PRIVATE) }
end
context 'when new project is internal' do
let(:project) { create(:project, :internal) }
it { is_expected.to eq(ProjectFeature::PRIVATE) }
end
context 'when new project is public' do
let(:project) { create(:project, :public) }
it { is_expected.to eq(ProjectFeature::ENABLED) }
context 'when access control is forced on the admin level' do
before do
allow(::Gitlab::Pages).to receive(:access_control_is_forced?).and_return(true)
end
it { is_expected.to eq(ProjectFeature::PRIVATE) }
end
end
end
describe '#public_pages?' do
it 'returns true if Pages access controll is not enabled' do
stub_config(pages: { access_control: false })
project_feature = described_class.new(pages_access_level: described_class::PRIVATE)
expect(project_feature.public_pages?).to eq(true)
end
context 'when Pages access control is enabled' do
before do
stub_config(pages: { access_control: true })
end
where(:project_visibility, :pages_access_level, :result) do
:private | ProjectFeature::PUBLIC | true
:internal | ProjectFeature::PUBLIC | true
:internal | ProjectFeature::ENABLED | false
:public | ProjectFeature::ENABLED | true
:private | ProjectFeature::PRIVATE | false
:public | ProjectFeature::PRIVATE | false
end
with_them do
let(:project_feature) do
project = build(:project, project_visibility)
project_feature = project.project_feature
project_feature.update!(pages_access_level: pages_access_level)
project_feature
end
it 'properly handles project and Pages visibility settings' do
expect(project_feature.public_pages?).to eq(result)
end
it 'returns false if access_control is forced on the admin level' do
stub_application_setting(force_pages_access_control: true)
expect(project_feature.public_pages?).to eq(false)
end
end
end
end
describe '#private_pages?' do
subject(:project_feature) { described_class.new }
it 'returns false if public_pages? is true' do
expect(project_feature).to receive(:public_pages?).and_return(true)
expect(project_feature.private_pages?).to eq(false)
end
it 'returns true if public_pages? is false' do
expect(project_feature).to receive(:public_pages?).and_return(false)
expect(project_feature.private_pages?).to eq(true)
end
end
describe '.required_minimum_access_level' do
it 'handles reporter level' do
expect(described_class.required_minimum_access_level(:merge_requests)).to eq(Gitlab::Access::REPORTER)
end
it 'handles guest level' do
expect(described_class.required_minimum_access_level(:issues)).to eq(Gitlab::Access::GUEST)
end
it 'accepts ActiveModel' do
expect(described_class.required_minimum_access_level(MergeRequest)).to eq(Gitlab::Access::REPORTER)
end
it 'accepts string' do
expect(described_class.required_minimum_access_level('merge_requests')).to eq(Gitlab::Access::REPORTER)
end
it 'handles repository' do
expect(described_class.required_minimum_access_level(:repository)).to eq(Gitlab::Access::GUEST)
end
it 'raises error if feature is invalid' do
expect do
described_class.required_minimum_access_level(:foos)
end.to raise_error
end
end
describe '.required_minimum_access_level_for_private_project' do
it 'returns higher permission for repository' do
expect(described_class.required_minimum_access_level_for_private_project(:repository)).to eq(Gitlab::Access::REPORTER)
end
it 'returns normal permission for issues' do
expect(described_class.required_minimum_access_level_for_private_project(:issues)).to eq(Gitlab::Access::GUEST)
end
end
end
| 33.100671 | 124 | 0.69262 |
ff8956d8e487bd1072c452f42da60037f1cedded | 28,104 | module Import
module Helpers
module Colorectal
module Providers
module R0a
# Processing methods used by ManchesterHandlerColorectal
module R0aHelper
include Import::Helpers::Colorectal::Providers::R0a::R0aConstants
def split_multiplegenes_nondosage_map(_non_dosage_map)
@non_dosage_record_map[:exon].each.with_index do |exon, index|
if exon.scan(COLORECTAL_GENES_REGEX).size > 1
@non_dosage_record_map[:exon][index] =
@non_dosage_record_map[:exon][index].scan(COLORECTAL_GENES_REGEX)
@non_dosage_record_map[:genotype][index] =
if @non_dosage_record_map[:genotype][index] == 'MLH1 Normal, MSH2 Normal, MSH6 Normal'
@non_dosage_record_map[:genotype][index] = ['NGS Normal'] * 3
@non_dosage_record_map[:genotype][index] =
@non_dosage_record_map[:genotype][index].flatten
elsif @non_dosage_record_map[:genotype][index].scan(/Normal, /i).size.positive?
@non_dosage_record_map[:genotype][index] =
@non_dosage_record_map[:genotype][index].split(',').map do |genotypes|
genotypes.gsub(/.+Normal/, 'Normal')
end
@non_dosage_record_map[:genotype][index] =
@non_dosage_record_map[:genotype][index].flatten
elsif @non_dosage_record_map[:genotype][index] == 'Normal'
@non_dosage_record_map[:genotype][index] =
['Normal'] * exon.scan(COLORECTAL_GENES_REGEX).size
@non_dosage_record_map[:genotype][index] =
@non_dosage_record_map[:genotype][index].flatten
elsif @non_dosage_record_map[:genotype][index].scan(/MSH2/) &&
@non_dosage_record_map[:genotype][index].scan(/MLH1/).empty? &&
@non_dosage_record_map[:genotype][index].scan(/MSH6/).empty?
@non_dosage_record_map[:genotype][index] =
[@non_dosage_record_map[:genotype][index]].unshift(['Normal'])
@non_dosage_record_map[:genotype][index] =
@non_dosage_record_map[:genotype][index].flatten
elsif @non_dosage_record_map[:genotype][index].scan(/MLH1/) &&
@non_dosage_record_map[:genotype][index].scan(/MSH2/).empty? &&
@non_dosage_record_map[:genotype][index].scan(/MSH6/).empty?
@non_dosage_record_map[:genotype][index] =
[@non_dosage_record_map[:genotype][index]].push(['Normal'])
@non_dosage_record_map[:genotype][index] =
@non_dosage_record_map[:genotype][index].flatten
elsif @non_dosage_record_map[:genotype][index].scan(/MSH2/) &&
@non_dosage_record_map[:genotype][index].scan(/MLH1/) &&
@non_dosage_record_map[:genotype][index].scan(/MSH6/).empty?
@non_dosage_record_map[:genotype][index] =
@non_dosage_record_map[:genotype][index].split(',').map(&:lstrip)
else @non_dosage_record_map[:genotype][index] =
@non_dosage_record_map[:genotype][index]
end
@non_dosage_record_map[:genotype2][index] =
if !@non_dosage_record_map[:genotype2][index].nil? &&
@non_dosage_record_map[:genotype2][index].scan(/100% coverage at 100X/).size.positive?
@non_dosage_record_map[:genotype2][index] = ['NGS Normal'] * 3
@non_dosage_record_map[:genotype2][index] =
@non_dosage_record_map[:genotype2][index].flatten
elsif !@non_dosage_record_map[:genotype2][index].nil? &&
@non_dosage_record_map[:genotype2][index].empty?
@non_dosage_record_map[:genotype2][index] = ['MLPA Normal'] * 2
@non_dosage_record_map[:genotype2][index] =
@non_dosage_record_map[:genotype2][index].flatten
elsif @non_dosage_record_map[:genotype2][index].nil? &&
@non_dosage_record_map[:genotype][index].is_a?(String) &&
@non_dosage_record_map[:genotype][index].scan(/MSH2/).size.positive?
@non_dosage_record_map[:genotype2][index] =
[''] * exon.scan(COLORECTAL_GENES_REGEX).size
@non_dosage_record_map[:genotype2][index] =
@non_dosage_record_map[:genotype2][index].flatten
end
end
end
@non_dosage_record_map[:exon] = @non_dosage_record_map[:exon].flatten
@non_dosage_record_map[:genotype] = @non_dosage_record_map[:genotype].flatten
@non_dosage_record_map[:genotype2] = @non_dosage_record_map[:genotype2].flatten
end
def split_multiplegenes_dosage_map(_dosage_map)
@dosage_record_map[:exon].each.with_index do |exon, index|
if exon.scan(COLORECTAL_GENES_REGEX).size > 1
@dosage_record_map[:exon][index] =
@dosage_record_map[:exon][index].scan(COLORECTAL_GENES_REGEX).flatten.each do |gene|
gene.concat('_MLPA')
end
@dosage_record_map[:genotype][index] =
if @dosage_record_map[:genotype][index] == 'Normal'
@dosage_record_map[:genotype][index] =
['Normal'] * exon.scan(COLORECTAL_GENES_REGEX).size
@dosage_record_map[:genotype][index] =
@dosage_record_map[:genotype][index].flatten
elsif @dosage_record_map[:genotype][index].scan(/MSH2/) &&
@dosage_record_map[:genotype][index].scan(/MLH1/).empty?
@dosage_record_map[:genotype][index] =
[@dosage_record_map[:genotype][index]].unshift(['Normal'])
@dosage_record_map[:genotype][index] =
@dosage_record_map[:genotype][index].flatten
elsif @dosage_record_map[:genotype][index].scan(/MLH1/) &&
@dosage_record_map[:genotype][index].scan(/MSH2/).empty?
@dosage_record_map[:genotype][index] =
[@dosage_record_map[:genotype][index]].push(['Normal'])
@dosage_record_map[:genotype][index] =
@dosage_record_map[:genotype][index].flatten
elsif @dosage_record_map[:genotype][index] == 'MLH1 Normal, MSH2 Normal, MSH6 Normal'
@dosage_record_map[:genotype][index] = ['NGS Normal'] * 3
@dosage_record_map[:genotype][index] =
@dosage_record_map[:genotype][index].flatten
end
@dosage_record_map[:genotype2][index] =
if !@dosage_record_map[:genotype2][index].nil? &&
@dosage_record_map[:genotype2][index].empty?
@dosage_record_map[:genotype2][index] = ['MLPA Normal'] * 2
@dosage_record_map[:genotype2][index] =
@dosage_record_map[:genotype2][index].flatten
elsif !@dosage_record_map[:genotype2][index].nil? &&
@dosage_record_map[:genotype2][index].scan(/100% coverage at 100X/).size.positive?
@dosage_record_map[:genotype2][index] = ['NGS Normal'] * 3
@dosage_record_map[:genotype2][index] =
@dosage_record_map[:genotype2][index].flatten
end
end
end
@dosage_record_map[:exon] = @dosage_record_map[:exon].flatten
@dosage_record_map[:genotype] = @dosage_record_map[:genotype].flatten
@dosage_record_map[:genotype2] = @dosage_record_map[:genotype2].flatten
end
def assign_and_populate_results_for(record)
genocolorectal = Import::Colorectal::Core::Genocolorectal.new(record)
genocolorectal.add_passthrough_fields(record.mapped_fields,
record.raw_fields,
PASS_THROUGH_FIELDS_COLO)
add_organisationcode_testresult(genocolorectal)
add_servicereportidentifier(genocolorectal, record)
testscope_from_rawfields(genocolorectal, record)
results = assign_gene_mutation(genocolorectal, record)
results.each { |genotype| @persister.integrate_and_store(genotype) }
end
def add_organisationcode_testresult(genocolorectal)
genocolorectal.attribute_map['organisationcode_testresult'] = '69820'
end
def assign_gene_mutation(genocolorectal, _record)
genotypes = []
genes = []
if non_dosage_test?
process_non_dosage_test_exons(genes)
tests = tests_from_non_dosage_record(genes)
grouped_tests = grouped_tests_from(tests)
process_grouped_non_dosage_tests(grouped_tests, genocolorectal, genotypes)
elsif dosage_test?
process_dosage_test_exons(genes)
tests = tests_from_dosage_record(genes)
grouped_tests = grouped_tests_from(tests)
process_grouped_dosage_tests(grouped_tests, genocolorectal, genotypes)
end
genotypes
end
def testscope_from_rawfields(genocolorectal, record)
moltesttypes = []
genera = []
exons = []
record.raw_fields.map do |raw_record|
moltesttypes.append(raw_record['moleculartestingtype'])
genera.append(raw_record['genus'])
exons.append(raw_record['exon'])
end
add_test_scope_to(genocolorectal, moltesttypes, genera, exons)
end
# TODO: Boyscout
def add_test_scope_to(genocolorectal, moltesttypes, genera, exons)
stringed_moltesttypes = moltesttypes.flatten.join(',')
stringed_exons = exons.flatten.join(',')
if stringed_moltesttypes =~ /predictive|confirm/i
genocolorectal.add_test_scope(:targeted_mutation)
elsif genera.include?('G') || genera.include?('F')
genocolorectal.add_test_scope(:full_screen)
elsif (screen?(stringed_moltesttypes) || mlh1_msh2_6_test?(moltesttypes)) &&
twelve_tests_or_more?(moltesttypes)
genocolorectal.add_test_scope(:full_screen)
elsif (screen?(stringed_moltesttypes) || mlh1_msh2_6_test?(moltesttypes)) &&
!twelve_tests_or_more?(moltesttypes) && ngs?(stringed_exons)
genocolorectal.add_test_scope(:full_screen)
elsif (screen?(stringed_moltesttypes) || mlh1_msh2_6_test?(moltesttypes)) &&
!twelve_tests_or_more?(moltesttypes) && !ngs?(stringed_exons)
genocolorectal.add_test_scope(:targeted_mutation)
elsif moltesttypes.include?('VARIANT TESTING REPORT')
genocolorectal.add_test_scope(:targeted_mutation)
elsif stringed_moltesttypes =~ /dosage/i
genocolorectal.add_test_scope(:full_screen)
elsif moltesttypes.include?('HNPCC MSH2 c.942+3A>T MUTATION TESTING REPORT')
genocolorectal.add_test_scope(:full_screen)
end
end
def process_grouped_non_dosage_tests(grouped_tests, genocolorectal, genotypes)
selected_genes = (@non_dosage_record_map[:moleculartestingtype].uniq &
MOLTEST_MAP.keys).join
return @logger.debug('Nothing to do') if selected_genes.to_s.blank?
grouped_tests.each do |gene, genetic_info|
next unless MOLTEST_MAP[selected_genes].include? gene
if cdna_match?(genetic_info)
process_non_dosage_cdna(gene, genetic_info, genocolorectal, genotypes)
elsif genetic_info.join(',').match(EXON_LOCATION_REGEX) &&
exon_match?(genetic_info)
process_colorectal_gene_and_exon_match(genocolorectal, genetic_info, genotypes)
elsif !cdna_match?(genetic_info) &&
!exon_match?(genetic_info) &&
normal?(genetic_info)
process_non_cdna_normal(gene, genetic_info, genocolorectal, genotypes)
elsif !cdna_match?(genetic_info) &&
!exon_match?(genetic_info) &&
!normal?(genetic_info) &&
fail?(genetic_info)
process_non_cdna_fail(gene, genetic_info, genocolorectal, genotypes)
# else binding.pry
end
end
end
def process_non_dosage_cdna(gene, genetic_info, genocolorectal, genotypes)
genocolorectal_dup = genocolorectal.dup_colo
colorectal_genes = colorectal_genes_from(genetic_info)
if colorectal_genes
process_colorectal_genes(colorectal_genes, genocolorectal_dup, gene, genetic_info,
genotypes)
else
process_non_colorectal_genes(genocolorectal_dup, gene, genetic_info, genotypes,
genocolorectal)
end
end
def process_non_cdna_normal(gene, genetic_info, genocolorectal, genotypes)
genocolorectal_dup = genocolorectal.dup_colo
@logger.debug("IDENTIFIED #{gene}, NORMAL TEST from #{genetic_info}")
add_gene_and_status_to(genocolorectal_dup, gene, 1, genotypes)
end
def process_non_cdna_fail(gene, genetic_info, genocolorectal, genotypes)
genocolorectal_dup = genocolorectal.dup_colo
add_gene_and_status_to(genocolorectal_dup, gene, 9, genotypes)
@logger.debug("Adding #{gene} to FAIL STATUS for #{genetic_info}")
end
def process_false_positive(colorectal_genes, gene, genetic_info)
@logger.debug("IDENTIFIED FALSE POSITIVE FOR #{gene}, " \
"#{colorectal_genes[:colorectal]}, #{cdna_from(genetic_info)} " \
"from #{genetic_info}")
end
def process_colorectal_genes(colorectal_genes, genocolorectal_dup, gene, genetic_info,
genotypes)
if colorectal_genes[:colorectal] != gene
process_false_positive(colorectal_genes, gene, genetic_info)
process_non_cdna_normal(gene, genetic_info, genocolorectal_dup, genotypes)
elsif colorectal_genes[:colorectal] == gene
@logger.debug("IDENTIFIED TRUE POSITIVE FOR #{gene}, " \
"#{cdna_from(genetic_info)} from #{genetic_info}")
genocolorectal_dup.add_gene_location(cdna_from(genetic_info))
if PROT_REGEX.match(genetic_info.join(','))
@logger.debug("IDENTIFIED #{protien_from(genetic_info)} from #{genetic_info}")
genocolorectal_dup.add_protein_impact(protien_from(genetic_info))
end
add_gene_and_status_to(genocolorectal_dup, gene, 2, genotypes)
@logger.debug("IDENTIFIED #{gene}, POSITIVE TEST from #{genetic_info}")
end
end
def process_non_colorectal_genes(genocolorectal_dup, gene, genetic_info, genotypes,
genocolorectal)
@logger.debug("IDENTIFIED #{gene}, #{cdna_from(genetic_info)} from #{genetic_info}")
mutations = genetic_info.join(',').scan(CDNA_REGEX).flatten.compact.map do |s|
s.gsub(/\s+/, '')
end.uniq
if mutations.size > 1
if mutations.size == 2
mutation_duplicate1 = mutations[0]
mutation_duplicate2 = mutations[1]
longest_mutation = mutations.max_by(&:length)
if mutation_duplicate1.include?(mutation_duplicate2) || mutation_duplicate2.include?(mutation_duplicate1)
# Possibly refactor this
genetic_info.each.with_index do |info, index|
if info.match(longest_mutation)
duplicated_geno = genocolorectal.dup_colo
duplicated_geno.add_gene_colorectal(gene)
duplicated_geno.add_gene_location(CDNA_REGEX.match(genetic_info[index])[:cdna])
if PROT_REGEX.match(genetic_info[index])
duplicated_geno.add_protein_impact(PROT_REGEX.match(genetic_info[index])[:impact])
end
duplicated_geno.add_status(2)
genotypes.append(duplicated_geno)
end
end
# Possibly refactor this
elsif mutations.size > 1 && genetic_info.join(',').scan(PROT_REGEX).blank?
mutations.each do |mutation|
duplicated_geno = genocolorectal.dup_colo
duplicated_geno.add_gene_colorectal(gene)
duplicated_geno.add_gene_location(mutation)
duplicated_geno.add_status(2)
genotypes.append(duplicated_geno)
end
# Possibly refactor this
elsif mutations.size > 1 && genetic_info.join(',').scan(PROT_REGEX).size.positive?
variants = mutations.zip(genetic_info.join(',').scan(PROT_REGEX).flatten)
variants.each do |cdna, protein|
duplicated_geno = genocolorectal.dup_colo
duplicated_geno.add_gene_colorectal(gene)
duplicated_geno.add_gene_location(cdna)
duplicated_geno.add_protein_impact(protein)
duplicated_geno.add_status(2)
genotypes.append(duplicated_geno)
end
end
genotypes
end
elsif mutations.size == 1
genocolorectal_dup.add_gene_location(cdna_from(genetic_info))
genocolorectal_dup.add_gene_colorectal(gene)
genocolorectal_dup.add_status(2)
genotypes.append(genocolorectal_dup)
if PROT_REGEX.match(genetic_info.join(','))
@logger.debug("IDENTIFIED #{protien_from(genetic_info)} from #{genetic_info}")
genocolorectal_dup.add_protein_impact(protien_from(genetic_info))
end
genotypes
end
# add_gene_and_status_to(genocolorectal_dup, gene, 2, genotypes)
@logger.debug("IDENTIFIED #{gene}, POSITIVE TEST from #{genetic_info}")
end
# TODO: Boyscout
def process_grouped_dosage_tests(grouped_tests, genocolorectal, genotypes)
selected_genes = (@dosage_record_map[:moleculartestingtype].uniq &
MOLTEST_MAP_DOSAGE.keys).join
return @logger.debug('Nothing to do') if selected_genes.to_s.blank?
grouped_tests.compact.select do |gene, genetic_info|
dosage_genes = MOLTEST_MAP_DOSAGE[selected_genes]
if dosage_genes.include? gene
process_dosage_gene(gene, genetic_info, genocolorectal, genotypes, dosage_genes)
else
@logger.debug("Nothing to be done for #{gene} as it is not in #{selected_genes}")
end
end
end
def process_dosage_gene(gene, genetic_info, genocolorectal, genotypes, dosage_genes)
if !colorectal_gene_match?(genetic_info)
genocolorectal_dup = genocolorectal.dup_colo
add_gene_and_status_to(genocolorectal_dup, gene, 1, genotypes)
@logger.debug("IDENTIFIED #{gene} from #{dosage_genes}, " \
"NORMAL TEST from #{genetic_info}")
elsif colorectal_gene_match?(genetic_info) && !exon_match?(genetic_info)
genocolorectal_dup = genocolorectal.dup_colo
add_gene_and_status_to(genocolorectal_dup, gene, 1, genotypes)
@logger.debug("IDENTIFIED #{gene} from #{dosage_genes}, " \
"NORMAL TEST from #{genetic_info}")
elsif colorectal_gene_match?(genetic_info) && exon_match?(genetic_info)
process_colorectal_gene_and_exon_match(genocolorectal, genetic_info, genotypes)
end
end
def process_colorectal_gene_and_exon_match(genocolorectal, genetic_info, genotypes)
genocolorectal_dup = genocolorectal.dup_colo
colorectal_gene = colorectal_genes_from(genetic_info)[:colorectal] unless
[nil, 0].include?(colorectal_genes_from(genetic_info))
genocolorectal_dup.add_gene_colorectal(colorectal_gene)
genocolorectal_dup.add_variant_type(exon_from(genetic_info))
if EXON_LOCATION_REGEX.match(genetic_info.join(','))
exon_locations = exon_locations_from(genetic_info)
if exon_locations.one?
genocolorectal_dup.add_exon_location(exon_locations.flatten.first)
elsif exon_locations.size == 2
genocolorectal_dup.add_exon_location(exon_locations.flatten.compact.join('-'))
end
end
genocolorectal_dup.add_status(2)
genotypes.append(genocolorectal_dup)
@logger.debug("IDENTIFIED #{colorectal_gene} for exonic variant " \
"#{EXON_REGEX.match(genetic_info.join(','))} from #{genetic_info}")
end
def add_servicereportidentifier(genocolorectal, record)
servicereportidentifiers = []
record.raw_fields.each do |records|
servicereportidentifiers << records['servicereportidentifier']
end
servicereportidentifier = servicereportidentifiers.flatten.uniq.join
genocolorectal.attribute_map['servicereportidentifier'] = servicereportidentifier
end
def add_gene_and_status_to(genocolorectal_dup, gene, status, genotypes)
genocolorectal_dup.add_gene_colorectal(gene)
genocolorectal_dup.add_status(status)
genotypes.append(genocolorectal_dup)
end
def grouped_tests_from(tests)
grouped_tests = Hash.new { |h, k| h[k] = [] }
tests.each do |test_array|
gene = test_array.first
test_array[1..].each { |test_value| grouped_tests[gene] << test_value }
end
grouped_tests.transform_values!(&:uniq)
end
def tests_from_non_dosage_record(genes)
return if genes.nil?
genes.zip(@non_dosage_record_map[:genotype],
@non_dosage_record_map[:genotype2]).uniq
end
def tests_from_dosage_record(genes)
return if genes.nil?
genes.zip(@dosage_record_map[:genotype],
@dosage_record_map[:genotype2],
@dosage_record_map[:moleculartestingtype]).uniq
end
def process_non_dosage_test_exons(genes)
@non_dosage_record_map[:exon].each do |exons|
if exons =~ COLORECTAL_GENES_REGEX
genes.append(COLORECTAL_GENES_REGEX.match(exons)[:colorectal])
else
genes.append('No Gene')
end
end
end
def process_dosage_test_exons(genes)
@dosage_record_map[:exon].map do |exons|
if exons.scan(COLORECTAL_GENES_REGEX).count.positive? && mlpa?(exons)
exons.scan(COLORECTAL_GENES_REGEX).flatten.each { |gene| genes.append(gene) }
else
genes.append('No Gene')
end
end
end
def relevant_consultant?(raw_record)
raw_record['consultantname'].to_s.upcase != 'DR SANDI DEANS'
end
def mlh1_msh2_6_test?(moltesttypes)
moltesttypes.include?('MLH1/MSH2/MSH6 GENETIC TESTING REPORT')
end
def ngs?(exons)
exons =~ /ngs/i.freeze
end
def screen?(moltesttypes)
moltesttypes =~ /screen/i.freeze
end
def control_sample?(raw_record)
raw_record['genocomm'] =~ /control|ctrl/i
end
def twelve_tests_or_more?(moltesttypes)
moltesttypes.size >= 12
end
def non_dosage_test?
(MOLTEST_MAP.keys & @non_dosage_record_map[:moleculartestingtype].uniq).size == 1
end
def dosage_test?
(MOLTEST_MAP_DOSAGE.keys & @dosage_record_map[:moleculartestingtype].uniq).size == 1
end
def colorectal_gene_match?(genetic_info)
genetic_info.join(',') =~ COLORECTAL_GENES_REGEX
end
def cdna_match?(genetic_info)
genetic_info.join(',') =~ CDNA_REGEX
end
def exon_match?(genetic_info)
genetic_info.join(',') =~ EXON_REGEX
end
def normal?(genetic_info)
genetic_info.join(',') =~ /normal|wild type|No pathogenic variant identified|No evidence/i
end
def fail?(genetic_info)
genetic_info.join(',') =~ /fail/i
end
def mlpa?(exon)
exon =~ /mlpa|P003/i
end
def cdna_from(genetic_info)
CDNA_REGEX.match(genetic_info.join(','))[:cdna]
end
def exon_from(genetic_info)
EXON_REGEX.match(genetic_info.join(','))[:insdeldup]
end
def exon_locations_from(genetic_info)
genetic_info.join(',').scan(EXON_LOCATION_REGEX)
end
def protien_from(genetic_info)
PROT_REGEX.match(genetic_info.join(','))[:impact]
end
def colorectal_genes_from(genetic_info)
COLORECTAL_GENES_REGEX.match(genetic_info.join(','))
end
def process_genocolorectal(genocolorectal_dup, gene, status, logging, genotypes)
@logger.debug(logging)
genocolorectal_dup.add_gene_colorectal(gene)
genocolorectal_dup.add_status(status)
genotypes.append(genocolorectal_dup)
end
def normal_test_logging_for(selected_genes, gene, genetic_info)
"IDENTIFIED #{gene} from #{MOLTEST_MAP_DOSAGE[selected_genes]}, " \
"NORMAL TEST from #{genetic_info}"
end
end
end
end
end
end
end
| 51.566972 | 123 | 0.568353 |
26567d9f8756ddfc24bbca8e6f1594e7a7b40dbe | 1,094 | # frozen_string_literal: true
module Polaris
class IconComponent < Polaris::NewComponent
COLOR_DEFAULT = :default
COLOR_MAPPINGS = {
COLOR_DEFAULT => "",
:base => "Polaris-Icon--colorBase",
:subdued => "Polaris-Icon--colorSubdued",
:critical => "Polaris-Icon--colorCritical",
:warning => "Polaris-Icon--colorWarning",
:highlight => "Polaris-Icon--colorHighlight",
:success => "Polaris-Icon--colorSuccess",
:primary => "Polaris-Icon--colorPrimary",
}
COLOR_OPTIONS = COLOR_MAPPINGS.keys
def initialize(
name: nil,
backdrop: false,
color: COLOR_DEFAULT,
**system_arguments
)
@source = name ? polaris_icon_source(name) : nil
@system_arguments = system_arguments
@system_arguments[:classes] = class_names(
@system_arguments[:classes],
"Polaris-Icon",
COLOR_MAPPINGS[fetch_or_fallback(COLOR_OPTIONS, color, COLOR_DEFAULT)],
"Polaris-Icon--hasBackdrop" => backdrop,
"Polaris-Icon--applyColor" => color != :default,
)
end
end
end
| 29.567568 | 79 | 0.639854 |
1cd654efe611452d74816b7517290b2b611b7ed2 | 1,717 | require 'test_helper'
describe Cask::CLI do
it "supports setting the appdir" do
Cask::CLI.process_options %w{help --appdir=/some/path/foo}
Cask.appdir.must_equal Pathname('/some/path/foo')
end
it "supports setting the appdir from ENV" do
ENV['HOMEBREW_CASK_OPTS'] = "--appdir=/some/path/bar"
Cask::CLI.process_options %w{help}
Cask.appdir.must_equal Pathname('/some/path/bar')
end
it "supports setting the prefpanedir" do
Cask::CLI.process_options %w{help --prefpanedir=/some/path/foo}
Cask.prefpanedir.must_equal Pathname('/some/path/foo')
end
it "supports setting the prefpanedir from ENV" do
ENV['HOMEBREW_CASK_OPTS'] = "--prefpanedir=/some/path/bar"
Cask::CLI.process_options %w{help}
Cask.prefpanedir.must_equal Pathname('/some/path/bar')
end
it "supports setting the qlplugindir" do
Cask::CLI.process_options %w{help --qlplugindir=/some/path/foo}
Cask.qlplugindir.must_equal Pathname('/some/path/foo')
end
it "supports setting the qlplugindir from ENV" do
ENV['HOMEBREW_CASK_OPTS'] = "--qlplugindir=/some/path/bar"
Cask::CLI.process_options %w{help}
Cask.qlplugindir.must_equal Pathname('/some/path/bar')
end
it "allows additional options to be passed through" do
rest = Cask::CLI.process_options %w{edit foo --create --appdir=/some/path/qux}
Cask.appdir.must_equal Pathname('/some/path/qux')
rest.must_equal %w{edit foo --create}
end
describe "--debug" do
it "sets the CLI's debug variable to true" do
Cask::CLI.process_options %w{help --debug}
Cask::CLI.instance_variable_get(:@debug).must_equal true
end
end
after do
ENV['HOMEBREW_CASK_OPTS'] = nil
end
end
| 26.828125 | 82 | 0.701805 |
181a93e9eac1af729a3ddbd1a8a141fdba713f5f | 44,140 | # This module provides an interface to the vips image processing library
# via ruby-ffi.
#
# Author:: John Cupitt (mailto:[email protected])
# License:: MIT
require 'ffi'
module Vips
private
attach_function :vips_image_new_matrix_from_array,
[:int, :int, :pointer, :int], :pointer
attach_function :vips_image_copy_memory, [:pointer], :pointer
attach_function :vips_image_set_progress, [:pointer, :bool], :void
attach_function :vips_image_set_kill, [:pointer, :bool], :void
attach_function :vips_filename_get_filename, [:string], :pointer
attach_function :vips_filename_get_options, [:string], :pointer
attach_function :vips_foreign_find_load, [:string], :string
attach_function :vips_foreign_find_save, [:string], :string
attach_function :vips_foreign_find_load_buffer, [:pointer, :size_t], :string
attach_function :vips_foreign_find_save_buffer, [:string], :string
if Vips::at_least_libvips?(8, 9)
attach_function :vips_foreign_find_load_stream, [:pointer], :string
attach_function :vips_foreign_find_save_stream, [:string], :string
end
attach_function :vips_image_write_to_memory,
[:pointer, SizeStruct.ptr], :pointer
attach_function :vips_image_get_typeof, [:pointer, :string], :GType
attach_function :vips_image_get,
[:pointer, :string, GObject::GValue.ptr], :int
if Vips::at_least_libvips?(8, 5)
attach_function :vips_image_get_fields, [:pointer], :pointer
attach_function :vips_image_hasalpha, [:pointer], :int
end
if Vips::at_least_libvips?(8, 6)
attach_function :vips_addalpha, [:pointer, :pointer, :varargs], :int
end
attach_function :vips_image_set,
[:pointer, :string, GObject::GValue.ptr], :void
attach_function :vips_image_remove, [:pointer, :string], :void
attach_function :vips_band_format_iscomplex, [:int], :int
attach_function :vips_band_format_isfloat, [:int], :int
attach_function :nickname_find, :vips_nickname_find, [:GType], :string
# turn a raw pointer that must be freed into a self-freeing Ruby string
def self.p2str(pointer)
pointer = FFI::AutoPointer.new(pointer, GLib::G_FREE)
pointer.read_string
end
public
# This class represents a libvips image. See the {Vips} module documentation
# for an introduction to using this class.
class Image < Vips::Object
alias_method :parent_get_typeof, :get_typeof
private
# the layout of the VipsImage struct
module ImageLayout
def self.included base
base.class_eval do
layout :parent, Vips::Object::Struct
# rest opaque
end
end
end
class Struct < Vips::Object::Struct
include ImageLayout
end
class ManagedStruct < Vips::Object::ManagedStruct
include ImageLayout
end
class GenericPtr < FFI::Struct
layout :value, :pointer
end
# handy for overloads ... want to be able to apply a function to an
# array or to a scalar
def self.smap x, &block
x.is_a?(Array) ? x.map { |y| smap(y, &block) } : block.(x)
end
def self.complex? format
format_number = GObject::GValue.from_nick BAND_FORMAT_TYPE, format
Vips::vips_band_format_iscomplex(format_number) != 0
end
def self.float? format
format_number = GObject::GValue.from_nick BAND_FORMAT_TYPE, format
Vips::vips_band_format_isfloat(format_number) != 0
end
# run a complex operation on a complex image, or an image with an even
# number of bands ... handy for things like running .polar on .index
# images
def self.run_cmplx image, &block
original_format = image.format
unless Image::complex? image.format
if image.bands % 2 != 0
raise Vips::Error, "not an even number of bands"
end
unless Image::float? image.format
image = image.cast :float
end
new_format = image.format == :double ? :dpcomplex : :complex
image = image.copy format: new_format, bands: image.bands / 2
end
image = block.(image)
unless Image::complex? original_format
new_format = image.format == :dpcomplex ? :double : :float
image = image.copy format: new_format, bands: image.bands * 2
end
image
end
# handy for expanding enum operations
def call_enum(name, other, enum)
if other.is_a?(Vips::Image)
Vips::Operation.call name.to_s, [self, other, enum]
else
Vips::Operation.call name.to_s + "_const", [self, enum, other]
end
end
# Write can fail due to no file descriptors and memory can fill if
# large objects are not collected fairly soon. We can't try a
# write and GC and retry on fail, since the write may take a
# long time and may not be repeatable.
#
# GCing before every write would have a horrible effect on
# performance, so as a compromise we GC every @@gc_interval writes.
#
# ruby2.1 introduced a generational GC which is fast enough to be
# able to GC on every write.
@@generational_gc = RUBY_ENGINE == "ruby" && RUBY_VERSION.to_f >= 2.1
@@gc_interval = 100
@@gc_countdown = @@gc_interval
def write_gc
if @@generational_gc
GC.start full_mark: false
else
@@gc_countdown -= 1
if @@gc_countdown < 0
@@gc_countdown = @@gc_interval
GC.start
end
end
end
public
def inspect
"#<Image #{width}x#{height} #{format}, #{bands} bands, #{interpretation}>"
end
def respond_to? name, include_all = false
# To support keyword args, we need to tell Ruby that final image
# arguments cannot be hashes of keywords.
#
# https://makandracards.com/makandra/
# 36013-heads-up-ruby-implicitly-converts-a-hash-to-keyword-arguments
return false if name == :to_hash
# respond to all vips operations by nickname
return true if Vips::type_find("VipsOperation", name.to_s) != 0
super
end
def self.respond_to? name, include_all = false
# respond to all vips operations by nickname
return true if Vips::type_find("VipsOperation", name.to_s) != 0
super
end
# Invoke a vips operation with {Vips::Operation.call}, using self as
# the first input argument.
#
# @param name [String] vips operation to call
# @return result of vips operation
def method_missing name, *args, **options
Vips::Operation.call name.to_s, [self, *args], options
end
# Invoke a vips operation with {Vips::Operation.call}.
def self.method_missing name, *args, **options
Vips::Operation.call name.to_s, args, options
end
# Return a new {Image} for a file on disc. This method can load
# images in any format supported by vips. The filename can include
# load options, for example:
#
# ```
# image = Vips::Image.new_from_file "fred.jpg[shrink=2]"
# ```
#
# You can also supply options as a hash, for example:
#
# ```
# image = Vips::Image.new_from_file "fred.jpg", shrink: 2
# ```
#
# The full set of options available depend upon the load operation that
# will be executed. Try something like:
#
# ```
# $ vips jpegload
# ```
#
# at the command-line to see a summary of the available options for the
# JPEG loader.
#
# Loading is fast: only enough of the image is loaded to be able to fill
# out the header. Pixels will only be decompressed when they are needed.
#
# @!macro [new] vips.loadopts
# @param opts [Hash] set of options
# @option opts [Boolean] :disc (true) Open large images via a
# temporary disc file
# @option opts [Vips::Access] :access (:random) Access mode for file
#
# @param name [String] the filename to load from
# @macro vips.loadopts
# @return [Image] the loaded image
def self.new_from_file name, **opts
# very common, and Vips::vips_filename_get_filename will segv if we
# pass this
raise Vips::Error, "filename is nil" if name == nil
filename = Vips::p2str(Vips::vips_filename_get_filename name)
option_string = Vips::p2str(Vips::vips_filename_get_options name)
loader = Vips::vips_foreign_find_load filename
raise Vips::Error if loader == nil
Operation.call loader, [filename], opts, option_string
end
# Create a new {Image} for an image encoded, in a format such as
# JPEG, in a binary string. Load options may be passed as
# strings or appended as a hash. For example:
#
# ```
# image = Vips::Image.new_from_buffer memory_buffer, "shrink=2"
# ```
#
# or alternatively:
#
# ```
# image = Vips::Image.new_from_buffer memory_buffer, "", shrink: 2
# ```
#
# The options available depend on the file format. Try something like:
#
# ```
# $ vips jpegload_buffer
# ```
#
# at the command-line to see the available options. Not all loaders
# support load from buffer, but at least JPEG, PNG and
# TIFF images will work.
#
# Loading is fast: only enough of the image is loaded to be able to fill
# out the header. Pixels will only be decompressed when they are needed.
#
# @param data [String] the data to load from
# @param option_string [String] load options as a string
# @macro vips.loadopts
# @return [Image] the loaded image
def self.new_from_buffer data, option_string, **opts
loader = Vips::vips_foreign_find_load_buffer data, data.bytesize
raise Vips::Error if loader.nil?
Vips::Operation.call loader, [data], opts, option_string
end
# Create a new {Image} from an input stream. Load options may be passed as
# strings or appended as a hash. For example:
#
# ```
# stream = Vips::Streami.new_from_file("k2.jpg")
# image = Vips::Image.new_from_stream stream, "shrink=2"
# ```
#
# or alternatively:
#
# ```
# image = Vips::Image.new_from_stream stream, "", shrink: 2
# ```
#
# The options available depend on the file format. Try something like:
#
# ```
# $ vips jpegload_stream
# ```
#
# at the command-line to see the available options. Not all loaders
# support load from stream, but at least JPEG, PNG and
# TIFF images will work.
#
# Loading is fast: only enough data is read to be able to fill
# out the header. Pixels will only be read and decompressed when they are
# needed.
#
# @param stream [Vips::Streami] the stream to load from
# @param option_string [String] load options as a string
# @macro vips.loadopts
# @return [Image] the loaded image
def self.new_from_stream stream, option_string, **opts
loader = Vips::vips_foreign_find_load_stream stream
raise Vips::Error if loader.nil?
Vips::Operation.call loader, [stream], opts, option_string
end
def self.matrix_from_array width, height, array
ptr = FFI::MemoryPointer.new :double, array.length
ptr.write_array_of_double array
image = Vips::vips_image_new_matrix_from_array width, height,
ptr, array.length
Vips::Image.new image
end
# Create a new Image from a 1D or 2D array. A 1D array becomes an
# image with height 1. Use `scale` and `offset` to set the scale and
# offset fields in the header. These are useful for integer
# convolutions.
#
# For example:
#
# ```
# image = Vips::Image.new_from_array [1, 2, 3]
# ```
#
# or
#
# ```
# image = Vips::Image.new_from_array [
# [-1, -1, -1],
# [-1, 16, -1],
# [-1, -1, -1]], 8
# ```
#
# for a simple sharpening mask.
#
# @param array [Array] the pixel data as an array of numbers
# @param scale [Real] the convolution scale
# @param offset [Real] the convolution offset
# @return [Image] the image
def self.new_from_array array, scale = 1, offset = 0
# we accept a 1D array and assume height == 1, or a 2D array
# and check all lines are the same length
unless array.is_a? Array
raise Vips::Error, "Argument is not an array."
end
if array[0].is_a? Array
height = array.length
width = array[0].length
unless array.all? { |x| x.is_a? Array }
raise Vips::Error, "Not a 2D array."
end
unless array.all? { |x| x.length == width }
raise Vips::Error, "Array not rectangular."
end
array = array.flatten
else
height = 1
width = array.length
end
unless array.all? { |x| x.is_a? Numeric }
raise Vips::Error, "Not all array elements are Numeric."
end
image = Vips::Image.matrix_from_array width, height, array
raise Vips::Error if image == nil
# be careful to set them as double
image.set_type GObject::GDOUBLE_TYPE, 'scale', scale.to_f
image.set_type GObject::GDOUBLE_TYPE, 'offset', offset.to_f
return image
end
# A new image is created with the same width, height, format,
# interpretation, resolution and offset as self, but with every pixel
# set to the specified value.
#
# You can pass an array to make a many-band image, or a single value to
# make a one-band image.
#
# @param value [Real, Array<Real>] value to put in each pixel
# @return [Image] constant image
def new_from_image value
pixel = (Vips::Image.black(1, 1) + value).cast(format)
image = pixel.embed 0, 0, width, height, extend: :copy
image.copy interpretation: interpretation, xres: xres, yres: yres,
xoffset: xoffset, yoffset: yoffset
end
# Write this image to a file. Save options may be encoded in the
# filename or given as a hash. For example:
#
# ```
# image.write_to_file "fred.jpg[Q=90]"
# ```
#
# or equivalently:
#
# ```
# image.write_to_file "fred.jpg", Q: 90
# ```
#
# The full set of save options depend on the selected saver. Try
# something like:
#
# ```
# $ vips jpegsave
# ```
#
# to see all the available options for JPEG save.
#
# @!macro [new] vips.saveopts
# @param opts [Hash] set of options
# @option opts [Boolean] :strip (false) Strip all metadata from image
# @option opts [Array<Float>] :background (0) Background colour to
# flatten alpha against, if necessary
#
# @param name [String] filename to write to
def write_to_file name, **opts
filename = Vips::p2str(Vips::vips_filename_get_filename name)
option_string = Vips::p2str(Vips::vips_filename_get_options name)
saver = Vips::vips_foreign_find_save filename
if saver == nil
raise Vips::Error, "No known saver for '#{filename}'."
end
Vips::Operation.call saver, [self, filename], opts, option_string
write_gc
end
# Write this image to a memory buffer. Save options may be encoded in
# the format_string or given as a hash. For example:
#
# ```
# buffer = image.write_to_buffer ".jpg[Q=90]"
# ```
#
# or equivalently:
#
# ```
# image.write_to_buffer ".jpg", Q: 90
# ```
#
# The full set of save options depend on the selected saver. Try
# something like:
#
# ```
# $ vips jpegsave
# ```
#
# to see all the available options for JPEG save.
#
# @param format_string [String] save format plus options
# @macro vips.saveopts
# @return [String] the image saved in the specified format
def write_to_buffer format_string, **opts
filename = Vips::p2str(Vips::vips_filename_get_filename format_string)
option_string = Vips::p2str(Vips::vips_filename_get_options format_string)
saver = Vips::vips_foreign_find_save_buffer filename
if saver == nil
raise Vips::Error, "No known buffer saver for '#{filename}'."
end
buffer = Vips::Operation.call saver, [self], opts, option_string
raise Vips::Error if buffer == nil
write_gc
return buffer
end
# Write this image to a stream. Save options may be encoded in
# the format_string or given as a hash. For example:
#
# ```ruby
# stream = Vips::Streamo.new_to_file "k2.jpg"
# image.write_to_stream stream, ".jpg[Q=90]"
# ```
#
# or equivalently:
#
# ```ruby
# image.write_to_stream stream, ".jpg", Q: 90
# ```
#
# The full set of save options depend on the selected saver. Try
# something like:
#
# ```
# $ vips jpegsave_stream
# ```
#
# to see all the available options for JPEG save.
#
# @param stream [Vips::Streamo] the stream to write to
# @param format_string [String] save format plus string options
# @macro vips.saveopts
def write_to_stream stream, format_string, **opts
filename = Vips::p2str(Vips::vips_filename_get_filename format_string)
option_string = Vips::p2str(Vips::vips_filename_get_options format_string)
saver = Vips::vips_foreign_find_save_stream filename
if saver == nil
raise Vips::Error, "No known stream saver for '#{filename}'."
end
Vips::Operation.call saver, [self, stream], opts, option_string
write_gc
end
# Write this image to a large memory buffer.
#
# @return [String] the pixels as a huge binary string
def write_to_memory
len = Vips::SizeStruct.new
ptr = Vips::vips_image_write_to_memory self, len
raise Vips::Error if ptr == nil
# wrap up as an autopointer
ptr = FFI::AutoPointer.new(ptr, GLib::G_FREE)
ptr.get_bytes 0, len[:value]
end
# Turn progress signalling on and off.
#
# If this is on, the most-downstream image from this image will issue
# progress signals.
#
# @see Object#signal_connect
# @param state [Boolean] progress signalling state
def set_progress state
Vips::vips_image_set_progress self, state
end
# Kill computation of this time.
#
# Set true to stop computation of this image. You can call this from a
# progress handler, for example.
#
# @see Object#signal_connect
# @param kill [Boolean] stop computation
def set_kill kill
Vips::vips_image_set_kill self, kill
end
# Get the `GType` of a metadata field. The result is 0 if no such field
# exists.
#
# @see get
# @param name [String] Metadata field to fetch
# @return [Integer] GType
def get_typeof name
# on libvips before 8.5, property types must be searched first,
# since vips_image_get_typeof returned built-in enums as int
unless Vips::at_least_libvips?(8, 5)
gtype = parent_get_typeof name
return gtype if gtype != 0
end
Vips::vips_image_get_typeof self, name
end
# Get a metadata item from an image. Ruby types are constructed
# automatically from the `GValue`, if possible.
#
# For example, you can read the ICC profile from an image like this:
#
# ```
# profile = image.get "icc-profile-data"
# ```
#
# and profile will be an array containing the profile.
#
# @param name [String] Metadata field to get
# @return [Object] Value of field
def get name
# with old libvips, we must fetch properties (as opposed to
# metadata) via VipsObject
unless Vips::at_least_libvips?(8, 5)
return super if parent_get_typeof(name) != 0
end
gvalue = GObject::GValue.alloc
raise Vips::Error if Vips::vips_image_get(self, name, gvalue) != 0
result = gvalue.get
gvalue.unset
result
end
# Get the names of all fields on an image. Use this to loop over all
# image metadata.
#
# @return [[String]] array of field names
def get_fields
# vips_image_get_fields() was added in libvips 8.5
return [] unless Vips.respond_to? :vips_image_get_fields
array = Vips::vips_image_get_fields self
names = []
p = array
until (q = p.read_pointer).null?
names << q.read_string
GLib::g_free q
p += FFI::Type::POINTER.size
end
GLib::g_free array
names
end
# Create a metadata item on an image of the specifed type. Ruby types
# are automatically transformed into the matching `GType`, if possible.
#
# For example, you can use this to set an image's ICC profile:
#
# ```
# x = y.set_type Vips::BLOB_TYPE, "icc-profile-data", profile
# ```
#
# where `profile` is an ICC profile held as a binary string object.
#
# @see set
# @param gtype [Integer] GType of item
# @param name [String] Metadata field to set
# @param value [Object] Value to set
def set_type gtype, name, value
gvalue = GObject::GValue.alloc
gvalue.init gtype
gvalue.set value
Vips::vips_image_set self, name, gvalue
gvalue.unset
end
# Set the value of a metadata item on an image. The metadata item must
# already exist. Ruby types are automatically transformed into the
# matching `GValue`, if possible.
#
# For example, you can use this to set an image's ICC profile:
#
# ```
# x = y.set "icc-profile-data", profile
# ```
#
# where `profile` is an ICC profile held as a binary string object.
#
# @see set_type
# @param name [String] Metadata field to set
# @param value [Object] Value to set
def set name, value
set_type get_typeof(name), name, value
end
# Remove a metadata item from an image.
#
# @param name [String] Metadata field to remove
def remove name
Vips::vips_image_remove self, name
end
# compatibility: old name for get
def get_value name
get name
end
# compatibility: old name for set
def set_value name, value
set name, value
end
# Get image width, in pixels.
#
# @return [Integer] image width, in pixels
def width
get "width"
end
# Get image height, in pixels.
#
# @return [Integer] image height, in pixels
def height
get "height"
end
# Get number of image bands.
#
# @return [Integer] number of image bands
def bands
get "bands"
end
# Get image format.
#
# @return [Symbol] image format
def format
get "format"
end
# Get image interpretation.
#
# @return [Symbol] image interpretation
def interpretation
get "interpretation"
end
# Get image coding.
#
# @return [Symbol] image coding
def coding
get "coding"
end
# Get image filename, if any.
#
# @return [String] image filename
def filename
get "filename"
end
# Get image xoffset.
#
# @return [Integer] image xoffset
def xoffset
get "xoffset"
end
# Get image yoffset.
#
# @return [Integer] image yoffset
def yoffset
get "yoffset"
end
# Get image x resolution.
#
# @return [Float] image x resolution
def xres
get "xres"
end
# Get image y resolution.
#
# @return [Float] image y resolution
def yres
get "yres"
end
# Get scale metadata.
#
# @return [Float] image scale
def scale
return 1 if get_typeof("scale") == 0
get "scale"
end
# Get offset metadata.
#
# @return [Float] image offset
def offset
return 0 if get_typeof("offset") == 0
get "offset"
end
# Get the image size.
#
# @return [Integer, Integer] image width and height
def size
[width, height]
end
if Vips::at_least_libvips?(8, 5)
# Detect if image has an alpha channel
#
# @return [Boolean] true if image has an alpha channel.
def has_alpha?
return Vips::vips_image_hasalpha(self) != 0
end
end
# vips_addalpha was added in libvips 8.6
if Vips::at_least_libvips?(8, 6)
# Append an alpha channel to an image.
#
# @return [Image] new image
def add_alpha
ptr = GenericPtr.new
result = Vips::vips_addalpha self, ptr
raise Vips::Error if result != 0
Vips::Image.new ptr[:value]
end
end
# Copy an image to a memory area.
#
# This can be useful for reusing results, but can obviously use a lot of
# memory for large images. See {Image#tilecache} for a way of caching
# parts of an image.
#
# @return [Image] new memory image
def copy_memory
new_image = Vips::vips_image_copy_memory self
Vips::Image.new new_image
end
# Draw a point on an image.
#
# See {Image#draw_rect}.
#
# @return [Image] modified image
def draw_point ink, left, top, **opts
draw_rect ink, left, top, 1, 1, opts
end
# Add an image, constant or array.
#
# @param other [Image, Real, Array<Real>] Thing to add to self
# @return [Image] result of addition
def + other
other.is_a?(Vips::Image) ?
add(other) : linear(1, other)
end
# Subtract an image, constant or array.
#
# @param other [Image, Real, Array<Real>] Thing to subtract from self
# @return [Image] result of subtraction
def - other
other.is_a?(Vips::Image) ?
subtract(other) : linear(1, Image::smap(other) { |x| x * -1 })
end
# Multiply an image, constant or array.
#
# @param other [Image, Real, Array<Real>] Thing to multiply by self
# @return [Image] result of multiplication
def * other
other.is_a?(Vips::Image) ?
multiply(other) : linear(other, 0)
end
# Divide an image, constant or array.
#
# @param other [Image, Real, Array<Real>] Thing to divide self by
# @return [Image] result of division
def / other
other.is_a?(Vips::Image) ?
divide(other) : linear(Image::smap(other) { |x| 1.0 / x }, 0)
end
# Remainder after integer division with an image, constant or array.
#
# @param other [Image, Real, Array<Real>] self modulo this
# @return [Image] result of modulo
def % other
other.is_a?(Vips::Image) ?
remainder(other) : remainder_const(other)
end
# Raise to power of an image, constant or array.
#
# @param other [Image, Real, Array<Real>] self to the power of this
# @return [Image] result of power
def ** other
call_enum "math2", other, :pow
end
# Integer left shift with an image, constant or array.
#
# @param other [Image, Real, Array<Real>] shift left by this much
# @return [Image] result of left shift
def << other
call_enum "boolean", other, :lshift
end
# Integer right shift with an image, constant or array.
#
# @param other [Image, Real, Array<Real>] shift right by this much
# @return [Image] result of right shift
def >> other
call_enum "boolean", other, :rshift
end
# Integer bitwise OR with an image, constant or array.
#
# @param other [Image, Real, Array<Real>] bitwise OR with this
# @return [Image] result of bitwise OR
def | other
call_enum "boolean", other, :or
end
# Integer bitwise AND with an image, constant or array.
#
# @param other [Image, Real, Array<Real>] bitwise AND with this
# @return [Image] result of bitwise AND
def & other
call_enum "boolean", other, :and
end
# Integer bitwise EOR with an image, constant or array.
#
# @param other [Image, Real, Array<Real>] bitwise EOR with this
# @return [Image] result of bitwise EOR
def ^ other
call_enum "boolean", other, :eor
end
# Equivalent to image ^ -1
#
# @return [Image] image with bits flipped
def !
self ^ -1
end
# Equivalent to image ^ -1
#
# @return [Image] image with bits flipped
def ~
self ^ -1
end
# @return [Image] image
def +@
self
end
# Equivalent to image * -1
#
# @return [Image] negative of image
def -@
self * -1
end
# Relational less than with an image, constant or array.
#
# @param other [Image, Real, Array<Real>] relational less than with this
# @return [Image] result of less than
def < other
call_enum "relational", other, :less
end
# Relational less than or equal to with an image, constant or array.
#
# @param other [Image, Real, Array<Real>] relational less than or
# equal to with this
# @return [Image] result of less than or equal to
def <= other
call_enum "relational", other, :lesseq
end
# Relational more than with an image, constant or array.
#
# @param other [Image, Real, Array<Real>] relational more than with this
# @return [Image] result of more than
def > other
call_enum "relational", other, :more
end
# Relational more than or equal to with an image, constant or array.
#
# @param other [Image, Real, Array<Real>] relational more than or
# equal to with this
# @return [Image] result of more than or equal to
def >= other
call_enum "relational", other, :moreeq
end
# Compare equality to nil, an image, constant or array.
#
# @param other [nil, Image, Real, Array<Real>] test equality to this
# @return [Image] result of equality
def == other
# for equality, we must allow tests against nil
if other == nil
false
else
call_enum "relational", other, :equal
end
end
# Compare inequality to nil, an image, constant or array.
#
# @param other [nil, Image, Real, Array<Real>] test inequality to this
# @return [Image] result of inequality
def != other
# for equality, we must allow tests against nil
if other == nil
true
else
call_enum "relational", other, :noteq
end
end
# Fetch bands using a number or a range
#
# @param index [Numeric, Range] extract these band(s)
# @return [Image] extracted band(s)
def [] index
if index.is_a? Range
n = index.size
extract_band index.begin, n: n
elsif index.is_a? Numeric
extract_band index
else
raise Vips::Error, "[] index is not range or numeric."
end
end
# Convert to an Array. This will be slow for large images.
#
# @return [Array] array of Fixnum
def to_a
# we render the image to a big string, then unpack
# as a Ruby array of the correct type
memory = write_to_memory
# make the template for unpack
template = {
char: 'c',
uchar: 'C',
short: 's_',
ushort: 'S_',
int: 'i_',
uint: 'I_',
float: 'f',
double: 'd',
complex: 'f',
dpcomplex: 'd'
}[format] + '*'
# and unpack into something like [1, 2, 3, 4 ..]
array = memory.unpack(template)
# gather band elements together
pixel_array = array.each_slice(bands).to_a
# build rows
row_array = pixel_array.each_slice(width).to_a
return row_array
end
# Return the largest integral value not greater than the argument.
#
# @return [Image] floor of image
def floor
round :floor
end
# Return the smallest integral value not less than the argument.
#
# @return [Image] ceil of image
def ceil
round :ceil
end
# Return the nearest integral value.
#
# @return [Image] rint of image
def rint
round :rint
end
# AND the bands of an image together
#
# @return [Image] all bands ANDed together
def bandand
bandbool :and
end
# OR the bands of an image together
#
# @return [Image] all bands ORed together
def bandor
bandbool :or
end
# EOR the bands of an image together
#
# @return [Image] all bands EORed together
def bandeor
bandbool :eor
end
# Split an n-band image into n separate images.
#
# @return [Array<Image>] Array of n one-band images
def bandsplit
(0...bands).map { |i| extract_band i }
end
# Join a set of images bandwise.
#
# @param other [Image, Array<Image>, Real, Array<Real>] bands to append
# @return [Image] many band image
def bandjoin other
unless other.is_a? Array
other = [other]
end
# if other is just Numeric, we can use bandjoin_const
not_all_real = !other.all? { |x| x.is_a? Numeric }
if not_all_real
Vips::Image.bandjoin([self] + other)
else
bandjoin_const other
end
end
# Composite a set of images with a set of blend modes.
#
# @param overlay [Image, Array<Image>] images to composite
# @param mode [BlendMode, Array<BlendMode>] blend modes to use
# @param opts [Hash] Set of options
# @option opts [Vips::Interpretation] :compositing_space Composite images in this colour space
# @option opts [Boolean] :premultiplied Images have premultiplied alpha
# @return [Image] blended image
def composite overlay, mode, **opts
unless overlay.is_a? Array
overlay = [overlay]
end
unless mode.is_a? Array
mode = [mode]
end
mode = mode.map do |x|
GObject::GValue.from_nick Vips::BLEND_MODE_TYPE, x
end
Vips::Image.composite([self] + overlay, mode, opts)
end
# Return the coordinates of the image maximum.
#
# @return [Real, Real, Real] maximum value, x coordinate of maximum, y
# coordinate of maximum
def maxpos
v, opts = max x: true, y: true
x = opts['x']
y = opts['y']
return v, x, y
end
# Return the coordinates of the image minimum.
#
# @return [Real, Real, Real] minimum value, x coordinate of minimum, y
# coordinate of minimum
def minpos
v, opts = min x: true, y: true
x = opts['x']
y = opts['y']
return v, x, y
end
# a median filter
#
# @param size [Integer] size of filter window
# @return [Image] result of median filter
def median size = 3
rank size, size, (size * size) / 2
end
# Return the real part of a complex image.
#
# @return [Image] real part of complex image
def real
complexget :real
end
# Return the imaginary part of a complex image.
#
# @return [Image] imaginary part of complex image
def imag
complexget :imag
end
# Return an image with rectangular pixels converted to polar.
#
# The image
# can be complex, in which case the return image will also be complex,
# or must have an even number of bands, in which case pairs of
# bands are treated as (x, y) coordinates.
#
# @see xyz
# @return [Image] image converted to polar coordinates
def polar
Image::run_cmplx(self) { |x| x.complex :polar }
end
# Return an image with polar pixels converted to rectangular.
#
# The image
# can be complex, in which case the return image will also be complex,
# or must have an even number of bands, in which case pairs of
# bands are treated as (x, y) coordinates.
#
# @see xyz
# @return [Image] image converted to rectangular coordinates
def rect
Image::run_cmplx(self) { |x| x.complex :rect }
end
# Return the complex conjugate of an image.
#
# The image
# can be complex, in which case the return image will also be complex,
# or must have an even number of bands, in which case pairs of
# bands are treated as (x, y) coordinates.
#
# @return [Image] complex conjugate
def conj
Image::run_cmplx(self) { |x| x.complex :conj }
end
# Calculate the cross phase of two images.
#
# @param other [Image, Real, Array<Real>] cross phase with this
# @return [Image] cross phase
def cross_phase other
complex2 other, :cross_phase
end
# Return the sine of an image in degrees.
#
# @return [Image] sine of each pixel
def sin
math :sin
end
# Return the cosine of an image in degrees.
#
# @return [Image] cosine of each pixel
def cos
math :cos
end
# Return the tangent of an image in degrees.
#
# @return [Image] tangent of each pixel
def tan
math :tan
end
# Return the inverse sine of an image in degrees.
#
# @return [Image] inverse sine of each pixel
def asin
math :asin
end
# Return the inverse cosine of an image in degrees.
#
# @return [Image] inverse cosine of each pixel
def acos
math :acos
end
# Return the inverse tangent of an image in degrees.
#
# @return [Image] inverse tangent of each pixel
def atan
math :atan
end
# Return the natural log of an image.
#
# @return [Image] natural log of each pixel
def log
math :log
end
# Return the log base 10 of an image.
#
# @return [Image] base 10 log of each pixel
def log10
math :log10
end
# Return e ** pixel.
#
# @return [Image] e ** pixel
def exp
math :exp
end
# Return 10 ** pixel.
#
# @return [Image] 10 ** pixel
def exp10
math :exp10
end
# Flip horizontally.
#
# @return [Image] image flipped horizontally
def fliphor
flip :horizontal
end
# Flip vertically.
#
# @return [Image] image flipped vertically
def flipver
flip :vertical
end
# Erode with a structuring element.
#
# The structuring element must be an array with 0 for black, 255 for
# white and 128 for don't care.
#
# @param mask [Image, Array<Real>, Array<Array<Real>>] structuring
# element
# @return [Image] eroded image
def erode mask
morph mask, :erode
end
# Dilate with a structuring element.
#
# The structuring element must be an array with 0 for black, 255 for
# white and 128 for don't care.
#
# @param mask [Image, Array<Real>, Array<Array<Real>>] structuring
# element
# @return [Image] dilated image
def dilate mask
morph mask, :dilate
end
# Rotate by 90 degrees clockwise.
#
# @return [Image] rotated image
def rot90
rot :d90
end
# Rotate by 180 degrees clockwise.
#
# @return [Image] rotated image
def rot180
rot :d180
end
# Rotate by 270 degrees clockwise.
#
# @return [Image] rotated image
def rot270
rot :d270
end
# Select pixels from `th` if `self` is non-zero and from `el` if
# `self` is zero. Use the `:blend` option to fade smoothly
# between `th` and `el`.
#
# @param th [Image, Real, Array<Real>] true values
# @param el [Image, Real, Array<Real>] false values
# @param opts [Hash] set of options
# @option opts [Boolean] :blend (false) Blend smoothly between th and el
# @return [Image] merged image
def ifthenelse(th, el, **opts)
match_image = [th, el, self].find { |x| x.is_a? Vips::Image }
unless th.is_a? Vips::Image
th = Operation.imageize match_image, th
end
unless el.is_a? Vips::Image
el = Operation.imageize match_image, el
end
Vips::Operation.call "ifthenelse", [self, th, el], opts
end
# Scale an image to uchar. This is the vips `scale` operation, but
# renamed to avoid a clash with the `.scale` property.
#
# @param opts [Hash] Set of options
# @return [Vips::Image] Output image
def scaleimage **opts
Vips::Image.scale self, opts
end
end
end
module Vips
# This module generates yard comments for all the dynamically bound
# vips operations.
#
# Regenerate with something like:
#
# ```
# $ ruby > methods.rb
# require 'vips'; Vips::Yard.generate
# ^D
# ```
module Yard
# map gobject's type names to Ruby
MAP_GO_TO_RUBY = {
"gboolean" => "Boolean",
"gint" => "Integer",
"gdouble" => "Float",
"gfloat" => "Float",
"gchararray" => "String",
"VipsImage" => "Vips::Image",
"VipsInterpolate" => "Vips::Interpolate",
"VipsStream" => "Vips::Stream",
"VipsStreami" => "Vips::Streami",
"VipsStreamo" => "Vips::Streamo",
"VipsStreamiu" => "Vips::Streamiu",
"VipsStreamou" => "Vips::Streamou",
"VipsArrayDouble" => "Array<Double>",
"VipsArrayInt" => "Array<Integer>",
"VipsArrayImage" => "Array<Image>",
"VipsArrayString" => "Array<String>",
}
# these have hand-written methods, see above
NO_GENERATE = ["scale", "bandjoin", "composite", "ifthenelse"]
# turn a gtype into a ruby type name
def self.gtype_to_ruby gtype
fundamental = GObject::g_type_fundamental gtype
type_name = GObject::g_type_name gtype
if MAP_GO_TO_RUBY.include? type_name
type_name = MAP_GO_TO_RUBY[type_name]
end
if fundamental == GObject::GFLAGS_TYPE ||
fundamental == GObject::GENUM_TYPE
type_name = "Vips::" + type_name[/Vips(.*)/, 1]
end
type_name
end
def self.generate_operation introspect
return if (introspect.flags & OPERATION_DEPRECATED) != 0
return if NO_GENERATE.include? introspect.name
method_args = introspect.method_args
required_output = introspect.required_output
optional_input = introspect.optional_input
optional_output = introspect.optional_output
print "# @!method "
print "self." unless introspect.member_x
print "#{introspect.name}("
print method_args.map{ |x| x[:yard_name] }.join(", ")
print ", " if method_args.length > 0
puts "**opts)"
puts "# #{introspect.description.capitalize}."
method_args.each do |details|
yard_name = details[:yard_name]
gtype = details[:gtype]
blurb = details[:blurb]
puts "# @param #{yard_name} [#{gtype_to_ruby(gtype)}] #{blurb}"
end
puts "# @param opts [Hash] Set of options"
optional_input.each do |arg_name, details|
yard_name = details[:yard_name]
gtype = details[:gtype]
blurb = details[:blurb]
puts "# @option opts [#{gtype_to_ruby(gtype)}] :#{yard_name} " +
"#{blurb}"
end
optional_output.each do |arg_name, details|
yard_name = details[:yard_name]
gtype = details[:gtype]
blurb = details[:blurb]
print "# @option opts [#{gtype_to_ruby(gtype)}] :#{yard_name}"
puts " Output #{blurb}"
end
print "# @return ["
if required_output.length == 0
print "nil"
elsif required_output.length == 1
print gtype_to_ruby(required_output.first[:gtype])
else
print "Array<"
print required_output.map{ |x| gtype_to_ruby(x[:gtype]) }.join(", ")
print ">"
end
if optional_output.length > 0
print ", Hash<Symbol => Object>"
end
print "] "
print required_output.map{ |x| x[:blurb] }.join(", ")
if optional_output.length > 0
print ", " if required_output.length > 0
print "Hash of optional output items"
end
puts ""
puts ""
end
def self.generate
generate_class = lambda do |gtype, _|
nickname = Vips::nickname_find gtype
if nickname
begin
# can fail for abstract types
introspect = Vips::Introspect.get_yard nickname
rescue Vips::Error
nil
end
generate_operation(introspect) if introspect
end
Vips::vips_type_map gtype, generate_class, nil
end
puts "module Vips"
puts " class Image"
puts ""
generate_class.(GObject::g_type_from_name("VipsOperation"), nil)
puts " end"
puts "end"
end
end
end
| 27.901391 | 98 | 0.619619 |
184b953ad3bea9f80eaa88b8117ccd758336c7ca | 344 | cask "font-marmelad" do
version :latest
sha256 :no_check
# github.com/google/fonts/ was verified as official when first introduced to the cask
url "https://github.com/google/fonts/raw/master/ofl/marmelad/Marmelad-Regular.ttf"
name "Marmelad"
homepage "https://fonts.google.com/specimen/Marmelad"
font "Marmelad-Regular.ttf"
end
| 28.666667 | 87 | 0.755814 |
280e8219eb8287eb87b06e1082f070a7e5c0ac98 | 4,090 | #!/usr/bin/env ruby
require 'cgi'
module DText
def parse_inline(str, options = {})
str = str.gsub(/&/, "&")
str.gsub!(/</, "<")
str.gsub!(/>/, ">")
str.gsub!(/\[\[.+?\]\]/m) do |tag|
tag = tag[2..-3]
if tag =~ /^(.+?)\|(.+)$/
tag = $1
name = $2
'<a href="/wiki/show?title=' + CGI.escape(CGI.unescapeHTML(tag.tr(" ", "_").downcase)) + '">' + name + '</a>'
else
'<a href="/wiki/show?title=' + CGI.escape(CGI.unescapeHTML(tag.tr(" ", "_").downcase)) + '">' + tag + '</a>'
end
end
str.gsub!(/\{\{.+?\}\}/m) do |tag|
tag = tag[2..-3]
'<a href="/post/index?tags=' + CGI.escape(CGI.unescapeHTML(tag)) + '">' + tag + '</a>'
end
str.gsub!(/[Pp]ost #(\d+)/, '<a href="/post/show/\1">post #\1</a>')
str.gsub!(/[Ff]orum #(\d+)/, '<a href="/forum/show/\1">forum #\1</a>')
str.gsub!(/[Cc]omment #(\d+)/, '<a href="/comment/show/\1">comment #\1</a>')
str.gsub!(/[Pp]ool #(\d+)/, '<a href="/pool/show/\1">pool #\1</a>')
#str.gsub!(/[Pp]review #(\d+)/) {print_preview(Post.find($1))}
str.gsub!(/\n/m, "<br>")
str.gsub!(/\[b\](.+?)\[\/b\]/, '<strong>\1</strong>')
str.gsub!(/\[i\](.+?)\[\/i\]/, '<em>\1</em>')
str.gsub!(/("[^"]+":(https?:\/\/|\/)\S+|https?:\/\/\S+)/m) do |link|
if link =~ /^"([^"]+)":(.+)$/
text = $1
link = $2
else
text = link
end
if link =~ /([;,.!?\)\]<>])$/
link.chop!
ch = $1
else
ch = ""
end
link.gsub!(/"/, '"')
'<a href="' + link + '">' + text + '</a>' + ch
end
str
end
def parse_list(str, options = {})
html = ""
layout = []
nest = 0
str.split(/\n/).each do |line|
if line =~ /^\s*(\*+) (.+)/
nest = $1.size
content = parse_inline($2)
else
content = parse_inline(line)
end
if nest > layout.size
html += "<ul>"
layout << "ul"
end
while nest < layout.size
elist = layout.pop
if elist
html += "</#{elist}>"
end
end
html += "<li>#{content}</li>"
end
while layout.any?
elist = layout.pop
html += "</#{elist}>"
end
html
end
def parse(str, options = {})
return "" if str.blank?
# Make sure quote tags are surrounded by newlines
unless options[:inline]
str.gsub!(/\s*\[quote\]\s*/m, "\n\n[quote]\n\n")
str.gsub!(/\s*\[\/quote\]\s*/m, "\n\n[/quote]\n\n")
str.gsub!(/\s*\[spoilers?\](?!\])\s*/m, "\n\n[spoiler]\n\n")
str.gsub!(/\s*\[\/spoilers?\]\s*/m, "\n\n[/spoiler]\n\n")
end
str.gsub!(/(?:\r?\n){3,}/, "\n\n")
str.strip!
blocks = str.split(/(?:\r?\n){2}/)
stack = []
html = blocks.map do |block|
case block
when /^(h[1-6])\.\s*(.+)$/
tag = $1
content = $2
if options[:inline]
"<h6>" + parse_inline(content, options) + "</h6>"
else
"<#{tag}>" + parse_inline(content, options) + "</#{tag}>"
end
when /^\s*\*+ /
parse_list(block, options)
when "[quote]"
if options[:inline]
""
else
stack << "blockquote"
"<blockquote>"
end
when "[/quote]"
if options[:inline]
""
elsif stack.last == "blockquote"
stack.pop
'</blockquote>'
else
""
end
when /\[spoilers?\](?!\])/
stack << "div"
'<div class="spoiler">'
when /\[\/spoilers?\]/
if stack.last == "div"
stack.pop
'</div>'
end
else
'<p>' + parse_inline(block) + "</p>"
end
end
stack.reverse.each do |tag|
if tag == "blockquote"
html << "</blockquote>"
elsif tag == "div"
html << "</div>"
end
end
html.join("")
end
module_function :parse_inline
module_function :parse_list
module_function :parse
end
| 24.058824 | 117 | 0.428117 |
21f906b452ae3cb6619564c9e93d6a92f2a7b55c | 292 | class CreateTestEngineDurations < ActiveRecord::Migration
def change
create_table :test_engine_durations do |t|
t.string :minutes
t.string :type
t.references :learning_journey, index: true
t.references :session, index: true
t.timestamps
end
end
end
| 22.461538 | 57 | 0.69863 |
035936b4ccc70dc7937fa446b1f55f173432defa | 713 | class ApplicationController < ActionController::Base
before_action :set_locale
protect_from_forgery with: :exception
helper_method :current_year, :current_user
private
def authorize
redirect_to login_url, alert: t('auth.notauth') if current_user.nil?
end
def current_year
Time.now.year
end
def set_locale
if params[:locale] && I18n.locale_available?(params[:locale])
I18n.locale = params[:locale]
session[:locale] = I18n.locale
elsif session[:locale].present?
I18n.locale = session[:locale]
else
I18n.locale = I18n.default_locale
end
end
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
end
| 22.28125 | 72 | 0.708275 |
7aaa1ab256a0743997a71e8e3103e3d9d81a77ea | 1,279 | module Lolipop
module Mc
module Starter
module Rails
module CheckItem
class EnvDatabase < Base
def check
config = @config.load
ssh_command = config['ssh']
if ssh_command == @config::NOCHECK
raise 'SSHコマンドの実行に失敗しました。SSH接続の設定を確認してください'
end
begin
stdout, stderr, status = Open3.capture3("#{ssh_command} env")
rescue => e
raise "SSHコマンドの実行に失敗しました。SSH接続の設定を確認してください #{e.message}"
end
raise '環境変数 `DATABASE_URL` が設定されていません' unless stdout.match(/DATABASE_URL=/)
raise '環境変数 `DATABASE_URL` のアダプターがmysql2ではありません' unless stdout.match("DATABASE_URL=mysql2://")
'環境変数 `DATABASE_URL` が設定されています'
end
def hint
puts 'Railsは環境変数に `DATABASE_URL` を設定すると config/database.yml ではなく `DATABASE_URL` のDB接続設定を優先します'
puts 'マネージドクラウドのプロジェクト詳細の `データベース` の記載を組み合わせて `DATABASE_URL` を作成して、同じくマネージドクラウドのプロジェクト詳細の `環境変数の設定と管理` で環境変数 `DATABASE_URL` を追加してください'
puts 'DATABASE_URL を作成するために、 `mc-rails database` というコマンドを実行し、インストラクションに従って値を入力してください。'
end
end
end
end
end
end
end
| 37.617647 | 148 | 0.591869 |
fff7329491c9eeeaef4e7d1b2c5e58aa65d04800 | 8,046 | require 'spec_helper'
describe MergeRequests::MergeService, services: true do
let(:user) { create(:user) }
let(:user2) { create(:user) }
let(:merge_request) { create(:merge_request, assignee: user2) }
let(:project) { merge_request.project }
before do
project.team << [user, :master]
project.team << [user2, :developer]
end
describe '#execute' do
context 'valid params' do
let(:service) { MergeRequests::MergeService.new(project, user, commit_message: 'Awesome message') }
before do
allow(service).to receive(:execute_hooks)
perform_enqueued_jobs do
service.execute(merge_request)
end
end
it { expect(merge_request).to be_valid }
it { expect(merge_request).to be_merged }
it 'sends email to user2 about merge of new merge_request' do
email = ActionMailer::Base.deliveries.last
expect(email.to.first).to eq(user2.email)
expect(email.subject).to include(merge_request.title)
end
it 'creates system note about merge_request merge' do
note = merge_request.notes.last
expect(note.note).to include 'merged'
end
end
context 'project has exceeded size limit' do
let(:service) { MergeRequests::MergeService.new(project, user, commit_message: 'Awesome message') }
before do
allow(project).to receive(:above_size_limit?).and_return(true)
perform_enqueued_jobs do
service.execute(merge_request)
end
end
it 'returns the correct error message' do
expect(merge_request.merge_error).to include('This merge request cannot be merged')
end
end
context 'closes related issues' do
let(:service) { described_class.new(project, user, commit_message: 'Awesome message') }
before do
allow(project).to receive(:default_branch).and_return(merge_request.target_branch)
end
it 'closes GitLab issue tracker issues' do
issue = create :issue, project: project
commit = double('commit', safe_message: "Fixes #{issue.to_reference}")
allow(merge_request).to receive(:commits).and_return([commit])
service.execute(merge_request)
expect(issue.reload.closed?).to be_truthy
end
context 'with JIRA integration' do
include JiraServiceHelper
let(:jira_tracker) { project.create_jira_service }
let(:jira_issue) { ExternalIssue.new('JIRA-123', project) }
let(:commit) { double('commit', safe_message: "Fixes #{jira_issue.to_reference}") }
before do
project.update_attributes!(has_external_issue_tracker: true)
jira_service_settings
stub_jira_urls(jira_issue.id)
allow(merge_request).to receive(:commits).and_return([commit])
end
it 'closes issues on JIRA issue tracker' do
jira_issue = ExternalIssue.new('JIRA-123', project)
stub_jira_urls(jira_issue)
commit = double('commit', safe_message: "Fixes #{jira_issue.to_reference}")
allow(merge_request).to receive(:commits).and_return([commit])
expect_any_instance_of(JiraService).to receive(:close_issue).with(merge_request, jira_issue).once
service.execute(merge_request)
end
context "when jira_issue_transition_id is not present" do
before { allow_any_instance_of(JIRA::Resource::Issue).to receive(:resolution).and_return(nil) }
it "does not close issue" do
allow(jira_tracker).to receive_messages(jira_issue_transition_id: nil)
expect_any_instance_of(JiraService).not_to receive(:transition_issue)
service.execute(merge_request)
end
end
context "wrong issue markdown" do
it 'does not close issues on JIRA issue tracker' do
jira_issue = ExternalIssue.new('#JIRA-123', project)
stub_jira_urls(jira_issue)
commit = double('commit', safe_message: "Fixes #{jira_issue.to_reference}")
allow(merge_request).to receive(:commits).and_return([commit])
expect_any_instance_of(JiraService).not_to receive(:close_issue)
service.execute(merge_request)
end
end
end
end
context 'closes related todos' do
let(:merge_request) { create(:merge_request, assignee: user, author: user) }
let(:project) { merge_request.project }
let(:service) { MergeRequests::MergeService.new(project, user, commit_message: 'Awesome message') }
let!(:todo) do
create(:todo, :assigned,
project: project,
author: user,
user: user,
target: merge_request)
end
before do
allow(service).to receive(:execute_hooks)
perform_enqueued_jobs do
service.execute(merge_request)
todo.reload
end
end
it { expect(todo).to be_done }
end
context 'remove source branch by author' do
let(:service) do
merge_request.merge_params['force_remove_source_branch'] = '1'
merge_request.save!
MergeRequests::MergeService.new(project, user, commit_message: 'Awesome message')
end
it 'removes the source branch' do
expect(DeleteBranchService).to receive(:new).
with(merge_request.source_project, merge_request.author).
and_call_original
service.execute(merge_request)
end
end
context "error handling" do
let(:service) { MergeRequests::MergeService.new(project, user, commit_message: 'Awesome message') }
it 'saves error if there is an exception' do
allow(service).to receive(:repository).and_raise("error message")
allow(service).to receive(:execute_hooks)
service.execute(merge_request)
expect(merge_request.merge_error).to eq("Something went wrong during merge: error message")
end
it 'saves error if there is an PreReceiveError exception' do
allow(service).to receive(:repository).and_raise(GitHooksService::PreReceiveError, "error")
allow(service).to receive(:execute_hooks)
service.execute(merge_request)
expect(merge_request.merge_error).to eq("error")
end
it 'aborts if there is a merge conflict' do
allow_any_instance_of(Repository).to receive(:merge).and_return(false)
allow(service).to receive(:execute_hooks)
service.execute(merge_request)
expect(merge_request.open?).to be_truthy
expect(merge_request.merge_commit_sha).to be_nil
expect(merge_request.merge_error).to eq("Conflicts detected during merge")
end
end
end
describe '#hooks_validation_pass?' do
let(:service) { MergeRequests::MergeService.new(project, user, commit_message: 'Awesome message') }
it 'returns true when valid' do
expect(service.hooks_validation_pass?(merge_request)).to be_truthy
end
context 'commit message validation' do
before do
allow(project).to receive(:push_rule) { build(:push_rule, commit_message_regex: 'unmatched pattern .*') }
end
it 'returns false and saves error when invalid' do
expect(service.hooks_validation_pass?(merge_request)).to be_falsey
expect(merge_request.merge_error).not_to be_empty
end
end
context 'authors email validation' do
before do
allow(project).to receive(:push_rule) { build(:push_rule, author_email_regex: '.*@unmatchedemaildomain.com') }
end
it 'returns false and saves error when invalid' do
expect(service.hooks_validation_pass?(merge_request)).to be_falsey
expect(merge_request.merge_error).not_to be_empty
end
end
context 'fast forward merge request' do
it 'returns true when fast forward is enabled' do
allow(project).to receive(:merge_requests_ff_only_enabled) { true }
expect(service.hooks_validation_pass?(merge_request)).to be_truthy
end
end
end
end
| 33.665272 | 118 | 0.668282 |
619adcb89712240fbbdc29ff7a6097897fb934cf | 1,159 | require "thor/group"
require "active_support/inflector"
module Corneal
module Generators
class ControllerGenerator < Thor::Group
include Thor::Actions
attr_reader :controller_name, :class_name, :file_name
desc "Generate an Controller with associated views"
argument :name, type: :string, desc: "Name of the controller"
# --no-views make views optional
class_option :views, type: :boolean, default: true, desc: "Generate views for controller"
def self.source_root
File.dirname(__FILE__)
end
def setup
@controller_name = name.pluralize.underscore
@class_name = "#{controller_name.camel_case}Controller"
@file_name = class_name.underscore
end
def create_controller
template "templates/controller.rb.erb", File.join("app/controllers", "#{file_name}.rb")
insert_into_file "config.ru", "use #{class_name}\n", after: "run ApplicationController\n"
end
def create_views
return unless options[:views]
directory "templates/views", File.join("app/views", "#{controller_name}")
end
end
end
end
| 30.5 | 97 | 0.669543 |
0326982ff1aca3bd715efb4ad1cb480abf46ca83 | 1,317 | require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/classes', __FILE__)
describe "IO.try_convert" do
before :each do
@name = tmp("io_try_convert.txt")
@io = new_io @name
end
after :each do
@io.close unless @io.closed?
rm_r @name
end
it "returns the passed IO object" do
IO.try_convert(@io).should equal(@io)
end
it "does not call #to_io on an IO instance" do
@io.should_not_receive(:to_io)
IO.try_convert(@io)
end
it "calls #to_io to coerce an object" do
obj = mock("io")
obj.should_receive(:to_io).and_return(@io)
IO.try_convert(obj).should equal(@io)
end
it "returns nil when the passed object does not respond to #to_io" do
IO.try_convert(mock("io")).should be_nil
end
it "return nil when BasicObject is passed" do
IO.try_convert(BasicObject.new).should be_nil
end
it "raises a TypeError if the object does not return an IO from #to_io" do
obj = mock("io")
obj.should_receive(:to_io).and_return("io")
lambda { IO.try_convert(obj) }.should raise_error(TypeError)
end
it "propagates an exception raised by #to_io" do
obj = mock("io")
obj.should_receive(:to_io).and_raise(TypeError.new)
lambda{ IO.try_convert(obj) }.should raise_error(TypeError)
end
end
| 26.34 | 76 | 0.687168 |
397da8abc7cada1f45ba5ae13b167e7f31a57c93 | 136 | # frozen_string_literal: true
module WaterDrop
# Namespace for all the contracts for config validations
module Contracts
end
end
| 17 | 58 | 0.794118 |
ff95cf3f7313f3435716e00a54c45457c235f3ba | 83 | class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :body
end
| 20.75 | 46 | 0.771084 |
bf298dfb17aa65466a29bd5e79d3e0bb362e1ab3 | 3,453 | module HealthSeven::V2_5_1
class RdsO13 < ::HealthSeven::Message
attribute :msh, Msh, position: "MSH", require: true
attribute :sfts, Array[Sft], position: "SFT", multiple: true
attribute :ntes, Array[Nte], position: "NTE", multiple: true
class Patient < ::HealthSeven::SegmentGroup
attribute :pid, Pid, position: "PID", require: true
attribute :pd1, Pd1, position: "PD1"
attribute :ntes, Array[Nte], position: "NTE", multiple: true
attribute :al1s, Array[Al1], position: "AL1", multiple: true
class PatientVisit < ::HealthSeven::SegmentGroup
attribute :pv1, Pv1, position: "PV1", require: true
attribute :pv2, Pv2, position: "PV2"
end
attribute :patient_visit, PatientVisit, position: "RDS_O13.PATIENT_VISIT"
end
attribute :patient, Patient, position: "RDS_O13.PATIENT"
class Order < ::HealthSeven::SegmentGroup
attribute :orc, Orc, position: "ORC", require: true
class Timing < ::HealthSeven::SegmentGroup
attribute :tq1, Tq1, position: "TQ1", require: true
attribute :tq2s, Array[Tq2], position: "TQ2", multiple: true
end
attribute :timings, Array[Timing], position: "RDS_O13.TIMING", multiple: true
class OrderDetail < ::HealthSeven::SegmentGroup
attribute :rxo, Rxo, position: "RXO", require: true
class OrderDetailSupplement < ::HealthSeven::SegmentGroup
attribute :ntes, Array[Nte], position: "NTE", require: true, multiple: true
attribute :rxrs, Array[Rxr], position: "RXR", require: true, multiple: true
class Component < ::HealthSeven::SegmentGroup
attribute :rxc, Rxc, position: "RXC", require: true
attribute :ntes, Array[Nte], position: "NTE", multiple: true
end
attribute :components, Array[Component], position: "RDS_O13.COMPONENT", multiple: true
end
attribute :order_detail_supplement, OrderDetailSupplement, position: "RDS_O13.ORDER_DETAIL_SUPPLEMENT"
end
attribute :order_detail, OrderDetail, position: "RDS_O13.ORDER_DETAIL"
class Encoding < ::HealthSeven::SegmentGroup
attribute :rxe, Rxe, position: "RXE", require: true
attribute :ntes, Array[Nte], position: "NTE", multiple: true
class TimingEncoded < ::HealthSeven::SegmentGroup
attribute :tq1, Tq1, position: "TQ1", require: true
attribute :tq2s, Array[Tq2], position: "TQ2", multiple: true
end
attribute :timing_encodeds, Array[TimingEncoded], position: "RDS_O13.TIMING_ENCODED", require: true, multiple: true
attribute :rxrs, Array[Rxr], position: "RXR", require: true, multiple: true
attribute :rxcs, Array[Rxc], position: "RXC", multiple: true
end
attribute :encoding, Encoding, position: "RDS_O13.ENCODING"
attribute :rxd, Rxd, position: "RXD", require: true
attribute :ntes, Array[Nte], position: "NTE", multiple: true
attribute :rxrs, Array[Rxr], position: "RXR", require: true, multiple: true
attribute :rxcs, Array[Rxc], position: "RXC", multiple: true
class Observation < ::HealthSeven::SegmentGroup
attribute :obx, Obx, position: "OBX", require: true
attribute :ntes, Array[Nte], position: "NTE", multiple: true
end
attribute :observations, Array[Observation], position: "RDS_O13.OBSERVATION", multiple: true
attribute :ft1s, Array[Ft1], position: "FT1", multiple: true
end
attribute :orders, Array[Order], position: "RDS_O13.ORDER", require: true, multiple: true
end
end | 53.953125 | 121 | 0.693021 |
d56efa10b5ec740aa9c5536767aea4804de483c4 | 7,069 | require 'repositories/service_usage_event_repository'
module VCAP::CloudController
class ServiceInstance < Sequel::Model
class InvalidServiceBinding < StandardError; end
ROUTE_SERVICE_WARNING = 'Support for route services is disabled. This service instance cannot be bound to a route.'.freeze
VOLUME_SERVICE_WARNING = 'Support for volume services is disabled. This service instance cannot be bound to an app.'.freeze
plugin :serialization
plugin :single_table_inheritance, :is_gateway_service,
model_map: lambda { |is_gateway_service|
if is_gateway_service
VCAP::CloudController::ManagedServiceInstance
else
VCAP::CloudController::UserProvidedServiceInstance
end
},
key_map: lambda { |klazz|
klazz == VCAP::CloudController::ManagedServiceInstance
}
plugin :columns_updated
serialize_attributes :json, :tags
one_to_one :service_instance_operation
one_to_many :service_bindings, before_add: :validate_service_binding, key: :service_instance_guid, primary_key: :guid
one_to_many :service_keys
many_to_many :shared_spaces,
left_key: :service_instance_guid,
left_primary_key: :guid,
right_key: :target_space_guid,
right_primary_key: :guid,
join_table: :service_instance_shares,
class: VCAP::CloudController::Space
many_to_many :routes, join_table: :route_bindings
many_to_one :space, after_set: :validate_space
many_to_one :service_plan_sti_eager_load,
class: 'VCAP::CloudController::ServicePlan',
dataset: -> { raise 'Must be used for eager loading' },
eager_loader_key: nil, # set up id_map ourselves
eager_loader: proc { |eo|
id_map = {}
eo[:rows].each do |service_instance|
service_instance.associations[:service_plan] = nil
id_map[service_instance.service_plan_id] ||= []
id_map[service_instance.service_plan_id] << service_instance
end
ds = ServicePlan.where(id: id_map.keys)
ds = ds.eager(eo[:associations]) if eo[:associations]
ds = eo[:eager_block].call(ds) if eo[:eager_block]
ds.all do |service_plan|
id_map[service_plan.id].each { |si| si.associations[:service_plan] = service_plan }
end
}
delegate :organization, to: :space
set_field_as_encrypted :credentials
def self.user_visibility_filter(user)
visible_spaces = user.spaces_dataset.all.
concat(user.audited_spaces_dataset.all).
concat(user.managed_spaces_dataset.all).
concat(managed_organizations_spaces_dataset(user.managed_organizations_dataset).all).uniq
Sequel.or([
[:space, visible_spaces],
[:shared_spaces, visible_spaces]
])
end
def type
self.class.name.demodulize.underscore
end
def user_provided_instance?
self.type == UserProvidedServiceInstance.name.demodulize.underscore
end
def managed_instance?
!user_provided_instance?
end
def name_clashes
proc do |_, instance|
next if instance.space_id.nil? || instance.name.nil?
clashes_with_shared_instance_names =
ServiceInstance.select_all(ServiceInstance.table_name).
join(:service_instance_shares, service_instance_guid: :guid, target_space_guid: instance.space_guid).
where(name: instance.name)
clashes_with_instance_names =
ServiceInstance.select_all(ServiceInstance.table_name).
where(space_id: instance.space_id, name: instance.name)
clashes_with_shared_instance_names.union(clashes_with_instance_names)
end
end
def validate
validates_presence :name
validates_presence :space
validates_unique :name, where: name_clashes
validates_max_length 50, :name
validates_max_length 10_000, :syslog_drain_url, allow_nil: true
validate_tags_length
end
# Make sure all derived classes use the base access class
def self.source_class
ServiceInstance
end
def tags
super || []
end
def bindable?
true
end
def as_summary_json
{
'guid' => guid,
'name' => name,
'bound_app_count' => service_bindings_dataset.count,
}
end
def to_hash(opts={})
access_context = VCAP::CloudController::Security::AccessContext.new
if access_context.cannot?(:read_env, self)
opts[:redact] = ['credentials']
end
hash = super(opts)
hash
end
def credentials_with_serialization=(val)
self.credentials_without_serialization = MultiJson.dump(val)
end
alias_method_chain :credentials=, 'serialization'
def credentials_with_serialization
string = credentials_without_serialization
return if string.blank?
MultiJson.load string
end
alias_method_chain :credentials, 'serialization'
def in_suspended_org?
space&.in_suspended_org?
end
def after_create
super
service_instance_usage_event_repository.created_event_from_service_instance(self)
end
def after_destroy
super
service_instance_usage_event_repository.deleted_event_from_service_instance(self)
end
def after_update
super
update_service_bindings
if @columns_updated.key?(:service_plan_id) || @columns_updated.key?(:name)
service_instance_usage_event_repository.updated_event_from_service_instance(self)
end
end
def last_operation
nil
end
def operation_in_progress?
false
end
def route_service?
false
end
def shareable?
false
end
def volume_service?
false
end
def shared?
shared_spaces.any?
end
def self.managed_organizations_spaces_dataset(managed_organizations_dataset)
VCAP::CloudController::Space.dataset.filter({ organization_id: managed_organizations_dataset.select(:organization_id) })
end
private
def validate_service_binding(service_binding)
if service_binding && service_binding.app.space != space
raise InvalidServiceBinding.new(service_binding.id)
end
end
def validate_space(space)
service_bindings.each { |binding| validate_service_binding(binding) }
end
def validate_tags_length
if tags.join('').length > 2048
@errors[:tags] = [:too_long]
end
end
def service_instance_usage_event_repository
@repository ||= Repositories::ServiceUsageEventRepository.new
end
def update_service_bindings
if columns_updated.key?(:syslog_drain_url)
service_bindings_dataset.update(syslog_drain_url: syslog_drain_url)
end
end
end
end
| 29.701681 | 127 | 0.666714 |
f772b9ee5828773453a4d94c57679fd88106a279 | 169 | require 'chef/provisioning/fog_driver/driver'
with_driver 'fog:AWS'
with_machine_options :bootstrap_options => {
:tags => {
'chef-provisioning-test' => ''
}
}
| 16.9 | 45 | 0.692308 |
e86546c351f7fee38fc647ca99a5b71b6b3f8663 | 93 | module TokyoMetro::Api::TrainTimetable::Info::StationTime::Info::TrainRelation::Following
end | 46.5 | 89 | 0.827957 |
9166999b4001d8b414899174cbfafedd964636e3 | 2,417 | # frozen_string_literal: true
module Resolvers
module Ci
class RunnerSetupResolver < BaseResolver
ACCESS_DENIED = 'User is not authorized to register a runner for the specified resource!'
type Types::Ci::RunnerSetupType, null: true
description 'Runner setup instructions.'
argument :platform,
type: GraphQL::STRING_TYPE,
required: true,
description: 'Platform to generate the instructions for.'
argument :architecture,
type: GraphQL::STRING_TYPE,
required: true,
description: 'Architecture to generate the instructions for.'
argument :project_id,
type: ::Types::GlobalIDType[::Project],
required: false,
deprecated: { reason: 'No longer used', milestone: '13.11' },
description: 'Project to register the runner for.'
argument :group_id,
type: ::Types::GlobalIDType[::Group],
required: false,
deprecated: { reason: 'No longer used', milestone: '13.11' },
description: 'Group to register the runner for.'
def resolve(platform:, architecture:, **args)
instructions = Gitlab::Ci::RunnerInstructions.new(
os: platform,
arch: architecture
)
{
install_instructions: instructions.install_script || other_install_instructions(platform),
register_instructions: instructions.register_command
}
ensure
raise Gitlab::Graphql::Errors::ResourceNotAvailable, ACCESS_DENIED if access_denied?(instructions)
end
private
def access_denied?(instructions)
instructions.errors.include?('Gitlab::Access::AccessDeniedError')
end
def other_install_instructions(platform)
Gitlab::Ci::RunnerInstructions::OTHER_ENVIRONMENTS[platform.to_sym][:installation_instructions_url]
end
def target_param(args)
project_param(args[:project_id]) || group_param(args[:group_id]) || {}
end
def project_param(project_id)
return unless project_id
{ project: find_object(project_id) }
end
def group_param(group_id)
return unless group_id
{ group: find_object(group_id) }
end
def find_object(gid)
GlobalID::Locator.locate(gid)
end
end
end
end
| 30.594937 | 107 | 0.62681 |
01efa009979bb237645238d06204e6de7267c4d8 | 13,690 | # encoding: utf-8
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
require 'azure_mgmt_subscriptions'
module Azure::Profiles::Latest
module Subscriptions
module Mgmt
SubscriptionDefinitionsOperationMetadata = Azure::Subscriptions::Mgmt::V2017_11_01_preview::SubscriptionDefinitionsOperationMetadata
SubscriptionDefinitions = Azure::Subscriptions::Mgmt::V2017_11_01_preview::SubscriptionDefinitions
SubscriptionOperations = Azure::Subscriptions::Mgmt::V2018_03_01_preview::SubscriptionOperations
SubscriptionOperationOperations = Azure::Subscriptions::Mgmt::V2018_11_01_preview::SubscriptionOperationOperations
SubscriptionFactory = Azure::Subscriptions::Mgmt::V2018_11_01_preview::SubscriptionFactory
Subscriptions = Azure::Subscriptions::Mgmt::V2019_06_01::Subscriptions
Tenants = Azure::Subscriptions::Mgmt::V2019_06_01::Tenants
Subscription = Azure::Subscriptions::Mgmt::V2020_09_01::Subscription
Operations = Azure::Subscriptions::Mgmt::V2020_09_01::Operations
AliasModel = Azure::Subscriptions::Mgmt::V2020_09_01::AliasModel
module Models
SubscriptionDefinition = Azure::Subscriptions::Mgmt::V2017_11_01_preview::Models::SubscriptionDefinition
SubscriptionDefinitionList = Azure::Subscriptions::Mgmt::V2017_11_01_preview::Models::SubscriptionDefinitionList
SubscriptionCreationParameters = Azure::Subscriptions::Mgmt::V2018_03_01_preview::Models::SubscriptionCreationParameters
OfferType = Azure::Subscriptions::Mgmt::V2018_03_01_preview::Models::OfferType
SubscriptionOperation = Azure::Subscriptions::Mgmt::V2018_11_01_preview::Models::SubscriptionOperation
SubscriptionOperationListResult = Azure::Subscriptions::Mgmt::V2018_11_01_preview::Models::SubscriptionOperationListResult
AdPrincipal = Azure::Subscriptions::Mgmt::V2018_11_01_preview::Models::AdPrincipal
ModernSubscriptionCreationParameters = Azure::Subscriptions::Mgmt::V2018_11_01_preview::Models::ModernSubscriptionCreationParameters
SubscriptionCreationResult = Azure::Subscriptions::Mgmt::V2018_11_01_preview::Models::SubscriptionCreationResult
SubscriptionListResult = Azure::Subscriptions::Mgmt::V2019_06_01::Models::SubscriptionListResult
TenantIdDescription = Azure::Subscriptions::Mgmt::V2019_06_01::Models::TenantIdDescription
LocationListResult = Azure::Subscriptions::Mgmt::V2019_06_01::Models::LocationListResult
TenantListResult = Azure::Subscriptions::Mgmt::V2019_06_01::Models::TenantListResult
ManagedByTenant = Azure::Subscriptions::Mgmt::V2019_06_01::Models::ManagedByTenant
Location = Azure::Subscriptions::Mgmt::V2019_06_01::Models::Location
Subscription = Azure::Subscriptions::Mgmt::V2019_06_01::Models::Subscription
SubscriptionPolicies = Azure::Subscriptions::Mgmt::V2019_06_01::Models::SubscriptionPolicies
SubscriptionState = Azure::Subscriptions::Mgmt::V2019_06_01::Models::SubscriptionState
SpendingLimit = Azure::Subscriptions::Mgmt::V2019_06_01::Models::SpendingLimit
Operation = Azure::Subscriptions::Mgmt::V2020_09_01::Models::Operation
ErrorResponse = Azure::Subscriptions::Mgmt::V2020_09_01::Models::ErrorResponse
OperationListResult = Azure::Subscriptions::Mgmt::V2020_09_01::Models::OperationListResult
CanceledSubscriptionId = Azure::Subscriptions::Mgmt::V2020_09_01::Models::CanceledSubscriptionId
PutAliasRequestProperties = Azure::Subscriptions::Mgmt::V2020_09_01::Models::PutAliasRequestProperties
EnabledSubscriptionId = Azure::Subscriptions::Mgmt::V2020_09_01::Models::EnabledSubscriptionId
PutAliasRequest = Azure::Subscriptions::Mgmt::V2020_09_01::Models::PutAliasRequest
OperationDisplay = Azure::Subscriptions::Mgmt::V2020_09_01::Models::OperationDisplay
PutAliasResponseProperties = Azure::Subscriptions::Mgmt::V2020_09_01::Models::PutAliasResponseProperties
RenamedSubscriptionId = Azure::Subscriptions::Mgmt::V2020_09_01::Models::RenamedSubscriptionId
PutAliasResponse = Azure::Subscriptions::Mgmt::V2020_09_01::Models::PutAliasResponse
ErrorResponseBody = Azure::Subscriptions::Mgmt::V2020_09_01::Models::ErrorResponseBody
PutAliasListResult = Azure::Subscriptions::Mgmt::V2020_09_01::Models::PutAliasListResult
SubscriptionName = Azure::Subscriptions::Mgmt::V2020_09_01::Models::SubscriptionName
Workload = Azure::Subscriptions::Mgmt::V2020_09_01::Models::Workload
ProvisioningState = Azure::Subscriptions::Mgmt::V2020_09_01::Models::ProvisioningState
end
class SubscriptionsManagementClass
attr_reader :subscription_definitions_operation_metadata, :subscription_definitions, :subscription_operations, :subscription_operation_operations, :subscription_factory, :subscriptions, :tenants, :subscription, :operations, :alias_model, :configurable, :base_url, :options, :model_classes
def initialize(configurable, base_url=nil, options=nil)
@configurable, @base_url, @options = configurable, base_url, options
@client_0 = Azure::Subscriptions::Mgmt::V2016_06_01::SubscriptionClient.new(configurable.credentials, base_url, options)
if(@client_0.respond_to?(:subscription_id))
@client_0.subscription_id = configurable.subscription_id
end
add_telemetry(@client_0)
@client_1 = Azure::Subscriptions::Mgmt::V2017_11_01_preview::SubscriptionDefinitionsClient.new(configurable.credentials, base_url, options)
if(@client_1.respond_to?(:subscription_id))
@client_1.subscription_id = configurable.subscription_id
end
add_telemetry(@client_1)
@subscription_definitions_operation_metadata = @client_1.subscription_definitions_operation_metadata
@subscription_definitions = @client_1.subscription_definitions
@client_2 = Azure::Subscriptions::Mgmt::V2018_03_01_preview::SubscriptionClient.new(configurable.credentials, base_url, options)
if(@client_2.respond_to?(:subscription_id))
@client_2.subscription_id = configurable.subscription_id
end
add_telemetry(@client_2)
@subscription_operations = @client_2.subscription_operations
@client_3 = Azure::Subscriptions::Mgmt::V2018_11_01_preview::SubscriptionClient.new(configurable.credentials, base_url, options)
if(@client_3.respond_to?(:subscription_id))
@client_3.subscription_id = configurable.subscription_id
end
add_telemetry(@client_3)
@subscription_operation_operations = @client_3.subscription_operation_operations
@subscription_factory = @client_3.subscription_factory
@client_4 = Azure::Subscriptions::Mgmt::V2019_03_01_preview::SubscriptionClient.new(configurable.credentials, base_url, options)
if(@client_4.respond_to?(:subscription_id))
@client_4.subscription_id = configurable.subscription_id
end
add_telemetry(@client_4)
@client_5 = Azure::Subscriptions::Mgmt::V2019_06_01::SubscriptionClient.new(configurable.credentials, base_url, options)
if(@client_5.respond_to?(:subscription_id))
@client_5.subscription_id = configurable.subscription_id
end
add_telemetry(@client_5)
@subscriptions = @client_5.subscriptions
@tenants = @client_5.tenants
@client_6 = Azure::Subscriptions::Mgmt::V2020_09_01::SubscriptionClient.new(configurable.credentials, base_url, options)
if(@client_6.respond_to?(:subscription_id))
@client_6.subscription_id = configurable.subscription_id
end
add_telemetry(@client_6)
@subscription = @client_6.subscription
@operations = @client_6.operations
@alias_model = @client_6.alias_model
@model_classes = ModelClasses.new
end
def add_telemetry(client)
profile_information = "Profiles/azure_sdk/#{Azure::VERSION}/Latest/Subscriptions/Mgmt"
client.add_user_agent_information(profile_information)
end
def method_missing(method, *args)
if @client_6.respond_to?method
@client_6.send(method, *args)
elsif @client_5.respond_to?method
@client_5.send(method, *args)
elsif @client_4.respond_to?method
@client_4.send(method, *args)
elsif @client_3.respond_to?method
@client_3.send(method, *args)
elsif @client_2.respond_to?method
@client_2.send(method, *args)
elsif @client_1.respond_to?method
@client_1.send(method, *args)
elsif @client_0.respond_to?method
@client_0.send(method, *args)
else
super
end
end
class ModelClasses
def subscription_definition
Azure::Subscriptions::Mgmt::V2017_11_01_preview::Models::SubscriptionDefinition
end
def subscription_definition_list
Azure::Subscriptions::Mgmt::V2017_11_01_preview::Models::SubscriptionDefinitionList
end
def subscription_creation_parameters
Azure::Subscriptions::Mgmt::V2018_03_01_preview::Models::SubscriptionCreationParameters
end
def offer_type
Azure::Subscriptions::Mgmt::V2018_03_01_preview::Models::OfferType
end
def subscription_operation
Azure::Subscriptions::Mgmt::V2018_11_01_preview::Models::SubscriptionOperation
end
def subscription_operation_list_result
Azure::Subscriptions::Mgmt::V2018_11_01_preview::Models::SubscriptionOperationListResult
end
def ad_principal
Azure::Subscriptions::Mgmt::V2018_11_01_preview::Models::AdPrincipal
end
def modern_subscription_creation_parameters
Azure::Subscriptions::Mgmt::V2018_11_01_preview::Models::ModernSubscriptionCreationParameters
end
def subscription_creation_result
Azure::Subscriptions::Mgmt::V2018_11_01_preview::Models::SubscriptionCreationResult
end
def subscription_list_result
Azure::Subscriptions::Mgmt::V2019_06_01::Models::SubscriptionListResult
end
def tenant_id_description
Azure::Subscriptions::Mgmt::V2019_06_01::Models::TenantIdDescription
end
def location_list_result
Azure::Subscriptions::Mgmt::V2019_06_01::Models::LocationListResult
end
def tenant_list_result
Azure::Subscriptions::Mgmt::V2019_06_01::Models::TenantListResult
end
def managed_by_tenant
Azure::Subscriptions::Mgmt::V2019_06_01::Models::ManagedByTenant
end
def location
Azure::Subscriptions::Mgmt::V2019_06_01::Models::Location
end
def subscription
Azure::Subscriptions::Mgmt::V2019_06_01::Models::Subscription
end
def subscription_policies
Azure::Subscriptions::Mgmt::V2019_06_01::Models::SubscriptionPolicies
end
def subscription_state
Azure::Subscriptions::Mgmt::V2019_06_01::Models::SubscriptionState
end
def spending_limit
Azure::Subscriptions::Mgmt::V2019_06_01::Models::SpendingLimit
end
def operation
Azure::Subscriptions::Mgmt::V2020_09_01::Models::Operation
end
def error_response
Azure::Subscriptions::Mgmt::V2020_09_01::Models::ErrorResponse
end
def operation_list_result
Azure::Subscriptions::Mgmt::V2020_09_01::Models::OperationListResult
end
def canceled_subscription_id
Azure::Subscriptions::Mgmt::V2020_09_01::Models::CanceledSubscriptionId
end
def put_alias_request_properties
Azure::Subscriptions::Mgmt::V2020_09_01::Models::PutAliasRequestProperties
end
def enabled_subscription_id
Azure::Subscriptions::Mgmt::V2020_09_01::Models::EnabledSubscriptionId
end
def put_alias_request
Azure::Subscriptions::Mgmt::V2020_09_01::Models::PutAliasRequest
end
def operation_display
Azure::Subscriptions::Mgmt::V2020_09_01::Models::OperationDisplay
end
def put_alias_response_properties
Azure::Subscriptions::Mgmt::V2020_09_01::Models::PutAliasResponseProperties
end
def renamed_subscription_id
Azure::Subscriptions::Mgmt::V2020_09_01::Models::RenamedSubscriptionId
end
def put_alias_response
Azure::Subscriptions::Mgmt::V2020_09_01::Models::PutAliasResponse
end
def error_response_body
Azure::Subscriptions::Mgmt::V2020_09_01::Models::ErrorResponseBody
end
def put_alias_list_result
Azure::Subscriptions::Mgmt::V2020_09_01::Models::PutAliasListResult
end
def subscription_name
Azure::Subscriptions::Mgmt::V2020_09_01::Models::SubscriptionName
end
def workload
Azure::Subscriptions::Mgmt::V2020_09_01::Models::Workload
end
def provisioning_state
Azure::Subscriptions::Mgmt::V2020_09_01::Models::ProvisioningState
end
end
end
end
end
end
| 53.476563 | 296 | 0.707597 |
5ded6563959c7c67ea0dc5292c178bf99407e698 | 359 | module FidorApi
module StandingOrder
autoload :Email, 'fidor_api/standing_order/email'
autoload :Phone, 'fidor_api/standing_order/phone'
autoload :Sepa, 'fidor_api/standing_order/sepa'
autoload :Base, 'fidor_api/standing_order/base'
autoload :Generic, 'fidor_api/standing_order/generic'
end
end
| 35.9 | 63 | 0.679666 |
1ad2ef859079b254dbca6e9fa63a70482d4ea9f0 | 169 | require 'sinatra/base'
require 'json'
class Server < Sinatra::Base
post '/echo' do
payload = JSON.parse(request.body.read)
"Hello event #{payload}"
end
end
| 16.9 | 43 | 0.680473 |
211bb23ff87bf6ddf7be3e285367b1e6e2ae6dfd | 682 | require 'rails_helper'
describe Event do
describe '.new' do
it 'should create a new event with a valid date and type' do
event = Event.new(2.days.ago, 'CaseFile')
expect(event).to be_instance_of(Event)
expect(event).to be_valid
end
it 'should raise an error if the date is in the future' do
e = Event.new(2.days.from_now, 'CaseFile')
expect(e).not_to be_valid
expect(e.errors).to eq ['Invalid Date']
end
it 'should raise an error if the event type is invalid' do
e = Event.new(Date.today, 'CaseFileXXX')
expect(e).not_to be_valid
expect(e.errors).to eq ['Invalid Event Type']
end
end
end | 27.28 | 64 | 0.646628 |
e9a70bc06fc345afb821bd373db340f4c30f9585 | 2,095 | #
# Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
#
# 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.
#
Puppet::Type.type(:vni_interface).provide(:vni_interface) do
desc "Provider for management of VNI interfaces for Oracle Solaris"
confine :operatingsystem => [:solaris]
defaultfor :osfamily => :solaris, :kernelrelease => ['5.11', '5.12']
commands :ipadm => '/usr/sbin/ipadm'
def self.instances
vnis = []
ipadm("show-if", "-p", "-o", "IFNAME,CLASS").split(
"\n").each do |line|
ifname, ifclass = line.split(":", 2)
next if ifclass != "vni"
vnis << new(:name => ifname, :ensure => :present)
end
vnis
end
def add_options
options = []
if @resource[:temporary] == :true
options << "-t"
end
options
end
def exists?
p = exec_cmd(command(:ipadm), "show-if", "-p", "-o", "IFNAME,CLASS",
@resource[:name])
if p[:exit] == 1
return false
end
ifname, ifclass = p[:out].strip().split(":", 2)
if ifclass == "vni"
return true
end
# for all other cases, return false
return false
end
def create
ipadm('create-vni', add_options, @resource[:name])
end
def destroy
ipadm('delete-vni', @resource[:name])
end
def exec_cmd(*cmd)
output = Puppet::Util::Execution.execute(cmd, :failonfail => false)
{:out => output, :exit => $CHILD_STATUS.exitstatus}
end
end
| 29.507042 | 78 | 0.597613 |
6124429ab50b52b19ef4e45a47162cf7c673d3ae | 328 | module MicroServiceServer
class Engine < ::Rails::Engine
isolate_namespace MicroServiceServer
initializer :append_migrations do |app|
unless app.root.to_s.match(root.to_s)
config.paths["db/migrate"].expanded.each do |expanded_path|
app.config.paths["db/migrate"] << expanded_path
end
end
end
end
end
| 23.428571 | 63 | 0.737805 |
21413e9ba01e08a2622dc437c9c4d74b6aab99b6 | 732 | class Wso2am300 < Formula
desc "WSO2 API Manager 3.0.0"
homepage "https://wso2.com/api-management/"
url "https://dl.bintray.com/wso2/binary/wso2am-3.0.0.zip"
sha256 "80dd6eaf9704eb77f2cba3805113aa40120500e3e31cd0592d89473a65ab0ab2"
bottle :unneeded
depends_on :java => "1.8"
def install
product = "wso2am"
version = "3.0.0"
puts "Installing WSO2 API Manager #{version}..."
bin.install "bin/#{product}-#{version}" => "#{product}-#{version}"
libexec.install Dir["*"]
bin.env_script_all_files(libexec/"bin", Language::Java.java_home_env("1.8"))
puts "Installation is completed."
puts "\nRun #{product}-#{version} to start WSO2 API Manager #{version}."
puts "\ncheers!!"
end
end
| 29.28 | 80 | 0.678962 |
e819988efeee5cde0b176f07d33e20a0a48fca54 | 41 | module SimpleElo
VERSION = "0.0.1"
end
| 10.25 | 19 | 0.682927 |
11046b74321c5ab309af7d0b43bd653f2c74276c | 95 | require 'spree_core'
require 'spree_api_auth/controller_setup'
require 'spree_api_auth/engine'
| 23.75 | 41 | 0.852632 |
aca9d42869b7442497ea21d3f707412599ae3364 | 123 | require 'test_helper'
class UsedTokenTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 15.375 | 45 | 0.707317 |
79de26a2de3b061b92cb881949d1e003281e5223 | 167 | shared_examples 'collection::certbot' do
include_examples 'python::toolchain'
include_examples 'misc::letsencrypt'
include_examples 'certbot::layout'
end
| 23.857143 | 40 | 0.766467 |
f72c93b4435dc0514386c6f3ddde4e485ae1275a | 12,904 | # Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
# config.secret_key = '34827b1d73f18ea65515c8c9f03ad33d14d6dcc35e8ad1325b6a5ac8202895b50e31ba82a117507f5af8b2918b00a910cf29d254d449d3463e2de24363a1f0a6'
config.secret_key = '9e5b92d9a56d4e8c7a392a940f3f8cdb240c2e6f6ce802e91d19f290d7027e367e64c7272cf78842bcbc98c040ae00be29bf7554a93b29f63098cae34fd78344'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = '[email protected]'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# encryptor), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = '11e925f735fb41fc7139284cae6dd18c6f851022dd2a6ffc3d1c6948855ad249e5cecf78c7ec4ded98574bf59eeb266fe99355f68f29ffa88b725c48ed1d13f8'
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = true
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 8..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^@]+@[^@]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_auth_token_on_timeout = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = false
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
end
| 49.440613 | 154 | 0.752635 |
1ab8748773c7edfaecbfa86f7acb7e66c56bef65 | 1,922 | Pod::Spec.new do |s|
s.name = 'CocoaAsyncSocket'
s.version = '7.6.0'
s.license = { :type => 'public domain', :text => <<-LICENSE
Public Domain License
The CocoaAsyncSocket project is in the public domain.
The original TCP version (AsyncSocket) was created by Dustin Voss in January 2003.
Updated and maintained by Deusty LLC and the Apple development community.
LICENSE
}
s.summary = 'Asynchronous socket networking library for Mac and iOS.'
s.homepage = 'https://github.com/robbiehanson/CocoaAsyncSocket'
s.authors = 'Dustin Voss', { 'Robbie Hanson' => '[email protected]' }
s.source = { :git => 'https://github.com/robbiehanson/CocoaAsyncSocket.git',
:tag => "#{s.version}" }
s.description = 'CocoaAsyncSocket supports TCP and UDP. The AsyncSocket class is for TCP, and the AsyncUdpSocket class is for UDP. ' \
'AsyncSocket is a TCP/IP socket networking library that wraps CFSocket and CFStream. It offers asynchronous ' \
'operation, and a native Cocoa class complete with delegate support or use the GCD variant GCDAsyncSocket. ' \
'AsyncUdpSocket is a UDP/IP socket networking library that wraps CFSocket. It works almost exactly like the TCP ' \
'version, but is designed specifically for UDP. This includes queued non-blocking send/receive operations, full ' \
'delegate support, run-loop based, self-contained class, and support for IPv4 and IPv6.'
s.source_files = 'Source/GCD/*.{h,m}'
s.requires_arc = true
# dispatch_queue_set_specific() is available in OS X v10.7+ and iOS 5.0+
s.ios.deployment_target = '5.0'
s.tvos.deployment_target = '9.0'
s.osx.deployment_target = '10.7'
s.ios.frameworks = 'CFNetwork', 'Security'
s.tvos.frameworks = 'CFNetwork', 'Security'
s.osx.frameworks = 'CoreServices', 'Security'
end
| 48.05 | 136 | 0.679501 |
18f6ffb2ba6aa3cba132d23e5ba9a8f5d3eb912f | 33 | require 'flipper/adapters/consul' | 33 | 33 | 0.848485 |
6a9895c3dc24630231c9f2ec39d7b3c522737871 | 2,794 | #
# Cookbook Name:: omnibus
# Recipe:: _omnibus_toolchain
#
# Copyright 2015, Chef Software, 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.
#
return unless omnibus_toolchain_enabled?
# These are sort of 'global' variables, independent of platform
toolchain_name = node['omnibus']['toolchain_name']
toolchain_version = node['omnibus']['toolchain_version']
if File.exist?("/opt/#{toolchain_name}/version-manifest.json") &&
(JSON.parse(File.read("/opt/#{toolchain_name}/version-manifest.json"))['build_version'] == toolchain_version)
Chef::Log.info("`#{toolchain_name}` is already installed at version #{toolchain_version}.")
else
install_options = ''
if solaris_10?
# create a nocheck file for automated install
file '/var/sadm/install/admin/auto-install' do
content <<-EOH.flush
mail=
instance=overwrite
partial=nocheck
runlevel=nocheck
idepend=nocheck
space=ask
setuid=nocheck
conflict=nocheckit
action=nocheck
basedir=default
EOH
owner 'root'
group 'root'
mode '0444'
end
case node['kernel']['machine']
when 'i86pc'
package_url = "https://chef-releng.s3.amazonaws.com/omnibus/omnibus-toolchain/#{toolchain_name}-#{toolchain_version}-1.i86pc.solaris"
when 'sun4v', 'sun4u'
package_url = "https://chef-releng.s3.amazonaws.com/omnibus/omnibus-toolchain/#{toolchain_name}-#{toolchain_version}-1.sun4v.solaris"
end
install_options = '-a auto-install'
elsif aix?
package_url = "http://chef-releng.s3.amazonaws.com/omnibus/omnibus-toolchain/#{toolchain_name}-#{toolchain_version}-1.powerpc.bff"
elsif nexus?
package_url = "http://chef-releng.s3.amazonaws.com/omnibus/omnibus-toolchain/#{toolchain_name}-#{toolchain_version}-1.nexus7.x86_64.rpm"
else
Chef::Application.fatal!("I don't know how to install #{node['omnibus']['toolchain_name']} on this platform!", 1)
end
package_path = File.join(Chef::Config[:file_cache_path], File.basename(package_url))
remote_file package_path do
source package_url
action :create_if_missing
end
package node['omnibus']['toolchain_name'] do
provider Chef::Provider::Package::Yum if nexus?
source package_path
options install_options
end
end
| 34.493827 | 140 | 0.714746 |
5db5b1da971fd3c3f83a1fa2a94a592180c79889 | 1,118 | class ApplicationController < ActionController::Base
before_action :set_paper_trail_whodunnit
include ControllerHelper
include ActionView::Helpers::OutputSafetyHelper
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :null_session
before_filter :journal_user, :check_notices
def journal_user
logger.info "JOURNAL: url=#{request.url}/#{request.method}; user_id=#{current_user ? current_user.id : 'none'}"
end
def check_notices
return unless current_user
return if request[:controller] =~ /\/admin\//
#FIXME: each category should be processed separately in outstanding code
notices = Core::Notice.where(sourceable: current_user, category: 1)
return if notices.count==0
list=[]
notices.each do |note|
list << note.message
#next if flash[:'alert-badjobs'] && flash[:'alert-badjobs'].include?(text)
#job=note.linkable
end
text = "#{notices.count==1 ? t('bad_job') : t('bad_jobs')} #{list.join '; '}"
flash.now[:'alert-badjobs'] = raw text
end
end
| 31.055556 | 115 | 0.702147 |
e954ebb36f510b8ff0963fc22b92b20190cacf6c | 935 | # encoding: utf-8
# frozen_string_literal: true
module YandexSpeechApi
module MP3_Player
class Linux_MP3_Player < MP3_Player::Base # no-doc
private
# @return [String]
# Path to +mpg123+ application
attr_reader :path_to_executable
##
# Check requirements.
#
# @exception ApplicationNotInstalled
# Raised if +mpg123+ not found.
def validate_requirements
@path_to_executable = Helpers::find_executable 'mpg123'
if path_to_executable.nil?
raise ApplicationNotInstalled , 'mpq123'
end
end
##
# no-doc
def play_mp3
`#{path_to_executable} -q '#{filename}'`
end
##
# Raised when necessary linux program not found.
class ApplicationNotInstalled < YandexSpeechError
def initialize(name); super "Program '#{name}' not found!" end; end
end # class Linux_MP3_Player
end # module MP3_Player
end # module YandexSpeechApi
| 22.261905 | 73 | 0.677005 |
62a40d5f4f712f73d7c95aed493c03857afa10e9 | 976 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
describe port(22) do
it { should be_listening.on('0.0.0.0') }
end
describe port(80) do
it { should be_listening.on('0.0.0.0') }
end
describe port(5432) do
it { should be_listening.on('127.0.0.1') }
it { should_not be_listening.on('0.0.0.0') }
end
describe port(8069) do
it { should be_listening.on('127.0.0.1') }
it { should_not be_listening.on('0.0.0.0') }
end
| 28.705882 | 74 | 0.721311 |
285145f8fa399fae7d495b164c5ec068e71e010d | 358 | leslie = User.create(name: "Leslie", email: "[email protected]", password: "password1")
dave = User.create(name: "Dave", email: "[email protected]", password: "password2")
leslie1 = leslie.stock_boxes.create(name: "Leslie1")
dave1 = dave.stock_boxes.create(name: "Dave1")
torso = leslie1.stocks.create(name: "torso")
snake = dave1.stocks.create(name: "snake")
| 39.777778 | 87 | 0.72067 |
1d80c93cf830fb2f7fd7c366038ca8384b30de2e | 17,788 |
require_relative 'ui_skeleton_editor'
class SkeletonEditorDialog < Qt::Dialog
GREY_PEN = Qt::Pen.new(Qt::Brush.new(Qt::Color.new(128, 128, 128)), 2)
RED_PEN = Qt::Pen.new(Qt::Brush.new(Qt::Color.new(224, 16, 16)), 2)
GREEN_PEN = Qt::Pen.new(Qt::Brush.new(Qt::Color.new(16, 224, 16)), 2)
BLUE_PEN = Qt::Pen.new(Qt::Brush.new(Qt::Color.new(16, 16, 224)), 2)
WHITE_PEN = Qt::Pen.new(Qt::Brush.new(Qt::Color.new(255, 255, 255)), 2)
attr_reader :game, :fs
slots "pose_changed_no_tween(int)"
slots "toggle_show_skeleton(int)"
slots "toggle_show_hitboxes(int)"
slots "toggle_show_points(int)"
slots "animation_changed(int)"
slots "animation_keyframe_changed_no_tween(int)"
slots "toggle_animation_paused()"
slots "advance_tweenframe()"
slots "export_to_spriter()"
slots "button_box_clicked(QAbstractButton*)"
def initialize(parent, sprite_info, fs, renderer)
super(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint)
@sprite_info = sprite_info
@fs = fs
@renderer = renderer
@ui = Ui_SkeletonEditor.new
@ui.setup_ui(self)
@skeleton_graphics_scene = Qt::GraphicsScene.new
@skeleton_graphics_scene.setBackgroundBrush(ClickableGraphicsScene::BACKGROUND_BRUSH)
@ui.skeleton_graphics_view.setScene(@skeleton_graphics_scene)
@animation_timer = Qt::Timer.new()
@animation_timer.setSingleShot(true)
connect(@animation_timer, SIGNAL("timeout()"), self, SLOT("advance_tweenframe()"))
set_animation_paused(true)
connect(@ui.pose_index, SIGNAL("activated(int)"), self, SLOT("pose_changed_no_tween(int)"))
connect(@ui.show_skeleton, SIGNAL("stateChanged(int)"), self, SLOT("toggle_show_skeleton(int)"))
connect(@ui.show_hitboxes, SIGNAL("stateChanged(int)"), self, SLOT("toggle_show_hitboxes(int)"))
connect(@ui.show_points, SIGNAL("stateChanged(int)"), self, SLOT("toggle_show_points(int)"))
connect(@ui.animation_index, SIGNAL("activated(int)"), self, SLOT("animation_changed(int)"))
connect(@ui.seek_slider, SIGNAL("valueChanged(int)"), self, SLOT("animation_keyframe_changed_no_tween(int)"))
connect(@ui.toggle_paused_button, SIGNAL("clicked()"), self, SLOT("toggle_animation_paused()"))
connect(@ui.spriter_export, SIGNAL("clicked()"), self, SLOT("export_to_spriter()"))
connect(@ui.buttonBox, SIGNAL("clicked(QAbstractButton*)"), self, SLOT("button_box_clicked(QAbstractButton*)"))
@ui.spriter_export.hide()
self.show()
self.load_skeleton()
end
def load_skeleton
@skeleton = SpriteSkeleton.new(@sprite_info.skeleton_file, @fs)
chunky_frames, @min_x, @min_y, _, _, _, _, _ = @renderer.render_sprite(@sprite_info)
@pixmap_frames = chunky_frames.map do |chunky_image|
pixmap = Qt::Pixmap.new
blob = chunky_image.to_blob
pixmap.loadFromData(blob, blob.length)
pixmap
end
@ui.skeleton_file_name.text = @skeleton.skeleton_file
@ui.pose_index.clear()
@skeleton.poses.each_index do |i|
@ui.pose_index.addItem("%02X" % i)
end
pose_changed(0)
@ui.animation_index.clear()
@skeleton.animations.each_with_index do |animation, i|
@ui.animation_index.addItem("%02X" % i)
end
animation_changed(0)
end
def pose_changed_no_tween(i)
@current_pose_index = i
pose = @skeleton.poses[@current_pose_index]
@current_pose_joint_states = initialize_joint_states(pose)
@tweening_progress = 0.0
@previous_pose = nil
update_drawn_joints()
@ui.pose_index.setCurrentIndex(i)
end
def pose_changed(i)
if @current_pose_joint_states
@previous_pose = @skeleton.poses[@current_pose_index]
@previous_pose_joint_state = @current_pose_joint_states
@current_pose_index = i
pose = @skeleton.poses[@current_pose_index]
@current_pose_joint_states = initialize_joint_states(pose)
@tweening_progress = 0.0
else
@current_pose_index = i
pose = @skeleton.poses[@current_pose_index]
@current_pose_joint_states = initialize_joint_states(pose)
@previous_pose_joint_state = @current_pose_joint_states
@previous_pose = @skeleton.poses[@current_pose_index]
@tweening_progress = 0.0
end
update_drawn_joints()
@ui.pose_index.setCurrentIndex(i)
end
def animation_changed(i)
@current_animation_index = i
@animation_timer.stop()
@ui.seek_slider.value = 0
@current_animation_keyframe_index = 0
@current_animation = @skeleton.animations[@current_animation_index]
if @current_animation.nil?
@ui.seek_slider.enabled = false
@ui.toggle_paused_button.enabled = false
return
end
@ui.seek_slider.enabled = true
@ui.seek_slider.minimum = 0
@ui.seek_slider.maximum = @current_animation.keyframes.length-1
@ui.toggle_paused_button.enabled = true
if @current_animation.keyframes.length > 0
animation_keyframe_changed(0)
start_animation()
else
# Animation with no keyframes
end
end
def initialize_joint_states(pose)
joint_states_for_pose = []
joint_states_to_initialize = []
@skeleton.joints.each_with_index do |joint, joint_index|
joint_state = JointState.new
joint_states_for_pose << joint_state
if joint.parent_id == 0xFF
joint_states_to_initialize << joint_state
end
end
while joint_states_to_initialize.any?
joint_state = joint_states_to_initialize.shift()
joint_index = joint_states_for_pose.index(joint_state)
joint_change = pose.joint_changes[joint_index]
joint = @skeleton.joints[joint_index]
if joint.parent_id == 0xFF
joint_state.x_pos = 0
joint_state.y_pos = 0
joint_state.inherited_rotation = 0
else
parent_joint = @skeleton.joints[joint.parent_id]
parent_joint_change = pose.joint_changes[joint.parent_id]
parent_joint_state = joint_states_for_pose[joint.parent_id]
joint_state.x_pos = parent_joint_state.x_pos
joint_state.y_pos = parent_joint_state.y_pos
joint_state.inherited_rotation = parent_joint_change.rotation
if parent_joint.copy_parent_visual_rotation && parent_joint.parent_id != 0xFF
joint_state.inherited_rotation += parent_joint_state.inherited_rotation
end
connected_rotation_in_degrees = joint_state.inherited_rotation / 182.0
offset_angle = connected_rotation_in_degrees
offset_angle += 90 * joint.positional_rotation
offset_angle_in_radians = offset_angle * Math::PI / 180
joint_state.x_pos += joint_change.distance*Math.cos(offset_angle_in_radians)
joint_state.y_pos += joint_change.distance*Math.sin(offset_angle_in_radians)
end
child_joints = @skeleton.joints.select{|joint| joint.parent_id == joint_index}
child_joint_indexes = child_joints.map{|joint| @skeleton.joints.index(joint)}
joint_states_to_initialize += child_joint_indexes.map{|joint_index| joint_states_for_pose[joint_index]}
end
joint_states_for_pose
end
def tween_poses(previous_pose, next_pose, tweening_progress)
tweened_pose = Pose.new
previous_pose.joint_changes.each_with_index do |prev_joint_change, joint_index|
next_joint_change = next_pose.joint_changes[joint_index]
prev_multiplier = 1.0 - tweening_progress
next_multiplier = tweening_progress
tweened_rotation = merge_two_angles(prev_joint_change.rotation, next_joint_change.rotation, prev_multiplier, next_multiplier)
tweened_distance = prev_joint_change.distance*prev_multiplier + next_joint_change.distance*next_multiplier
tweened_joint_change_data = [tweened_rotation, tweened_distance, prev_joint_change.new_frame_id].pack("vcC")
tweened_joint_change = JointChange.new(tweened_joint_change_data)
tweened_pose.joint_changes << tweened_joint_change
end
tweened_states = initialize_joint_states(tweened_pose)
return [tweened_states, tweened_pose]
end
def merge_two_angles(a, b, a_multiplier, b_multiplier)
if b - a >= 0x8000
b -= 0x10000
elsif a - b >= 0x8000
a -= 0x10000
end
a*a_multiplier + b*b_multiplier
end
def animation_keyframe_changed(i)
@current_animation_keyframe_index = i
@current_animation_tweenframe_index = 0
@current_keyframe = @current_animation.keyframes[@current_animation_keyframe_index]
pose_changed(@current_keyframe.pose_id)
animation_tweenframe_changed(0)
@ui.seek_slider.value = @current_animation_keyframe_index
millisecond_delay = (1 / 60.0 * 1000).round
@animation_timer.start(millisecond_delay)
end
def animation_keyframe_changed_no_tween(i, force=false)
return if i == @current_animation_keyframe_index && @ui.seek_slider.value == @current_animation_keyframe_index && !force
@current_animation_keyframe_index = i
@current_animation_tweenframe_index = 0
@current_keyframe = @current_animation.keyframes[@current_animation_keyframe_index]
pose_changed_no_tween(@current_keyframe.pose_id)
animation_tweenframe_changed(0)
@ui.seek_slider.value = @current_animation_keyframe_index
millisecond_delay = (1 / 60.0 * 1000).round
@animation_timer.start(millisecond_delay)
end
def animation_tweenframe_changed(i)
@current_animation_tweenframe_index = i
@tweening_progress = @current_animation_tweenframe_index.to_f / @current_keyframe.length_in_frames
#@ui.frame_delay.text = "%04X" % frame_delay.delay
update_drawn_joints()
end
def advance_tweenframe
if @current_animation && !@animation_paused
if @current_animation_tweenframe_index >= @current_keyframe.length_in_frames
advance_keyframe()
millisecond_delay = (1 / 60.0 * 1000).round
@animation_timer.start(millisecond_delay)
else
# Advance by 3 frames at a time, to display the animation at 20fps.
# This is because displaying at 60fps causes it to lag and play much slower than it's supposed to.
# If there are less than 3 frames left in this keyframe, only advance by however many frames are left.
max_tweenframes_to_advance = @current_keyframe.length_in_frames - @current_animation_tweenframe_index
num_tweenframes_to_advance = [3, max_tweenframes_to_advance].min
animation_tweenframe_changed(@current_animation_tweenframe_index+num_tweenframes_to_advance)
millisecond_delay = (num_tweenframes_to_advance / 60.0 * 1000).round
@animation_timer.start(millisecond_delay)
end
end
end
def set_animation_paused(paused)
@animation_paused = paused
if @animation_paused
@ui.toggle_paused_button.text = "Play"
else
@ui.toggle_paused_button.text = "Pause"
start_animation()
end
end
def start_animation
millisecond_delay = (1 / 60.0 * 1000).round
@animation_timer.start(millisecond_delay)
end
def toggle_animation_paused
set_animation_paused(!@animation_paused)
end
def advance_keyframe
if @current_animation && !@animation_paused
if @current_animation_keyframe_index >= @current_animation.keyframes.length-1
animation_keyframe_changed(0)
unless @ui.loop_animation.checked
set_animation_paused(true)
end
else
animation_keyframe_changed(@current_animation_keyframe_index+1)
end
end
end
def update_drawn_joints
@skeleton_graphics_scene.items.each do |item|
@skeleton_graphics_scene.removeItem(item)
end
next_pose = @skeleton.poses[@current_pose_index]
if @previous_pose
@current_tweened_joint_states, pose = tween_poses(@previous_pose, next_pose, @tweening_progress)
else
@current_tweened_joint_states = @current_pose_joint_states
pose = next_pose
end
@skeleton.joint_indexes_by_draw_order.each do |joint_index|
joint = @skeleton.joints[joint_index]
joint_change = pose.joint_changes[joint_index]
joint_state = @current_tweened_joint_states[joint_index]
next if joint.frame_id == 0xFF
rotation = joint_change.rotation
if joint.parent_id != 0xFF && joint.copy_parent_visual_rotation
rotation += joint_state.inherited_rotation
end
rotation_in_degrees = rotation/182.0
if joint_change.new_frame_id == 0xFF
frame_id = joint.frame_id
else
frame_id = joint_change.new_frame_id
end
pixmap = @pixmap_frames[frame_id]
graphics_item = Qt::GraphicsPixmapItem.new(pixmap)
graphics_item.setOffset(@min_x, @min_y)
graphics_item.setPos(joint_state.x_pos, joint_state.y_pos)
graphics_item.setRotation(rotation_in_degrees)
if joint.horizontal_flip && joint.vertical_flip
graphics_item.scale(-1, -1)
elsif joint.horizontal_flip
graphics_item.scale(-1, 1)
elsif joint.vertical_flip
graphics_item.scale(1, -1)
end
@skeleton_graphics_scene.addItem(graphics_item)
end
if @ui.show_skeleton.checked
@skeleton.joints.each_index do |joint_index|
joint = @skeleton.joints[joint_index]
joint_change = pose.joint_changes[joint_index]
joint_state = @current_tweened_joint_states[joint_index]
ellipse = @skeleton_graphics_scene.addEllipse(joint_state.x_pos-1, joint_state.y_pos-1, 3, 3, GREY_PEN)
ellipse.setZValue(1)
if joint.parent_id != 0xFF
parent_joint = @skeleton.joints[joint.parent_id]
parent_joint_state = @current_tweened_joint_states[joint.parent_id]
line = @skeleton_graphics_scene.addLine(joint_state.x_pos, joint_state.y_pos, parent_joint_state.x_pos, parent_joint_state.y_pos, GREY_PEN)
line.setZValue(1)
end
end
end
if @ui.show_hitboxes.checked
@skeleton.hitboxes.each do |hitbox|
joint = @skeleton.joints[hitbox.parent_joint_id]
joint_change = pose.joint_changes[hitbox.parent_joint_id]
joint_state = @current_tweened_joint_states[hitbox.parent_joint_id]
x_pos = joint_state.x_pos
y_pos = joint_state.y_pos
offset_angle = hitbox.rotation + joint_change.rotation
if joint.copy_parent_visual_rotation
offset_angle += joint_state.inherited_rotation
end
offset_angle_in_degrees = offset_angle / 182.0
offset_angle_in_radians = offset_angle_in_degrees * Math::PI / 180
x_pos += hitbox.distance*Math.cos(offset_angle_in_radians)
y_pos += hitbox.distance*Math.sin(offset_angle_in_radians)
hitbox_item = Qt::GraphicsRectItem.new
if hitbox.can_damage_player && hitbox.can_take_damage
hitbox_item.setPen(RED_PEN)
elsif hitbox.can_damage_player
hitbox_item.setPen(BLUE_PEN)
elsif hitbox.can_take_damage
hitbox_item.setPen(GREEN_PEN)
else
hitbox_item.setPen(WHITE_PEN)
end
hitbox_item.setRect(x_pos-hitbox.width/2, y_pos-hitbox.height/2, hitbox.width, hitbox.height)
hitbox_item.setTransformOriginPoint(hitbox_item.rect.center)
rotation_in_degrees = hitbox.rotation / 182.0
hitbox_item.setRotation(rotation_in_degrees)
hitbox_item.setZValue(1)
@skeleton_graphics_scene.addItem(hitbox_item)
end
end
if @ui.show_points.checked?
@skeleton.points.each do |point|
joint = @skeleton.joints[point.parent_joint_id]
joint_change = pose.joint_changes[point.parent_joint_id]
joint_state = @current_tweened_joint_states[point.parent_joint_id]
x_pos = joint_state.x_pos
y_pos = joint_state.y_pos
offset_angle = point.rotation + joint_change.rotation
if joint.copy_parent_visual_rotation
offset_angle += joint_state.inherited_rotation
end
offset_angle_in_degrees = offset_angle / 182.0
offset_angle_in_radians = offset_angle_in_degrees * Math::PI / 180
x_pos += point.distance*Math.cos(offset_angle_in_radians)
y_pos += point.distance*Math.sin(offset_angle_in_radians)
ellipse = @skeleton_graphics_scene.addEllipse(x_pos, y_pos, 3, 3, RED_PEN)
ellipse.setZValue(1)
end
end
end
def toggle_show_skeleton(checked)
update_drawn_joints()
end
def toggle_show_hitboxes(checked)
update_drawn_joints()
end
def toggle_show_points(checked)
update_drawn_joints()
end
def skeleton_name
skeleton_name = @sprite_info.skeleton_file[:name]
if skeleton_name =~ /\.jnt$/
skeleton_name = skeleton_name[0..-5]
end
return skeleton_name
end
def export_to_spriter
output_folder = "./spriter_skeletons/#{skeleton_name}"
FileUtils.mkdir_p(output_folder)
SpriterInterface.export(output_folder, skeleton_name, @skeleton, @sprite_info, @fs, @renderer)
Qt::MessageBox.warning(self,
"Exported to Spriter",
"This skeleton has been exported in Spriter's format to the folder #{output_folder}"
)
rescue SpriterInterface::ExportError => e
Qt::MessageBox.warning(self,
"Failed to export to Spriter",
e.message
)
end
def button_box_clicked(button)
if @ui.buttonBox.standardButton(button) == Qt::DialogButtonBox::Apply
end
end
def inspect; to_s; end
end
class JointState
attr_accessor :x_pos,
:y_pos,
:inherited_rotation
end
| 35.363817 | 149 | 0.703733 |
e23eb1b0e682cb57336c5a23209d324545035d23 | 1,177 | class Api::ConfirmationsController < ApplicationController
def create
@confirmation = Confirmation.new(confirmation_params)
@confirmation.user_id = current_user.id
@home = Home.find(confirmation_params[:home_id])
start_date = confirmation_params[:start_date].to_date
end_date = confirmation_params[:end_date].to_date
if @home.booking_conflict?(start_date, end_date)
render json: "Home is unavailable on those dates", status: 422
elsif @confirmation.save
render :show
else
render json: @confirmation.errors.full_messages, status: 422
end
end
def show
@confirmation = Confirmation.find_by(user_id: current_user.id)
if @confirmation
render :show
else
render json: "Error", status: 422
end
end
def destroy
@confirmation = Confirmation.find_by(user_id: current_user.id)
@confirmation.destroy
render :show
end
private
def confirmation_params
params.require(:confirmation).permit(
:cleaning_cost,
:days,
:end_date,
:home_id,
:num_guests,
:service_cost,
:nightly_cost,
:start_date,
:total_cost,
)
end
end
| 23.54 | 68 | 0.686491 |
33a944b3e1e2d86f13dad622fb669e3742c13a63 | 781 | # frozen_string_literal: true
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
module Google
module Cloud
module Speech
module V1
VERSION = "0.3.0"
end
end
end
end
| 26.931034 | 74 | 0.731114 |
87660bba07e766b576e3433e71641c11168f5254 | 422 | class Filezilla < Cask
version '3.9.0.5'
sha256 '805e7a83faa13235d15eeab572eab06d6033901a196ba3ebcf753793f81219cd'
url "https://downloads.sourceforge.net/project/filezilla/FileZilla_Client/#{version}/FileZilla_#{version}_macosx-x86.app.tar.bz2"
homepage 'https://filezilla-project.org/'
app 'FileZilla.app'
# todo verify that this does not contain user-generate content
# zap :delete => '~/.filezilla'
end
| 35.166667 | 131 | 0.767773 |
bf1036fc71bea7dbde642f11036eda1887b396f5 | 726 | class TicketCategoriesController < ApplicationController
before_action :set_ticket_category, only: :show
authorize_resource
# GET /ticket_categories
# GET /ticket_categories.json
def index
@ticket_categories = TicketCategory.all
end
# GET /ticket_categories/1
# GET /ticket_categories/1.json
def show
end
private
# Use callbacks to share common setup or constraints between actions.
def set_ticket_category
@ticket_category = TicketCategory.friendly.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def ticket_category_params
params.require(:ticket_category).permit(:name, :slug, :description)
end
end
| 26.888889 | 88 | 0.750689 |
ab7d1b378a70e169b602d1714577b88134213ddf | 1,893 | module BootstrapPager
module PageScopeMethods
# Specify the <tt>per_page</tt> value for the preceding <tt>page</tt> scope
# Model.page(3).per(10)
def per(num)
if (n = num.to_i) <= 0
self
elsif max_per_page && max_per_page < n
limit(max_per_page).offset(offset_value / limit_value * max_per_page)
else
limit(n).offset(offset_value / limit_value * n)
end
end
def padding(num)
@_padding = num
offset(offset_value + num.to_i)
end
# Total number of pages
def total_pages(column = :id)
count_without_padding = total_count(column)
count_without_padding -= @_padding if defined?(@_padding) && @_padding
count_without_padding = 0 if count_without_padding < 0
total_pages_count = (count_without_padding.to_f / limit_value).ceil
if max_pages.present? && max_pages < total_pages_count
max_pages
else
total_pages_count
end
end
#FIXME for compatibility. remove num_pages at some time in the future
alias num_pages total_pages
# Current page number
def current_page
offset_without_padding = offset_value
offset_without_padding -= @_padding if defined?(@_padding) && @_padding
offset_without_padding = 0 if offset_without_padding < 0
(offset_without_padding / limit_value) + 1
end
# Next page number in the collection
def next_page
current_page + 1 unless last_page?
end
# Previous page number in the collection
def prev_page
current_page - 1 unless first_page?
end
# First page of the collection?
def first_page?
current_page == 1
end
# Last page of the collection?
def last_page?
current_page >= total_pages
end
# Out of range of the collection?
def out_of_range?
current_page > total_pages
end
end
end
| 26.661972 | 79 | 0.66561 |
185ddefcaab47269d82fda5c98fdfaf58894e1f4 | 1,313 | # By default Volt generates this controller for your Main component
module Main
class MainController < Volt::ModelController
def index
# Add code for when the index view is loaded
end
def about
# Add code for when the about view is loaded
end
private
def say_to_all
puts 'saying to all'
page.notification_messages << NotificationMessage.say('Broadcast Notification', "Hello to All")
end
def say_to_me
puts 'saying to me'
Volt.current_user.notification_messages << NotificationMessage.say('User Notification', "Hello to #{Volt.current_user.full_name}")
end
def is_logged_in?
Volt.current_user.then do |user|
!user
end
end
# The main template contains a #template binding that shows another
# template. This is the path to that template. It may change based
# on the params._component, params._controller, and params._action values.
def main_path
"#{params._component || 'main'}/#{params._controller || 'main'}/#{params._action || 'index'}"
end
# Determine if the current nav component is the active one by looking
# at the first part of the url against the href attribute.
def active_tab?
url.path.split('/')[1] == attrs.href.split('/')[1]
end
end
end
| 29.177778 | 136 | 0.676314 |
1dc50f159f04edff2d2795b464e98e3c6886ac18 | 221 | module Devise
module Models
module AclManager
extend ActiveSupport::Concern
included do
include ::AclManager::Permissions
include ::AclManager::Relationships
end
end
end
end
| 17 | 43 | 0.660633 |
5d26d1e4f9cee2b4b53f59d14411e1cf1a73c579 | 7,782 | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
json_seed_data = [
{
"name": "Selandir",
"role": "Damage",
"class_": "Paladin",
"tooltip": "Justice demand retribution!",
"battletag": "nope",
"valid": true
},
{
"name": "test",
"role": "Tank",
"class_": "Death knight",
"tooltip": "test",
"battletag": "test",
"valid": true,
"deleted": true
},
{
"name": "bizonur",
"role": "Damage",
"class_": "Warlock",
"tooltip": "",
"battletag": "krogulek#2934",
"valid": true
},
{
"name": "selandir testuje ostatecznie",
"role": "Healer",
"class_": "Mage",
"tooltip": "krogulec to pizda",
"battletag": "aleJestSpoko#1234",
"valid": false,
"deleted": true
},
{
"name": "testy-hooka",
"role": "Damage",
"class_": "Shaman",
"tooltip": "asda",
"battletag": "2423",
"valid": false,
"deleted": true
},
{
"name": "Kociokwikful/ Plechozaur",
"role": "Damage",
"class_": "Warrior",
"tooltip": "",
"battletag": "Kociokwik#2593",
"valid": true,
"deleted": false
},
{
"name": "Kaseku",
"role": "Damage",
"class_": "Hunter",
"tooltip": "",
"battletag": "Kaseku#2575",
"valid": true,
"deleted": false
},
{
"name": "ThraĂŤl",
"role": "Tank",
"class_": "Warrior",
"tooltip": "",
"battletag": "Thrael#2896",
"valid": false,
"deleted": true
},
{
"name": "ThraĂŤl",
"role": "Damage",
"class_": "Warrior",
"tooltip": "Ushe The Shadow Warrior",
"battletag": "Thrael#2896",
"valid": true,
"deleted": true
},
{
"name": "ThraĂŤl",
"role": "Damage",
"class_": "Warrior",
"tooltip": "Ushe The Shadow Warrior",
"battletag": "Thrael#2896",
"valid": false,
"deleted": true
},
{
"name": "Zelaznykon",
"role": "Damage",
"class_": "Hunter",
"tooltip": "",
"battletag": "SynSzatana",
"valid": true,
"deleted": false
},
{
"name": "Preathorpp",
"role": "Damage",
"class_": "Mage",
"tooltip": "",
"battletag": "prokop#2167",
"valid": true,
"deleted": false
},
{
"name": "Serei",
"role": "Damage",
"class_": "Mage",
"tooltip": "",
"battletag": "Kubes90#1388",
"valid": true,
"deleted": false
},
{
"name": "Uszoll",
"role": "Damage",
"class_": "Rogue",
"tooltip": "",
"battletag": "ZOLTAN#2293",
"valid": true,
"deleted": false
},
{
"name": "Garrnash",
"role": "Damage",
"class_": "Warrior",
"tooltip": "Garnek",
"battletag": "kolus123#2427",
"valid": true,
"deleted": false
},
{
"name": "Garrnash",
"role": "Damage",
"class_": "Warrior",
"tooltip": "Garnek",
"battletag": "kolus123#2427",
"valid": false,
"deleted": true
},
{
"name": "Senel/Panndzia",
"role": "Damage",
"class_": "Demon hunter",
"tooltip": "Zobaczę co mi się bardziej spodoba",
"battletag": "Ozi#2970",
"valid": true,
"deleted": false
},
{
"name": "Eridor",
"role": "Healer",
"class_": "Priest",
"tooltip": "",
"battletag": "Eridor#1284",
"valid": true,
"deleted": false
},
{
"name": "Eridor",
"role": "Healer",
"class_": "Priest",
"tooltip": "",
"battletag": "Eridor#1284",
"valid": false,
"deleted": true
},
{
"name": "errorPUT test",
"role": "Tank",
"class_": "Death knight",
"tooltip": "adsaadsaadsaadsaadsaadsaadsaadsaadsaadsaadsaadsaadsaadsaadsa",
"battletag": "qweqweqoweqweqlweknqlwkenqwe",
"valid": false,
"deleted": true
},
{
"name": "Nenii",
"role": "Damage",
"class_": "Hunter",
"tooltip": "",
"battletag": "Nenii#2870",
"valid": true,
"deleted": false
},
{
"name": "Biokukla",
"role": "Damage",
"class_": "Death knight",
"tooltip": "http://x3.cdn03.imgwykop.pl/c3201142/comment_YUJyVnGOy1HlphXfienwsFnukDzfla85,wat.jpg",
"battletag": "crd#2966",
"valid": true,
"deleted": false
},
{
"name": "t",
"role": "Tank",
"class_": "Death knight",
"tooltip": "t",
"battletag": "t",
"valid": false,
"deleted": true
},
{
"name": "Zaduzodamazu",
"role": "Healer",
"class_": "Shaman",
"tooltip": "knyf",
"battletag": "knyfito#2829",
"valid": true,
"deleted": false
},
{
"name": "Zielonookaa",
"role": "Damage",
"class_": "Hunter",
"tooltip": "",
"battletag": "Leonia#2106",
"valid": true,
"deleted": true
},
{
"name": "AMBAFATIMA",
"role": "Damage",
"class_": "Priest",
"tooltip": "",
"battletag": "buz#2780",
"valid": true,
"deleted": false
},
{
"name": " ",
"role": "Tank",
"class_": "Death knight",
"tooltip": "",
"battletag": " ",
"valid": false,
"deleted": true
},
{
"name": "Lindlay",
"role": "Healer",
"class_": "Priest",
"tooltip": "",
"battletag": "Lindlay#2122",
"valid": true,
"deleted": false
},
{
"name": "DeXeer",
"role": "Tank",
"class_": "Warrior",
"tooltip": "",
"battletag": "DeeXeer#2371",
"valid": true,
"deleted": false
},
{
"name": "Thrael",
"role": "Damage",
"class_": "Warrior",
"tooltip": "Ushe The Shadow Warrior",
"battletag": "Thrael#2896",
"valid": true,
"deleted": false
},
{
"name": "Kuszacypalas",
"role": "Tank",
"class_": "Demon hunter",
"tooltip": "",
"battletag": "Bloodmati#2321",
"valid": true,
"deleted": false
},
{
"name": "Ga",
"role": "Tank",
"class_": "Demon hunter",
"tooltip": "",
"battletag": "Gamper#2890",
"valid": false,
"deleted": true
},
{
"name": "Gamper",
"role": "Tank",
"class_": "Demon hunter",
"tooltip": "",
"battletag": "Gamper#2890",
"valid": true,
"deleted": true
},
{
"name": "kambo",
"role": "Damage",
"class_": "Warlock",
"tooltip": "",
"battletag": "Monia#2983",
"valid": true,
"deleted": false
},
{
"name": "Brazolq",
"role": "Damage",
"class_": "Shaman",
"tooltip": ":)",
"battletag": "Brazolq#2597",
"valid": true,
"deleted": false
},
{
"name": "Gamper",
"role": "Tank",
"class_": "Druid",
"tooltip": "Druidzi król",
"battletag": "Gamper#2890",
"valid": true,
"deleted": false
},
{
"name": "Nokem",
"role": "Tank",
"class_": "Monk",
"tooltip": "Kocham Gampera",
"battletag": "Nokem#2918",
"valid": true,
"deleted": false
}
]
u = User.new(:email => '[email protected]', :password => 'tvzvuwg4')
u.save
def set_role role, c
if role == 'Damage'
case c.downcase
when 'warlock', 'mage', 'hunter', 'priest'
'Ranged DD'
when 'rogue, shaman'
'Melee DD'
else 'Melee DD'
end
elsif role == 'Tank'
'Tank'
elsif role == 'Healer'
'Healer'
end
end
json_seed_data.each do |j|
next if !j[:valid] || j[:deleted]
new_char = Character.new(
:name => j[:name],
:game_class => j[:class_],
:game_role => set_role(j[:role], j[:class_]),
:game_tag => j[:battletag],
:armory_addr => 'http://eu.battle.net/wow/en/character/burning-legion/' + j[:name] + '/simple',
:user_id => u.id
)
puts "#{j[:name]}, #{new_char.save(:validate => false)}"
end
| 20.752 | 103 | 0.516705 |
f7292328d7186e2059aedc10b643905c010a99d0 | 401 | FactoryBot.define do
sequence :user_mail do |n|
"test#{n}@test.com.br"
end
factory :user do
email { generate(:user_mail) }
name { 'Teste da Silva' }
password { 'TesteSenha' }
password_confirmation { 'TesteSenha' }
creator { false }
admin { false }
factory :creator do
creator { true }
end
factory :admin do
admin { true }
end
end
end
| 17.434783 | 42 | 0.59601 |
e9f685fcb9f2f1b17c33de0b82756ca173e00169 | 2,268 | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20150818184834) do
create_table "businesses", force: :cascade do |t|
t.integer "user_id"
t.string "category"
t.string "name"
t.string "phone"
t.string "email"
t.text "description"
t.boolean "featured", default: false
t.datetime "created_at"
t.datetime "updated_at"
t.string "website"
t.string "address"
t.string "city"
t.string "postal_code"
t.string "province"
t.string "country"
t.string "photo_file_name"
t.string "photo_content_type"
t.integer "photo_file_size"
t.datetime "photo_updated_at"
t.string "photo_scraped"
t.float "longitude"
t.float "latitude"
end
add_index "businesses", ["user_id"], name: "index_businesses_on_user_id"
create_table "designs", force: :cascade do |t|
t.integer "business_id"
t.string "template"
t.string "main_color"
t.string "secondary_color"
t.string "accent_color"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "designs", ["business_id"], name: "index_designs_on_business_id"
create_table "users", force: :cascade do |t|
t.string "password_digest"
t.string "photo"
t.string "user_type", default: "customer"
t.datetime "created_at"
t.datetime "updated_at"
t.string "provider"
t.string "uid"
t.string "name"
t.string "first_name"
t.string "last_name"
t.string "email"
end
end
| 32.4 | 86 | 0.685185 |
184e0c7d7d5e38135f5837165c83575d31de3348 | 346 | cask 'slicy' do
version :latest
sha256 :no_check
url 'https://macrabbit.com/slicy/get/'
appcast 'https://update.macrabbit.com/slicy/1.1.3.xml',
:checkpoint => '39d01f62bb6ab96fdee061a8077fd8cbffcafee6551d7be4bc0fe4dc20249e3d'
name 'Slicy'
homepage 'http://macrabbit.com/slicy/'
license :commercial
app 'Slicy.app'
end
| 24.714286 | 91 | 0.722543 |
6aa414ba6b1eddfbcde8f1081e23150fc9d9052c | 10,994 | # frozen_string_literal: true
require "active_support/core_ext/module/attribute_accessors"
require "active_record/attribute_mutation_tracker"
module ActiveRecord
module AttributeMethods
module Dirty # :nodoc:
extend ActiveSupport::Concern
include ActiveModel::Dirty
included do
if self < ::ActiveRecord::Timestamp
raise "You cannot include Dirty after Timestamp"
end
class_attribute :partial_writes, instance_writer: false
self.partial_writes = true
after_create { changes_internally_applied }
after_update { changes_internally_applied }
# Attribute methods for "changed in last call to save?"
attribute_method_affix(prefix: "saved_change_to_", suffix: "?")
attribute_method_prefix("saved_change_to_")
attribute_method_suffix("_before_last_save")
# Attribute methods for "will change if I call save?"
attribute_method_affix(prefix: "will_save_change_to_", suffix: "?")
attribute_method_suffix("_change_to_be_saved", "_in_database")
end
# Attempts to +save+ the record and clears changed attributes if successful.
def save(*)
if status = super
changes_applied
end
status
end
# Attempts to <tt>save!</tt> the record and clears changed attributes if successful.
def save!(*)
super.tap do
changes_applied
end
end
# <tt>reload</tt> the record and clears changed attributes.
def reload(*)
super.tap do
@previous_mutation_tracker = nil
clear_mutation_trackers
@changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
end
end
def initialize_dup(other) # :nodoc:
super
@attributes = self.class._default_attributes.map do |attr|
attr.with_value_from_user(@attributes.fetch_value(attr.name))
end
clear_mutation_trackers
end
def changes_internally_applied # :nodoc:
@mutations_before_last_save = mutation_tracker
forget_attribute_assignments
@mutations_from_database = AttributeMutationTracker.new(@attributes)
end
def changes_applied
@previous_mutation_tracker = mutation_tracker
@changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
clear_mutation_trackers
end
def clear_changes_information
@previous_mutation_tracker = nil
@changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
forget_attribute_assignments
clear_mutation_trackers
end
def raw_write_attribute(attr_name, *)
result = super
clear_attribute_change(attr_name)
result
end
def clear_attribute_changes(attr_names)
super
attr_names.each do |attr_name|
clear_attribute_change(attr_name)
end
end
def changed_attributes
# This should only be set by methods which will call changed_attributes
# multiple times when it is known that the computed value cannot change.
if defined?(@cached_changed_attributes)
@cached_changed_attributes
else
emit_warning_if_needed("changed_attributes", "saved_changes.transform_values(&:first)")
super.reverse_merge(mutation_tracker.changed_values).freeze
end
end
def changes
cache_changed_attributes do
emit_warning_if_needed("changes", "saved_changes")
super
end
end
def previous_changes
unless previous_mutation_tracker.equal?(mutations_before_last_save)
ActiveSupport::Deprecation.warn(<<-EOW.strip_heredoc)
The behavior of `previous_changes` inside of after callbacks is
deprecated without replacement. In the next release of Rails,
this method inside of `after_save` will return the changes that
were just saved.
EOW
end
previous_mutation_tracker.changes
end
def attribute_changed_in_place?(attr_name)
mutation_tracker.changed_in_place?(attr_name)
end
# Did this attribute change when we last saved? This method can be invoked
# as `saved_change_to_name?` instead of `saved_change_to_attribute?("name")`.
# Behaves similarly to +attribute_changed?+. This method is useful in
# after callbacks to determine if the call to save changed a certain
# attribute.
#
# ==== Options
#
# +from+ When passed, this method will return false unless the original
# value is equal to the given option
#
# +to+ When passed, this method will return false unless the value was
# changed to the given value
def saved_change_to_attribute?(attr_name, **options)
mutations_before_last_save.changed?(attr_name, **options)
end
# Returns the change to an attribute during the last save. If the
# attribute was changed, the result will be an array containing the
# original value and the saved value.
#
# Behaves similarly to +attribute_change+. This method is useful in after
# callbacks, to see the change in an attribute that just occurred
#
# This method can be invoked as `saved_change_to_name` in instead of
# `saved_change_to_attribute("name")`
def saved_change_to_attribute(attr_name)
mutations_before_last_save.change_to_attribute(attr_name)
end
# Returns the original value of an attribute before the last save.
# Behaves similarly to +attribute_was+. This method is useful in after
# callbacks to get the original value of an attribute before the save that
# just occurred
def attribute_before_last_save(attr_name)
mutations_before_last_save.original_value(attr_name)
end
# Did the last call to `save` have any changes to change?
def saved_changes?
mutations_before_last_save.any_changes?
end
# Returns a hash containing all the changes that were just saved.
def saved_changes
mutations_before_last_save.changes
end
# Alias for `attribute_changed?`
def will_save_change_to_attribute?(attr_name, **options)
mutations_from_database.changed?(attr_name, **options)
end
# Alias for `attribute_change`
def attribute_change_to_be_saved(attr_name)
mutations_from_database.change_to_attribute(attr_name)
end
# Alias for `attribute_was`
def attribute_in_database(attr_name)
mutations_from_database.original_value(attr_name)
end
# Alias for `changed?`
def has_changes_to_save?
mutations_from_database.any_changes?
end
# Alias for `changes`
def changes_to_save
mutations_from_database.changes
end
# Alias for `changed`
def changed_attribute_names_to_save
changes_to_save.keys
end
# Alias for `changed_attributes`
def attributes_in_database
changes_to_save.transform_values(&:first)
end
def attribute_was(*)
emit_warning_if_needed("attribute_was", "attribute_before_last_save")
super
end
def attribute_change(*)
emit_warning_if_needed("attribute_change", "saved_change_to_attribute")
super
end
def attribute_changed?(*)
emit_warning_if_needed("attribute_changed?", "saved_change_to_attribute?")
super
end
def changed?(*)
emit_warning_if_needed("changed?", "saved_changes?")
super
end
def changed(*)
emit_warning_if_needed("changed", "saved_changes.keys")
super
end
private
def mutation_tracker
unless defined?(@mutation_tracker)
@mutation_tracker = nil
end
@mutation_tracker ||= AttributeMutationTracker.new(@attributes)
end
def emit_warning_if_needed(method_name, new_method_name)
unless mutation_tracker.equal?(mutations_from_database)
ActiveSupport::Deprecation.warn(<<-EOW.squish)
The behavior of `#{method_name}` inside of after callbacks will
be changing in the next version of Rails. The new return value will reflect the
behavior of calling the method after `save` returned (e.g. the opposite of what
it returns now). To maintain the current behavior, use `#{new_method_name}`
instead.
EOW
end
end
def mutations_from_database
unless defined?(@mutations_from_database)
@mutations_from_database = nil
end
@mutations_from_database ||= mutation_tracker
end
def changes_include?(attr_name)
super || mutation_tracker.changed?(attr_name)
end
def clear_attribute_change(attr_name)
mutation_tracker.forget_change(attr_name)
mutations_from_database.forget_change(attr_name)
end
def attribute_will_change!(attr_name)
super
if self.class.has_attribute?(attr_name)
mutations_from_database.force_change(attr_name)
else
ActiveSupport::Deprecation.warn(<<-EOW.squish)
#{attr_name} is not an attribute known to Active Record.
This behavior is deprecated and will be removed in the next
version of Rails. If you'd like #{attr_name} to be managed
by Active Record, add `attribute :#{attr_name} to your class.
EOW
mutations_from_database.deprecated_force_change(attr_name)
end
end
def _update_record(*)
partial_writes? ? super(keys_for_partial_write) : super
end
def _create_record(*)
partial_writes? ? super(keys_for_partial_write) : super
end
def keys_for_partial_write
changed_attribute_names_to_save & self.class.column_names
end
def forget_attribute_assignments
@attributes = @attributes.map(&:forgetting_assignment)
end
def clear_mutation_trackers
@mutation_tracker = nil
@mutations_from_database = nil
@mutations_before_last_save = nil
end
def previous_mutation_tracker
@previous_mutation_tracker ||= NullMutationTracker.instance
end
def mutations_before_last_save
@mutations_before_last_save ||= previous_mutation_tracker
end
def cache_changed_attributes
@cached_changed_attributes = changed_attributes
yield
ensure
clear_changed_attributes_cache
end
def clear_changed_attributes_cache
remove_instance_variable(:@cached_changed_attributes) if defined?(@cached_changed_attributes)
end
end
end
end
| 32.916168 | 103 | 0.665272 |
4a3b059b1d9ebf7e644241532c5e634e689704ae | 1,348 | class Bartycrouch < Formula
desc "Incrementally update/translate your Strings files"
homepage "https://github.com/Flinesoft/BartyCrouch"
url "https://github.com/Flinesoft/BartyCrouch.git",
tag: "4.4.1",
revision: "d0ea3568044e2348e5fa87b9fdbc9254561039e2"
license "MIT"
head "https://github.com/Flinesoft/BartyCrouch.git"
bottle do
cellar :any_skip_relocation
sha256 "635a9fff91e57290f013826f3b102fd1e639ed4d8dd9f2a5fc84ee3ee86b3383" => :big_sur
sha256 "290d66a6a7164de7c459553fcaaf6ffdc2c8e48673d4536626aac4a644a18107" => :arm64_big_sur
sha256 "a403e05eef2353f041f499275a0ebcea1fc9381bea71b9205227a319ed5547c9" => :catalina
end
depends_on xcode: ["12.0", :build]
depends_on :macos
def install
system "make", "install", "prefix=#{prefix}"
end
test do
(testpath/"Test.swift").write <<~EOS
import Foundation
class Test {
func test() {
NSLocalizedString("test", comment: "")
}
}
EOS
(testpath/"en.lproj/Localizable.strings").write <<~EOS
/* No comment provided by engineer. */
"oldKey" = "Some translation";
EOS
system bin/"bartycrouch", "update"
assert_match /"oldKey" = "/, File.read("en.lproj/Localizable.strings")
assert_match /"test" = "/, File.read("en.lproj/Localizable.strings")
end
end
| 29.955556 | 95 | 0.690653 |
91660e3688e838d32c0d35884f5baade39fbe06e | 561 | require 'spec_helper'
describe Talkable::API::Reward do
describe ".find" do
let(:visitor_uuid) { "8fdf75ac-92b4-479d-9974-2f9c64eb2e09" }
before do
stub_request(:get, %r{.*api/v2/rewards.*visitor_uuid=8fdf75ac-92b4-479d-9974-2f9c64eb2e09}).
to_return(body: '{"ok": true, "result": {"rewards": [{"id":128}]}}')
end
it "success" do
result = Talkable::API::Reward.find({visitor_uuid: visitor_uuid})
expect(result[:rewards]).to be_kind_of(Array)
expect(result[:rewards].first).to eq({id: 128})
end
end
end
| 29.526316 | 98 | 0.652406 |
bfd74a02da2f151e8094bc6fd6f497a9bce1dc59 | 192 | Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
get '/base_categories' => 'base_categories#index'
end
| 32 | 101 | 0.770833 |
6126529bedabd5db5ece59fd64b74d7f560d9b2f | 550 | module ActiveAdmin
module Inputs
module Filters
class TextInput < ::Formtastic::Inputs::TextInput
include Base
include Base::SearchMethodSelect
def input_html_options
{
:cols => builder.default_text_area_width,
:rows => builder.default_text_area_height
}.merge(super)
end
def to_html
input_wrapping do
label_html <<
builder.text_area(method, input_html_options)
end
end
end
end
end
end
| 20.37037 | 57 | 0.578182 |
f8aea137c92c15e38365ee737af7e93327acde16 | 1,215 | # Copyright 2014, Greg Althaus
#
# 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.
#
#
# Install and start lldpd
#
# This is a little bit of a hack for now.
return if node[:platform] == "coreos" || node[:rebar_ohai][:in_docker]
package_name = "lldpd"
service_name = "lldpd"
case node[:platform]
when "centos"
package_name = "lldpad" if node[:platform_version] == "6.5"
service_name = "lldpad" if node[:platform_version] == "6.5"
end
unless system("which #{service_name}")
case node[:platform]
when 'ubuntu','debian'
package package_name do
action :install
options '--force-yes'
end
else
package package_name
end
end
service service_name do
action [ :enable, :start ]
end
| 25.3125 | 74 | 0.714403 |
abe5724a2c8c0a0ebc049ce3fa3f27c1e5fc90fe | 2,103 | # Copyright 2018 Twitter, Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# encoding: UTF-8
module Twitter
module TwitterText
class Configuration
require 'json'
PARSER_VERSION_CLASSIC = "v1"
PARSER_VERSION_WEIGHTED = "v2"
PARSER_VERSION_EMOJI_PARSING = "v3"
PARSER_VERSION_DEFAULT = PARSER_VERSION_WEIGHTED
class << self
attr_accessor :default_configuration
end
attr_reader :version, :max_weighted_tweet_length, :scale
attr_reader :default_weight, :transformed_url_length, :ranges
attr_reader :emoji_parsing_enabled
CONFIG_V1 = File.join(
File.expand_path('../../../config', __FILE__), # project root
"#{PARSER_VERSION_CLASSIC}.json"
)
CONFIG_V2 = File.join(
File.expand_path('../../../config', __FILE__), # project root
"#{PARSER_VERSION_WEIGHTED}.json"
)
CONFIG_V3 = File.join(
File.expand_path('../../../config', __FILE__), # project root
"#{PARSER_VERSION_EMOJI_PARSING}.json"
)
def self.parse_string(string, options = {})
JSON.parse(string, options.merge(symbolize_names: true))
end
def self.parse_file(filename)
string = File.open(filename, 'rb') { |f| f.read }
parse_string(string)
end
def self.configuration_from_file(filename)
config = parse_file(filename)
config ? self.new(config) : nil
end
def initialize(config = {})
@version = config[:version]
@max_weighted_tweet_length = config[:maxWeightedTweetLength]
@scale = config[:scale]
@default_weight = config[:defaultWeight]
@transformed_url_length = config[:transformedURLLength]
@emoji_parsing_enabled = config[:emojiParsingEnabled]
@ranges = config[:ranges].map { |range| Twitter::TwitterText::WeightedRange.new(range) } if config.key?(:ranges) && config[:ranges].is_a?(Array)
end
self.default_configuration = self.configuration_from_file(CONFIG_V3)
end
end
end
| 30.478261 | 152 | 0.65573 |
21ba31267aa94781ec46e7e2fce15e29708a9e69 | 429 | # frozen_string_literal: true
require_relative "../lib/tty-sparkline"
sparkline = TTY::Sparkline.new(left: 10, top: 10, height: 2, width: 40)
sparkline2 = TTY::Sparkline.new(left: 10, top: 14, height: 10, width: 40)
print sparkline.cursor.clear_screen
sparkline.cursor.invisible do
loop do
sparkline << rand(50)
sparkline2 << rand(50)
print sparkline.render
print sparkline2.render
sleep(0.05)
end
end
| 23.833333 | 73 | 0.713287 |
ac7fe2876fda90d0c258f0964d22e79ee6e0018b | 901 | # frozen_string_literal: true
module AcaEntities
module Serializers
module Xml
module Fdsh
module Vlp
module H92
# Happymapper implementation for the root object of an ArrayOfSponsorshipData.
class ArrayOfSponsorshipData
include HappyMapper
register_namespace 'vlp', 'http://vlp.ee.sim.dsh.cms.hhs.gov'
tag 'ArrayOfSponsorshipData'
namespace 'vlp'
has_many :SponsorshipData, SponsorshipData
def self.domain_to_mapper(sponsorship_datas)
mapper = self.new
mapper.SponsorshipData = sponsorship_datas.collect do |sponsorship_data|
SponsorshipData.domain_to_mapper(sponsorship_data)
end
mapper
end
end
end
end
end
end
end
end | 27.30303 | 90 | 0.581576 |
b95a3f80c070c9037aa21cb5c1fd93a4a21770ad | 35 | module WopiFilesContentsHelper
end
| 11.666667 | 30 | 0.914286 |
113e40eaf91f1403a207ff9414469b9bd4d48f99 | 187 | # coding: utf-8
class DummyWithDefaultCurrency
include Mongoid::Document
include Mongoid::MoneyField
field :description
money_field :price, default_currency: 'EUR'
end | 18.7 | 46 | 0.743316 |
e8296b60ca7e44009fec4cf727ddf3d39e2f8d49 | 1,010 | User.create!(name: "Example User",
email: "[email protected]",
password: "foobar",
password_confirmation: "foobar",
admin: true,
activated: true,
activated_at: Time.zone.now)
99.times do |n|
name = Faker::Name.name
email = "example-#{n+1}@railstutorial.org"
password = "password"
User.create!(name: name,
email: email,
password: password,
password_confirmation: password,
activated: true,
activated_at: Time.zone.now)
end
# マイクロポスト
users = User.order(:created_at).take(6)
50.times do
content = Faker::Lorem.sentence(5)
users.each { |user| user.microposts.create!(content: content) }
end
# リレーションシップ
users = User.all
user = users.first
following = users[2..50]
followers = users[3..40]
following.each { |followed| user.follow(followed) }
followers.each { |follower| follower.follow(user) }
| 28.857143 | 65 | 0.586139 |
6aab665a4af9cac08c12c008ca219a178da76b72 | 886 | require 'spec_helper_acceptance'
describe 'rabbitmq user:' do
context "create user resource" do
it 'should run successfully' do
pp = <<-EOS
if $::osfamily == 'RedHat' {
class { 'erlang': epel_enable => true }
Class['erlang'] -> Class['::rabbitmq']
}
class { '::rabbitmq':
service_manage => true,
port => '5672',
delete_guest_user => true,
admin_enable => true,
} ->
rabbitmq_user { 'dan':
admin => true,
password => 'bar',
}
EOS
apply_manifest(pp, :catch_failures => true)
apply_manifest(pp, :catch_changes => true)
end
it 'should have the user' do
shell('rabbitmqctl list_users') do |r|
expect(r.stdout).to match(/dan.*administrator/)
expect(r.exit_code).to be_zero
end
end
end
end
| 22.717949 | 55 | 0.544018 |
7a0e3f00a7089317ac7d2a8ad152d04908520c06 | 110 | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'lastpass/cli'
require 'minitest/autorun'
| 22 | 58 | 0.745455 |
0804cd8e2efa358e58c18ca25ce02b6ed5a6b2a7 | 854 | def triangular_word?(word)
encoded_num = encode(word)
i = 0
while i < encoded_num
# p "encoded_num: #{encoded_num}"
# p "(i * (i + 1)) / 2: #{(i * (i + 1)) / 2}"
return true if encoded_num == (i * (i + 1)) / 2
i += 1
end
false
end
def encode(word)
alpha = ("a".."z").to_a
word.split("").inject(0) do |memo, char|
# p "memo: #{memo}"
# p "alpha.index(char): #{alpha.index(char)}"
memo + alpha.index(char) + 1 # to comply with zero-based array index
end
end
def triangular_number?(num)
end
p triangular_word?('abc') # true
p triangular_word?('ba') # true
p triangular_word?('lovely') # true
p triangular_word?('question') # true
p triangular_word?('aa') # false
p triangular_word?('cd') # false
p triangular_word?('cat') # false
p triangular_word?('sink') # false
| 25.117647 | 72 | 0.583138 |
33299bd72993010909f3cbe6fdadc71bfc8ce8eb | 901 | require 'dotenv'
require 'ringcentral'
RSpec.describe 'query params' do
describe 'single' do
it 'contain single query param' do
Dotenv.load
rc = RingCentral.new(ENV['RINGCENTRAL_CLIENT_ID'], ENV['RINGCENTRAL_CLIENT_SECRET'], ENV['RINGCENTRAL_SERVER_URL'])
rc.authorize(username: ENV['RINGCENTRAL_USERNAME'], extension: ENV['RINGCENTRAL_EXTENSION'], password: ENV['RINGCENTRAL_PASSWORD'])
r = rc.get('/restapi/v1.0/account/~/extension/~/address-book/contact', { phoneNumber: '666' })
expect(r).not_to be_nil
message = r.body
expect(message['uri']).to include('phoneNumber=666')
r = rc.get('/restapi/v1.0/account/~/extension/~/address-book/contact', { phoneNumber: ['666', '888'] })
expect(r).not_to be_nil
message = r.body
expect(message['uri']).to include('phoneNumber=666&phoneNumber=888')
rc.revoke()
end
end
end
| 39.173913 | 137 | 0.678135 |
4a231c960801446147ebe6c1fecd3610576c9b86 | 125 | class AddImageToProperties < ActiveRecord::Migration[5.2]
def change
add_column :properties, :image, :string
end
end
| 20.833333 | 57 | 0.752 |
b90249d2e8be37dcbfc897a42e45d119b4ac2ac3 | 2,137 | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
User.create(email: "[email protected]", password: "password", password_confirmation: "password", name: "Cillian Wing", location: "Austin, TX", bio: "Test bio for Cillian...I'll fill some more out later.")
User.create(email: "[email protected]", password: "password", password_confirmation: "password", name: "Anthony Camara", location: "San Diego, CA", bio: "Test bio for Anthony...I'll fill some more out later.")
User.create(email: "[email protected]", password: "password", password_confirmation: "password", name: "Michael Camara", location: "San Diego, CA", bio: "Test bio for Michael...I'll fill some more out later.")
@user1 = User.find_by(id: 1)
@user2 = User.find_by(id: 2)
@user3 = User.find_by(id: 3)
@user1.trips.create(title: "Peru", description: "Two week trip to peru to trek to Macchu Picchu and then see a few cities throughout the country.", start: (Date.today+15), end: (Date.today+29), group_trip: true, creator_id: @user1.id)
@user1.trips.create(title: "Thailand", description: "Three week trip through Thailand starting in Bangkok, hitting a few islands, and ending on Phuket.", start: (Date.today-60), end: (Date.today-39), group_trip: true, creator_id: @user1.id)
@user2.trips.create(title: "Eastern Europe", description: "3 week trip through eastern Europe. Starting by flying into Prague and then seeing various other places after that.", start: (Date.today+50), end: (Date.today+71), group_trip: true, creator_id: @user2.id)
@user3.trips.create(title: "Austin", description: "Quick weekend trip to Austin to see some friends from college.", start: (Date.today+75), end: (Date.today+78), group_trip: false, creator_id: @user3.id)
@trip1 = Trip.find_by(id: 1)
@trip2 = Trip.find_by(id: 2)
@trip3 = Trip.find_by(id: 3)
@trip4 = Trip.find_by(id: 4)
| 79.148148 | 263 | 0.725316 |
e88e473acf4905b40cef70d2c5edffd6ee0e990d | 1,466 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'referencia/version'
Gem::Specification.new do |spec|
spec.name = "referencia"
spec.version = Referencia::VERSION
spec.authors = ["Orlandy Ariel"]
spec.email = ["[email protected]"]
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com' to prevent pushes to rubygems.org, or delete to allow pushes to any server."
end
spec.summary = %q{TODO: Write a short summary, because Rubygems requires one.}
spec.description = %q{TODO: Write a longer description or delete this line.}
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.8"
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 2.11"
spec.add_development_dependency "guard"
spec.add_development_dependency "guard-rspec"
spec.add_development_dependency "guard-bundler"
spec.add_development_dependency "coveralls"
end
| 41.885714 | 156 | 0.687585 |
6a75f64e7bde7e1b10b232219b8f40a2dcaa94bf | 1,409 | require 'spec_helper'
describe Sorry::Api::Request do
# Placeholder access token.
let(:access_token) { Faker::Internet.password(128) }
# Mock the request object.
let(:request) { Sorry::Api::Request.new(Sorry::Api::Client.new(access_token: access_token)) }
describe 'error handling' do
it 'should reraise any errors' do
# Pass the error handler a new instance of error.
expect{request.handle_error(StandardError.new)}.to raise_exception(StandardError)
end
end
describe 'response parsing' do
# Mock the response body to test the parses.
let(:response_body) { '{"response":{"id": 1, "name": "Some name"}}' }
it 'should return an response outside of its envelope' do
# Expect the parses to remove the envelop.
expect(request.parse_response(response_body)).to eq({:id => 1, :name => "Some name"})
end
end
describe 'the HTTP client' do
it 'should be a Faraday client' do
# Ask the instance for the http_client
expect(request.http_client).to be_a(Faraday::Connection)
end
it 'should be configured with the URL for the endpoint' do
# Ask the instance for the http_client
expect(request.http_client.url_prefix.to_s).to eq(Sorry::Api::ENDPOINT)
end
it 'has the access_token as a bearer header' do
# Ask the instance for the http_client
expect(request.http_client.headers).to include({"Authorization"=>"bearer #{access_token}"})
end
end
end | 27.627451 | 94 | 0.720369 |
b931de9c7d4549f243a94eb592a058cec897b2f8 | 1,080 | class PagesController < ApplicationController
skip_before_action :authenticate_user!, only: :home
def home
@CATEGORIES = [
{ name: "Coronavirus", filename: "coronavirus.jpg" },
{ name: "Hunger and Poverty", filename: "hunger-poverty.jpg" },
{ name: "Health", filename: "health.jpg" },
{ name: "Eldery", filename: "eldery.jpg" },
{ name: "Children", filename: "children.jpg" },
{ name: "Education", filename: "education.jpg" },
{ name: "Emergency Situations", filename: "emergency.jpg" },
{ name: "Animal causes", filename: "animals.jpg" }
]
@urgent_campaigns = Campaign.all.reject { |campaign| campaign.raised >= campaign.total }.sort { |campaign| campaign.raised / campaign.total.to_f }.first(3)
@latest_reviews = Review.order(created_at: :desc).sample(5)
end
def dashboard
@results = params[:results_query]
@donations = current_user.donations
@institutions = current_user.institutions
@campaigns = current_user.campaigns
@accountabilities = current_user.accountabilities
end
end
| 40 | 159 | 0.673148 |
e96150bdb2d6bab021e15bea0b057f51ea8c8628 | 4,586 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe Spree::Order, type: :model do
let(:order) { create(:order_with_line_items) }
context "#next!" do
context "when current state is confirm" do
before do
order.state = "confirm"
order.save!
end
context "when payment processing succeeds" do
let!(:payment) do
create(:payment, state: 'checkout', order: order)
end
it "should finalize order when transitioning to complete state" do
order.complete!
expect(order).to be_complete
expect(order).to be_completed
end
context "when credit card processing fails" do
let!(:payment) do
create(:payment, :failing, state: 'checkout', order: order)
end
it "should not complete the order" do
expect(order.complete).to be false
expect(order.state).to eq("confirm")
end
end
end
end
context "when current state is address" do
before do
order.ensure_updated_shipments
order.next!
expect(order.all_adjustments).to be_empty
expect(order.state).to eq "address"
end
it "adjusts tax rates when transitioning to delivery" do
expect(Spree::TaxCalculator::Default).to receive(:new).once.with(order).and_call_original
order.next!
end
end
end
context "#can_cancel?" do
let(:order) { create(:completed_order_with_totals) }
states = [:pending, :backorder, :ready]
states.each do |shipment_state|
it "should be true if shipment_state is #{shipment_state}" do
expect(order).to be_completed
order.shipment_state = shipment_state
expect(order).to be_can_cancel
end
end
(Spree::Shipment.state_machine.states.keys - states).each do |shipment_state|
it "should be false if shipment_state is #{shipment_state}" do
expect(order).to be_completed
order.shipment_state = shipment_state
expect(order).not_to be_can_cancel
end
end
end
context "#cancel" do
let!(:order) { create(:completed_order_with_totals) }
let!(:shipment) { order.shipments.first }
it "is setup correctly" do
expect(order).to be_completed
expect(order).to be_complete
expect(order).to be_allow_cancel
end
it "should send a cancel email" do
perform_enqueued_jobs do
order.cancel!
end
mail = ActionMailer::Base.deliveries.last
expect(mail.subject).to include "Cancellation"
end
context "resets payment state" do
let!(:payment) { create(:payment, order: order, amount: order.total, state: "completed") }
context "without shipped items" do
it "should set payment state to 'void'" do
expect { order.cancel! }.to change{ order.reload.payment_state }.to("void")
end
end
context "with shipped items" do
before do
order.shipments[0].ship!
end
it "should not alter the payment state" do
expect(order).to_not be_allow_cancel
expect(order.cancel).to be false
expect(order.payment_state).to eql "paid"
end
end
it "should automatically refund all payments" do
expect(order).to be_allow_cancel
expect { order.cancel! }.to change{ payment.reload.state }.to("void")
end
end
end
describe "#complete" do
context "when the confirm step has been taken out of the checkout flow" do
let!(:payment) { create(:payment, state: 'checkout', order: order) }
before :all do
class Spree::Order
checkout_flow do
go_to_state :address
go_to_state :delivery
go_to_state :payment, if: ->(order) { order.payment_required? }
# confirm step has been removed. Payment is the last step now
end
end
end
after :all do
# restore the standard checkout flow to avoid leaking into other tests
class Spree::Order
checkout_flow do
go_to_state :address
go_to_state :delivery
go_to_state :payment, if: ->(order) { order.payment_required? }
go_to_state :confirm
end
end
end
before do
order.update!(state: 'payment')
end
it 'will properly transition from the last checkout flow state to complete' do
order.complete!
expect(order.state).to eq 'complete'
end
end
end
end
| 28.484472 | 97 | 0.62102 |
ed7c22aa019c76c589eba4e12c893302d041d94e | 72 | require 'cocoapods_mangle/gem_version'
require 'cocoapods_mangle/hooks'
| 24 | 38 | 0.861111 |
21ce50566880224da5484e0b3b053489d8f0be6a | 2,685 | # coding: utf-8
# Copyright © 2011-2020 MUSC Foundation for Research Development
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
require 'rails_helper'
RSpec.describe SubServiceRequest, type: :model do
let_there_be_lane
context 'previously_submitted?' do
before :each do
@organization = create(:organization, process_ssrs: true)
@protocol = create(:protocol_without_validations, primary_pi: jug2)
@service_request = create(:service_request_without_validations, protocol: @protocol)
end
context "submitted ssr" do
it 'should not return true' do
ssr = create(:sub_service_request_without_validations,
organization: @organization,
service_request: @service_request,
submitted_at: Time.now)
expect(ssr.previously_submitted?).to eq(true)
end
end
context "not submitted ssr" do
it 'should not return true' do
ssr = create(:sub_service_request_without_validations,
organization: @organization,
service_request: @service_request,
submitted_at: nil)
expect(ssr.previously_submitted?).to eq(false)
end
end
end
end
| 47.105263 | 145 | 0.732588 |
87377280bac034480c43334e834f6a2df56c4148 | 675 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe Role, type: :model do
describe 'Associations' do
it 'has_and_belongs_to_many news' do
association = described_class.reflect_on_association(:users)
expect(association.macro).to eq :has_and_belongs_to_many
end
end
describe 'Validations' do
context 'when name is not unique' do
it { should validate_uniqueness_of(:name) }
end
end
describe 'Scope' do
before { create(:admin_role) }
before { create(:student_role) }
it 'should not include admin role' do
expect(Role.visible_to_users).not_to include(Role.find_by_name('admin'))
end
end
end
| 24.107143 | 78 | 0.712593 |
38ef637410a461b5bdcb45aa1349dbedefeaf122 | 1,007 | class Findomain < Formula
desc "Cross-platform subdomain enumerator"
homepage "https://github.com/Findomain/findomain"
url "https://github.com/Findomain/findomain/archive/4.0.1.tar.gz"
sha256 "4ef2f88beb87d7af7f53470df77f556e6d00a0c8745da4066902e98c47e8451d"
license "GPL-3.0-or-later"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "927d1c19cfec0697bd0237044ae33e62c9d9a968bfc593508aac3ecd02d9b9a8"
sha256 cellar: :any_skip_relocation, big_sur: "bb90cda08e18d47f040e3c866fd2a465e713efb0f4b527894af99ef0c37ec1f3"
sha256 cellar: :any_skip_relocation, catalina: "f0ca1f37371167d16c82d719fdff35546d8388799c88b1f324583f8accbde03c"
sha256 cellar: :any_skip_relocation, mojave: "9b99d238a617b04059485419304412a8bca562e445de44ba8ef6aa8739707326"
end
depends_on "rust" => :build
def install
system "cargo", "install", *std_cargo_args
end
test do
assert_match "Good luck Hax0r", shell_output("#{bin}/findomain -t brew.sh")
end
end
| 40.28 | 122 | 0.787488 |
4a2e88cdc4c862277bd68eb5c8a1b7187ce0d888 | 1,969 | require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
end
test "login with invalid information" do
get login_path
assert_template 'sessions/new'
post login_path, params: { session: { email: "", password: "" } }
assert_template 'sessions/new'
assert_not flash.empty?
get root_path
assert flash.empty?
end
test "login with valid information" do
get login_path
post login_path, params: { session: { email: @user.email,
password: 'password' } }
assert_redirected_to @user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(@user)
end
test "login with valid information followed by logout" do
get login_path
post login_path, params: { session: { email: @user.email,
password: 'password' } }
assert is_logged_in?
assert_redirected_to @user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(@user)
delete logout_path
assert_not is_logged_in?
assert_redirected_to root_url
# 2番目のウィンドウでログアウトをクリックするユーザーをシミュレートする
delete logout_path
follow_redirect!
assert_select "a[href=?]", login_path
assert_select "a[href=?]", logout_path, count: 0
assert_select "a[href=?]", user_path(@user), count: 0
end
test "login with remembering" do
log_in_as(@user, remember_me: '1')
assert_not_empty cookies['remember_token']
end
test "login without remembering" do
# クッキーを保存してログイン
log_in_as(@user, remember_me: '1')
delete logout_path
# クッキーを削除してログイン
log_in_as(@user, remember_me: '0')
assert_empty cookies['remember_token']
end
end
| 30.292308 | 69 | 0.672423 |
6aacdee4e7271dd661cd3060c5c24bf43119b0d9 | 867 | require 'rails_helper'
RSpec.describe Stocks::RetrieveDailyTimeSeriesEventsInteractor do
let(:stock_symbol) { 'IBM' }
let(:stock) { FactoryBot.build(:stock) }
subject(:context) { Stocks::RetrieveDailyTimeSeriesEventsInteractor.call(symbol: stock_symbol) }
context 'when given valid parameters' do
let(:response_body) { File.read('spec/interactors/stocks/daily_time_series_events_response.json') }
let(:response) { OpenStruct.new(body: response_body) }
context 'when Alpha Vantage API responds appropriately' do
before(:each) do
allow(HTTParty).to receive(:get).and_return(response)
allow(Stock).to receive(:find_by).with(symbol: stock_symbol).and_return(stock)
allow(DailyTimeSeriesEvent).to receive(:create!)
end
it 'succeeds' do
expect(context).to be_a_success
end
end
end
end
| 32.111111 | 103 | 0.71857 |
e9576b4aa3a076a3ee5e47a361a5ab1f76b755cc | 971 | class Mighttpd2 < Formula
desc "HTTP server"
homepage "https://www.mew.org/~kazu/proj/mighttpd/en/"
url "https://hackage.haskell.org/package/mighttpd2-3.4.6/mighttpd2-3.4.6.tar.gz"
sha256 "fe14264ea0e45281591c86030cad2b349480f16540ad1d9e3a29657ddf62e471"
license "BSD-3-Clause"
revision 1
livecheck do
url :stable
end
bottle do
cellar :any_skip_relocation
sha256 "bcea435a9feba47df19b64d9fac972a1df8f580647204b07a73b2ade2e14c479" => :catalina
sha256 "68e563757fb405de41a4312c03f7b72da99586430ea8f0aff98fdab48213635f" => :mojave
sha256 "7b033c6ce128310465134a09bae1ef3df9cb630db732167a06028c1a5773576e" => :high_sierra
end
depends_on "cabal-install" => :build
depends_on "ghc" => :build
uses_from_macos "zlib"
def install
system "cabal", "v2-update"
system "cabal", "v2-install", "-ftls", *std_cabal_v2_args
end
test do
system "#{bin}/mighty-mkindex"
assert (testpath/"index.html").file?
end
end
| 27.742857 | 93 | 0.745623 |
b9eabbed3cc5100db12d66671d5b6284ced33283 | 4,018 | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2020 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
require 'spec_helper'
describe ::API::V3::WorkPackages::Schema::SpecificWorkPackageSchema do
let(:project) { FactoryBot.build(:project) }
let(:type) { FactoryBot.build(:type) }
let(:work_package) do
FactoryBot.build(:work_package,
project: project,
type: type)
end
let(:current_user) do
FactoryBot.build_stubbed(:user).tap do |u|
allow(u)
.to receive(:allowed_to?)
.and_return(true)
end
end
shared_examples_for 'with parent which is a BACKLOGS type' do |writable|
let(:parent) { FactoryBot.create(:work_package, type: type_task) }
before do
work_package.parent_id = parent.id
work_package.save!
end
it "is #{'not' unless writable} writable" do
expect(subject.writable?(:version)).to eql(writable)
end
end
shared_examples_for 'with parent which is not a BACKLOGS type' do
let(:parent) { FactoryBot.create(:work_package, type: type_feature) }
before do
work_package.parent_id = parent.id
work_package.save!
end
it "is writable" do
expect(subject.writable?(:version)).to eql(true)
end
end
before do
login_as(current_user)
end
describe '#remaining_time_writable?' do
subject { described_class.new(work_package: work_package) }
context 'work_package is a leaf' do
before do
allow(work_package).to receive(:leaf?).and_return(true)
end
it 'is writable' do
expect(subject.writable?(:remaining_time)).to eql(true)
end
end
context 'work_package is no leaf' do
before do
allow(work_package).to receive(:leaf?).and_return(false)
end
it 'is not writable' do
expect(subject.writable?(:remaining_time)).to eql(false)
end
end
end
describe '#version_writable?' do
subject { described_class.new(work_package: work_package) }
let(:type_task) { FactoryBot.create(:type_task) }
let(:type_feature) { FactoryBot.create(:type_feature) }
before do
allow(WorkPackage).to receive(:backlogs_types).and_return([type_task.id])
allow(work_package).to receive(:backlogs_enabled?).and_return(true)
end
describe 'work_package is a task' do
before do
allow(work_package)
.to receive(:is_task?)
.and_return(true)
end
it_behaves_like 'with parent which is a BACKLOGS type', false
it_behaves_like 'with parent which is not a BACKLOGS type'
end
describe 'work_package is no task' do
before do
allow(work_package)
.to receive(:is_task?)
.and_return(false)
end
it_behaves_like 'with parent which is a BACKLOGS type', true
it_behaves_like 'with parent which is not a BACKLOGS type'
end
end
end
| 29.985075 | 91 | 0.687904 |
2681bbf699d24ab52597dec57c2e8982fff2c482 | 53 | class AmexTokenizationClient
VERSION = "0.3.0"
end
| 13.25 | 28 | 0.754717 |
7925d75f1d9140eed11c9f37ad50488d7a13778e | 535 | describe AvailabilityZoneController do
describe "#show" do
before do
EvmSpecHelper.create_guid_miq_server_zone
@zone = FactoryGirl.create(:availability_zone)
login_as FactoryGirl.create(:user_admin)
end
subject do
get :show, :params => {:id => @zone.id}
end
context "render listnav partial" do
render_views
it do
is_expected.to have_http_status 200
is_expected.to render_template(:partial => "layouts/listnav/_availability_zone")
end
end
end
end
| 23.26087 | 88 | 0.678505 |
913675eed23f1ce579dd9eb2363bbcf4e2f6350f | 2,375 | module AddImageInsidePdf
class TextReplaceProcessor < HexaPDF::Content::Processor
def initialize(page, to_hide_arr)
super()
@canvas = page.canvas(type: :overlay)
@to_hide_arr = to_hide_arr
@boxeslist = []
end
def show_text(str)
boxes = decode_text_with_positioning(str)
boxes.each do |box|
@boxeslist << box
end
end
def blackout_text()
@to_hide_arr.each do |hide_item|
@boxeslist.each_with_index do |box, index|
#puts sum_string(index, hide_item.length)
if hide_item == sum_string(index, hide_item.length)
blackout_array(index, hide_item.length)
end
end
end
end
def blackout_array(start_ind, end_ind)
sum = ""
i = start_ind
while i < start_ind+end_ind do
box = @boxeslist[i]
@canvas.fill_color(255, 255, 255)
x, y = *box.lower_left
tx, ty = *box.upper_right
@canvas.rectangle(x, y, tx - x, ty - y).fill
i +=1
end
end
def replace_text_to_image(writable_image, height=20)
@to_hide_arr.each do |hide_item|
@boxeslist.each_with_index do |box, index|
#puts sum_string(index, hide_item.length)
if hide_item == sum_string(index, hide_item.length)
write_image_to_array(index, hide_item.length, writable_image, height)
end
end
end
end
def write_image_to_array(start_ind, end_ind, writable_image, height)
sum = ""
i = start_ind
x1, y1 = false, false
while i < start_ind+end_ind do
box = @boxeslist[i]
@canvas.fill_color(255, 255, 255)
x, y = *box.lower_left
tx, ty = *box.upper_right
if i==start_ind
x1, y1 = x, y
end
@canvas.rectangle(x, y, tx - x, ty - y).fill
i +=1
end
if x1 && y1
@canvas.translate(0, 0) do
@canvas.image(writable_image, at: [x1, y1], height: height)
end
end
end
def sum_string(start_ind, end_ind)
sum = ""
i = start_ind
while i < start_ind+end_ind do
begin
sum += @boxeslist[i].string
rescue NoMethodError
print ""
end
i +=1
end
return sum
end
alias :show_text_with_positioning :show_text
end
end | 25.815217 | 81 | 0.574737 |
1a35fcdad36befd82198cb8d56cab4504720f68c | 615 | def hourglass(matrix)
max_hourglass_sum = - 1.0/0
max_iteration_count = matrix.length - 2 # assuming this only works because matrix is even
row_base = 0
while row_base < max_iteration_count
max_iteration_count.times do |i|
row_one_sum = matrix[row_base][i..i + 2].sum
row_two_sum = matrix[row_base + 1][i + 1]
row_three_sum = matrix[row_base + 2][i..i + 2].sum
hourglass_sum = row_one_sum + row_two_sum + row_three_sum
if hourglass_sum > max_hourglass_sum
max_hourglass_sum = hourglass_sum
end
end
row_base += 1
end
return max_hourglass_sum
end | 29.285714 | 91 | 0.691057 |
03eadd57982eb1e583a924f62c15b7ea24532255 | 612 | module Telegram
module Bot
module Types
class InlineQueryResultPhoto < Base
attribute :type, String, default: 'photo'
attribute :id, String
attribute :photo_url, String
attribute :thumb_url, String
attribute :photo_width, Integer
attribute :photo_height, Integer
attribute :title, String
attribute :description, String
attribute :caption, String
attribute :parse_mode, String
attribute :reply_markup, InlineKeyboardMarkup
attribute :input_message_content, InputMessageContent
end
end
end
end
| 29.142857 | 61 | 0.671569 |
4a41c66711c6ebf73532366672d943266f0c00ef | 9,555 | # frozen_string_literal: true
require "test_helper"
class EmailTypoTest < Minitest::Test # rubocop:disable Metrics/ClassLength
test "shows deprecation message" do
_, stderr = capture_io do
EmailTypo.fix("[email protected]")
end
assert_equal "EmailTypo.fix is deprecated; use EmailTypo.call instead.",
stderr.chomp
end
%w[
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
].each do |email|
test "fix gmail account (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
%w[
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
].each do |email|
test "fix international gmail account (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
%w[
[email protected]
[email protected]
[email protected]
].each do |email|
test "fix .co.jp account (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
%w[
[email protected]
[email protected]
].each do |email|
test "fix .co.br account (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
%w[
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
].each do |email|
test "fix googlemail account (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
%w[
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
].each do |email|
test "fix yahoo account (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
%w[
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
].each do |email|
test "fix hotmail account (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
%w[
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
].each do |email|
test "fix aol account (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
[
"jo\ [email protected]",
"jo\'[email protected]",
"[email protected]",
"john@#example.com",
"[email protected]",
"john@@example.com",
"john@example,com",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected],",
"[email protected].",
"[email protected]<",
"[email protected]>",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected],",
"[email protected].",
"[email protected]",
"[email protected]\"",
"[email protected]\'",
"[email protected]\\",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"john@examplecom",
"john\#@example.com",
"mailto:[email protected]",
"[email protected]",
"[email protected]"
].each do |email|
test "fix generic dot com account (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
%w[
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
john@examplenet
[email protected]
[email protected]
].each do |email|
test "fix dot net account (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
%w[
[email protected]
[email protected]
[email protected]
[email protected]
john@exampleorg
].each do |email|
test "fix dot org account (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
%w[
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
].each do |email|
test "don't mess with #{email}" do
assert_equal email, EmailTypo.call(email)
end
end
(EmailData.tlds - %w[unicom comsec et free om mm mo mom ne cm]).each do |tld|
test "accept #{tld} account" do
email = "john@example.#{tld}"
assert_equal email, EmailTypo.call(email)
end
end
%w[cm et ne om].each do |tld|
test "reject #{tld} account" do
email = "john@example.#{tld}"
refute_equal email, EmailTypo.call(email)
end
end
%w[
[email protected]
[email protected]
[email protected]
[email protected]
].each do |email|
test "fix verizon account (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
%w[
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
].each do |email|
test "fix icloud account (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
%w[
[email protected]
[email protected]
[email protected]
].each do |email|
test "fix outlook account (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
%w[
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
].each do |email|
test "fix comcast account (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
%w[
[email protected]
].each do |email|
test "fix extraneous numbers (#{email})" do
assert_equal "[email protected]", EmailTypo.call(email)
end
end
{
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]/.au" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"`[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]",
"[email protected]" => "[email protected]"
}.each do |actual, expected|
test "fix emails (#{actual})" do
assert_equal expected, EmailTypo.call(actual)
end
end
end
| 23.768657 | 79 | 0.624385 |
5d94998d9e7993c7eb059068bc627af1f5425d35 | 21,462 | # coding: utf-8
Rails.application.routes.draw do
namespace :mercury do
resources :images
end
mount Mercury::Engine => '/'
# The priority is based upon order of creation:
# first created -> highest priority.
get "/robots.txt" => RobotsGenerator
# URLs for sitemaps
#
# From Rails guide: By default dynamic segments don’t accept dots –
# this is because the dot is used as a separator for formatted
# routes. If you need to use a dot within a dynamic segment add a
# constraint which overrides this – for example :id => /[^\/]+/
# allows anything except a slash.
#
# That's why there's the constraints in generate URL to accept host
# parameter with dots
#
get "/sitemap.xml.gz" => "sitemap#sitemap", format: :xml
get "/sitemap/:sitemap_host/generate.xml.gz" => "sitemap#generate", format: :xml, :constraints => { sitemap_host: /[.\-\w]+/ }
# A route for DV test file
# A CA will check if there is a file in this route
get "/:dv_file" => "domain_validation#index", constraints: {dv_file: /.*\.txt/}
get "/design" => "design#design"
# config/routes.rb
if Rails.env.development?
mount MailPreview => 'mail_view'
end
# Some non-RESTful mappings
post '/webhooks/paypal_ipn' => 'paypal_ipn#ipn_hook', as: :paypal_ipn_hook
post '/webhooks/plans' => 'plans#create'
get '/webhooks/trials' => 'plans#get_trials'
post '/bounces' => 'amazon_bounces#notification'
get "/people/:person_id/inbox/:id", :to => redirect("/fi/people/%{person_id}/messages/%{id}")
get "/listings/new/:type" => "listings#new", :as => :new_request_without_locale # needed for some emails, where locale part is already set
get "/change_locale" => "i18n#change_locale", :as => :change_locale
# Internal API
namespace :int_api do
post "/create_trial_marketplace" => "marketplaces#create"
post "/prospect_emails" => "marketplaces#create_prospect_email"
resources :listings, only: [], defaults: { format: :json } do
member do
post :update_working_time_slots
end
end
end
# Harmony Proxy
# This endpoint proxies the requests to Harmony and does authorization
match '/harmony_proxy/*harmony_path' => 'harmony_proxy#proxy', via: :all
# UI API, i.e. internal endpoints for dynamic UI that doesn't belong to under any specific controller
get "/ui_api/topbar_props" => "topbar_api#props"
# Keep before /:locale/ routes, because there is locale 'vi', which matches '_lp_preview'
# and regexp anchors are not allowed in routing requirements.
get '/_lp_preview' => 'landing_page#preview'
locale_regex_string = Sharetribe::AVAILABLE_LOCALES.map { |l| l[:ident] }.concat(Sharetribe::REMOVED_LOCALES.to_a).join("|")
locale_matcher = Regexp.new(locale_regex_string)
locale_matcher_anchored = Regexp.new("^(#{locale_regex_string})$")
# Conditional routes for custom landing pages
get '/:locale/' => 'landing_page#index', as: :landing_page_with_locale, constraints: ->(request) {
locale_matcher_anchored.match(request.params["locale"]) &&
CustomLandingPage::LandingPageStore.enabled?(request.env[:current_marketplace]&.id)
}
get '/' => 'landing_page#index', as: :landing_page_without_locale, constraints: ->(request) {
CustomLandingPage::LandingPageStore.enabled?(request.env[:current_marketplace]&.id)
}
# Conditional routes for search view if landing page is enabled
get '/:locale/s' => 'homepage#index', as: :search_with_locale, constraints: ->(request) {
locale_matcher_anchored.match(request.params["locale"]) &&
CustomLandingPage::LandingPageStore.enabled?(request.env[:current_marketplace]&.id)
}
get '/s' => 'homepage#index', as: :search_without_locale, constraints: ->(request) {
CustomLandingPage::LandingPageStore.enabled?(request.env[:current_marketplace]&.id)
}
# Default routes for homepage, these are matched if custom landing page is not in use
# Inside this constraits are the routes that are used when request has subdomain other than www
get '/:locale/' => 'homepage#index', :constraints => { :locale => locale_matcher }, as: :homepage_with_locale
get '/' => 'homepage#index', as: :homepage_without_locale
get '/:locale/s', to: redirect('/%{locale}', status: 307), constraints: { locale: locale_matcher }
get '/s', to: redirect('/', status: 307)
# error handling: 3$: http://blog.plataformatec.com.br/2012/01/my-five-favorite-hidden-features-in-rails-3-2/
get '/500' => 'errors#server_error'
get '/404' => 'errors#not_found', :as => :error_not_found
get '/406' => 'errors#not_acceptable', :as => :error_not_acceptable
get '/410' => 'errors#gone', as: :error_gone
get '/community_not_found' => 'errors#community_not_found', as: :community_not_found
resources :communities, only: [:new, :create]
devise_for :people, only: :omniauth_callbacks, controllers: { omniauth_callbacks: "sessions" }
# Adds locale to every url right after the root path
scope "(/:locale)", :constraints => { :locale => locale_matcher } do
put '/mercury_update' => "mercury_update#update", :as => :mercury_update
get "/transactions/op_status/:process_token" => "transactions#paypal_op_status", as: :paypal_op_status
get "/transactions/transaction_op_status/:process_token" => "transactions#transaction_op_status", :as => :transaction_op_status
get "/transactions/created/:transaction_id" => "transactions#created", as: :transaction_created
get "/transactions/finalize_processed/:process_token" => "transactions#finalize_processed", as: :transaction_finalize_processed
# All new transactions (in the future)
get "/transactions/new" => "transactions#new", as: :new_transaction
# preauthorize flow
# Deprecated route (26-08-2016)
get "/listings/:listing_id/book", :to => redirect { |params, request|
"/#{params[:locale]}/listings/#{params[:listing_id]}/initiate?#{request.query_string}"
}
# Deprecated route (26-08-2016)
post "/listings/:listing_id/booked" => "preauthorize_transactions#initiated", as: :booked # POST request, no redirect
get "/listings/:listing_id/initiate" => "preauthorize_transactions#initiate", :as => :initiate_order
post "/listings/:listing_id/initiated" => "preauthorize_transactions#initiated", :as => :initiated_order
# free flow
post "/listings/:listing_id/create_contact" => "free_transactions#create_contact", :as => :create_contact
get "/listings/:listing_id/contact" => "free_transactions#contact", :as => :contact_to_listing
get "/logout" => "sessions#destroy", :as => :logout
get "/confirmation_pending" => "community_memberships#confirmation_pending", :as => :confirmation_pending
get "/login" => "sessions#new", :as => :login
get "/listing_bubble/:id" => "listings#listing_bubble", :as => :listing_bubble
get "/listing_bubble_multiple/:ids" => "listings#listing_bubble_multiple", :as => :listing_bubble_multiple
get '/:person_id/settings/payments' => 'payment_settings#index', :as => :person_payment_settings
post '/:person_id/settings/payments' => 'payment_settings#update', :as => :update_person_payment_settings
get '/:person_id/settings/payments/paypal_account' => 'paypal_accounts#index', :as => :paypal_account_settings_payment
# community membership related actions
get '/community_memberships/pending_consent' => 'community_memberships#pending_consent', as: :pending_consent
post '/community_memberships/give_consent' => 'community_memberships#give_consent', as: :give_consent
get '/community_memberships/access_denied' => 'community_memberships#access_denied', as: :access_denied
get '/community_memberships/check_email_availability_and_validity' => 'community_memberships#check_email_availability_and_validity'
get '/community_memberships/check_invitation_code' => 'community_memberships#check_invitation_code'
namespace :paypal_service do
resources :checkout_orders do
collection do
get :success
get :cancel
get :success_processed
end
end
end
namespace :admin do
get '' => "getting_started_guide#index"
# Payments
resources :payment_preferences, only: [:index], param: :payment_gateway do
collection do
put :common_update
put :update_stripe_keys
end
member do
get :disable
get :enable
end
end
# PayPal Connect
get "/paypal_preferences" => redirect("/%{locale}/admin/payment_preferences")
get "/paypal_preferences/account_create" => "paypal_preferences#account_create"
get "/paypal_preferences/permissions_verified" => "paypal_preferences#permissions_verified"
# Settings
get "/settings" => "communities#settings", as: :settings
patch "/settings" => "communities#update_settings", as: :update_settings
# Guide
get "getting_started_guide" => "getting_started_guide#index", as: :getting_started_guide
get "getting_started_guide/slogan_and_description" => "getting_started_guide#slogan_and_description", as: :getting_started_guide_slogan_and_description
get "getting_started_guide/cover_photo" => "getting_started_guide#cover_photo", as: :getting_started_guide_cover_photo
get "getting_started_guide/filter" => "getting_started_guide#filter", as: :getting_started_guide_filter
get "getting_started_guide/payment" => "getting_started_guide#payment", as: :getting_started_guide_payment
get "getting_started_guide/listing" => "getting_started_guide#listing", as: :getting_started_guide_listing
get "getting_started_guide/invitation" => "getting_started_guide#invitation", as: :getting_started_guide_invitation
# Details and look 'n feel
get "/look_and_feel/edit" => "communities#edit_look_and_feel", as: :look_and_feel_edit
patch "/look_and_feel" => "communities#update_look_and_feel", as: :look_and_feel
get "/details/edit" => "community_customizations#edit_details", as: :details_edit
patch "/details" => "community_customizations#update_details", as: :details
get "/new_layout" => "communities#new_layout", as: :new_layout
patch "/new_layout" => "communities#update_new_layout", as: :update_new_layout
# Topbar menu
get "/topbar/edit" => "communities#topbar", as: :topbar_edit
patch "/topbar" => "communities#update_topbar", as: :topbar
# Landing page menu
get "/landing_page" => "communities#landing_page", as: :landing_page
resources :communities do
member do
get :edit_welcome_email
post :create_sender_address
get :check_email_status
post :resend_verification_email
get :edit_text_instructions
get :test_welcome_email
get :social_media
get :analytics
put :social_media, to: 'communities#update_social_media'
put :analytics, to: 'communities#update_analytics'
delete :delete_marketplace
# DEPRECATED (2016-08-26)
# These routes are not in use anymore, don't use them
# See new "Topbar menu" routes above, outside of communities resource
get :topbar, to: redirect("/admin/topbar/edit")
put :topbar, to: "communities#update_topbar" # PUT request, no redirect
# also redirect old menu link requests to topbar
get :menu_links, to: redirect("/admin/topbar/edit")
put :menu_links, to: "communities#update_topbar" # PUT request, no redirect
# DEPRECATED (2016-07-07)
# These routes are not in use anymore, don't use them
# See new "Guide" routes above, outside of communities resource
get :getting_started, to: redirect('/admin/getting_started_guide')
# DEPRECATED (2016-03-22)
# These routes are not in use anymore, don't use them
# See new routes above, outside of communities resource
get :edit_details, to: redirect("/admin/details/edit")
put :update_details, to: "community_customizations#update_details" # PUT request, no redirect
get :edit_look_and_feel, to: redirect("/admin/look_and_feel/edit")
put :edit_look_and_feel, to: "community_customizations#update_look_and_feel" # PUT request, no redirect
# DEPRECATED (2016-03-22)
# These routes are not in use anymore, don't use them
# See the above :admin_settings routes, outside of :communities resource
get :settings, to: redirect("/admin/settings")
put :update_settings # PUT request, no redirect
get "getting_started_guide", to: redirect("/admin/getting_started_guide")
get "getting_started_guide/slogan_and_description", to: redirect("/admin/getting_started_guide/slogan_and_description")
get "getting_started_guide/cover_photo", to: redirect("/admin/getting_started_guide/cover_photo")
get "getting_started_guide/filter", to: redirect("/admin/getting_started_guide/filter")
get "getting_started_guide/paypal", to: redirect("/admin/getting_started_guide/paypal")
get "getting_started_guide/listing", to: redirect("/admin/getting_started_guide/listing")
get "getting_started_guide/invitation", to: redirect("/admin/getting_started_guide/invitation")
end
resources :transactions, controller: :community_transactions, only: :index
resources :conversations, controller: :community_conversations, only: [:index, :show]
resources :emails
resources :community_memberships do
member do
put :ban
put :unban
end
collection do
post :promote_admin
post :posting_allowed
end
end
resource :paypal_preferences, only: :index do
# DEPRECATED (2015-11-16)
# Do not add new routes here.
# See the above :paypal_preferences routes, outside of communities resource
member do
get :index, to: redirect("/admin/paypal_preferences")
post :preferences_update # POST request, no redirect
get :account_create, to: redirect("/admin/paypal_preferences/account_create")
get :permissions_verified, to: redirect("/admin/paypal_preferences/permissions_verified")
end
end
end
resources :custom_fields do
collection do
get :edit_price
get :edit_location
post :order
put :update_price
put :update_location
get :edit_expiration
put :update_expiration
end
end
resources :categories do
member do
get :remove
delete :destroy_and_move
end
collection do
post :order
end
end
resources :listing_shapes do
collection do
post :order
end
member do
get :close_listings
end
end
resource :plan, only: [:show]
end
resources :invitations, only: [:new, :create ] do
collection do
get :unsubscribe
end
end
resources :user_feedbacks, :controller => :feedbacks
resources :homepage do
collection do
get :sign_in
post :join
end
end
resources :listings do
member do
post :follow
delete :unfollow
end
collection do
get :new_form_content
get :edit_form_content
get :more_listings
get :browse
get :locations_json
get :verification_required
end
resources :comments, :only => [:create, :destroy]
resources :listing_images do
collection do
post :add_from_file
put :add_from_url
put :reorder
end
end
end
resources :listing_images do
member do
get :image_status
end
collection do
post :add_from_file
put :add_from_url
end
end
resources :infos do
collection do
get :about
get :how_to_use
get :terms
get :privacy
get :news
end
end
resource :terms do
member do
post :accept
end
end
resources :sessions do
collection do
post :request_new_password
post :change_mistyped_email
end
end
resources :consent
resource :sms do
get :message_arrived
end
devise_for :people, skip: :omniauth_callbacks, controllers: { confirmations: "confirmations", registrations: "people", omniauth_callbacks: "sessions"}, :path_names => { :sign_in => 'login'}
devise_scope :person do
# these matches need to be before the general resources to have more priority
get "/people/confirmation" => "confirmations#show", :as => :confirmation
put "/people/confirmation" => "confirmations#create"
get "/people/sign_up" => redirect("/%{locale}/login")
# List few specific routes here for Devise to understand those
get "/signup" => "people#new", :as => :sign_up
get '/people/auth/:provider/setup' => 'sessions#facebook_setup' #needed for devise setup phase hook to work
resources :people, param: :username, :path => "", :only => :show, :constraints => { :username => /[_a-z0-9]{3,20}/ }
resources :people, except: [:show] do
collection do
get :check_username_availability
get :check_email_availability
get :check_email_availability_and_validity
get :check_invitation_code
get :create_facebook_based
end
end
resources :people, except: [:show], :path => "" do
resources :listings do
member do
put :close
put :move_to_top
put :show_in_updates_email
end
end
resources :person_messages
resource :inbox, :only => [:show]
resources :messages, :controller => :conversations do
collection do
# This is only a redirect from old route, changed 2014-09-11
# You can clean up this later
get :received, to: 'inboxes#show'
end
member do
get :confirm, to: 'confirm_conversations#confirm'
get :cancel, to: 'confirm_conversations#cancel'
put :confirmation, to: 'confirm_conversations#confirmation' #TODO these should be under transaction
get :accept_preauthorized, to: 'accept_preauthorized_conversations#accept'
get :reject_preauthorized, to: 'accept_preauthorized_conversations#reject'
put :acceptance_preauthorized, to: 'accept_preauthorized_conversations#accepted_or_rejected'
end
resources :messages
resources :feedbacks, :controller => :testimonials do
collection do
put :skip
end
end
end
resource :paypal_account, only: [:index] do
member do
get :ask_order_permission
get :ask_billing_agreement
get :permissions_verified
get :billing_agreement_success
get :billing_agreement_cancel
end
end
resource :stripe_account, only: [:show, :update, :create] do
member do
put :send_verification
end
end
resources :transactions, only: [:show, :new, :create]
resource :settings do
member do
get :account
get :notifications
get :unsubscribe
end
end
resources :testimonials
resources :emails do
member do
post :send_confirmation
end
end
resources :followers
resources :followed_people
end # people
end # devise scope person
get "/:person_id/messages/:conversation_type/:id" => "conversations#show", :as => :single_conversation
get '/:person_id/settings/profile', to: redirect("/%{person_id}/settings") #needed to keep old links working
end # scope locale
id_to_username = Proc.new do |params, req|
username = Person.find(params[:person_id]).try(:username)
locale = params[:locale] + "/" if params[:locale]
if username
"/#{locale}#{username}#{params[:path]}"
else
"/404"
end
end
get "(/:locale)/people/:person_id(*path)" => redirect(id_to_username), :constraints => { :locale => locale_matcher, :person_id => /[a-zA-Z0-9_-]{22}/ }
get "(/:locale)/:person_id(*path)" => redirect(id_to_username), :constraints => { :locale => locale_matcher, :person_id => /[a-zA-Z0-9_-]{22}/ }
#keep this matcher last
#catches all non matched routes, shows 404 and logs more reasonably than the alternative RoutingError + stacktrace
match "*path" => "errors#not_found", via: :all
end
| 41.754864 | 193 | 0.649706 |
f7d8ba90e19331d6e4c67fba0c22ad905ca2b015 | 2,486 | require "rails_helper"
describe :users, type: :request do
let(:user) { FactoryBot.create(:user) }
before do
login!(user: user)
end
describe "#index" do
it "shows index" do
get users_path
expect(response).to render_template("users/index")
expect(page).to have_text(user.name)
end
end
describe "#edit" do
it "shows form" do
get edit_user_path(user)
expect(response).to render_template("users/edit")
expect(page).to have_text(user.name)
expect(page).not_to have_css("input#user_admin")
end
context "with admin" do
let(:user) { FactoryBot.create(:user, admin: true) }
let(:another_user) { FactoryBot.create(:user) }
it "shows another user form" do
get edit_user_path(another_user)
expect(response).to render_template("users/edit")
expect(page).to have_text(user.name)
expect(page).to have_css("input#user_admin")
end
end
context "with another user" do
let(:user) { FactoryBot.create(:user) }
let(:another_user) { FactoryBot.create(:user) }
it "returns 401" do
get edit_user_path(another_user)
expect(response).to have_http_status(401)
end
end
end
describe "#update" do
it "updates user" do
patch user_path(user), params: { user: { name: "foo" } }
expect(response).to redirect_to(edit_user_path(user))
expect(user.reload.name).to eq("foo")
end
context "with admin" do
let(:user) { FactoryBot.create(:user, admin: true) }
let(:another_user) { FactoryBot.create(:user) }
it "updates another user" do
patch user_path(another_user), params: { user: { name: "foo", admin: true } }
expect(response).to redirect_to(edit_user_path(another_user))
expect(another_user.reload.name).to eq("foo")
expect(another_user.admin).to eq(true)
end
end
context "with another user" do
let(:user) { FactoryBot.create(:user) }
let(:another_user) { FactoryBot.create(:user) }
it "returns 401" do
patch user_path(another_user), params: { user: { name: "foo" } }
expect(response).to have_http_status(401)
end
end
context "with normal user" do
let(:user) { FactoryBot.create(:user) }
it "cannot update admin column" do
patch user_path(user), params: { user: { admin: true } }
expect(response).to have_http_status(401)
end
end
end
end
| 28.574713 | 85 | 0.632341 |
ff5334877453b3658cb284d0824d11136b2d2f06 | 704 | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "pdf_renderer/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "pdf_renderer"
s.version = PdfRenderer::VERSION
s.authors = [""]
s.email = [""]
s.homepage = "TODO"
s.summary = "TODO: Summary of PdfRenderer."
s.description = "TODO: Description of PdfRenderer."
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["test/**/*"]
s.add_dependency "rails", "~> 4.2.5"
s.add_dependency "prawn", "0.12.0"
s.add_development_dependency "sqlite3"
end
| 28.16 | 85 | 0.634943 |
f774f3f21c93ecabb166f28ce49127523451cba8 | 245 | class CreateSettings < ActiveRecord::Migration[5.1]
def change
create_table :settings do |t|
t.string :name
t.string :slug
t.text :description
t.json :data
t.string :type
t.timestamps
end
end
end
| 17.5 | 51 | 0.620408 |
e96e0077f5ea097f7876b0048353d4640a3493ce | 1,345 | require 'test_helper'
class NewItemUsesControllerTest < ActionDispatch::IntegrationTest
setup do
@new_item_use = new_item_uses(:one)
end
test "should get index" do
get new_item_uses_url
assert_response :success
end
test "should get new" do
get new_new_item_use_url
assert_response :success
end
test "should create new_item_use" do
assert_difference('NewItemUse.count') do
post new_item_uses_url, params: { new_item_use: { generate_no: @new_item_use.generate_no, name: @new_item_use.name, result_no: @new_item_use.result_no } }
end
assert_redirected_to new_item_use_url(NewItemUse.last)
end
test "should show new_item_use" do
get new_item_use_url(@new_item_use)
assert_response :success
end
test "should get edit" do
get edit_new_item_use_url(@new_item_use)
assert_response :success
end
test "should update new_item_use" do
patch new_item_use_url(@new_item_use), params: { new_item_use: { generate_no: @new_item_use.generate_no, name: @new_item_use.name, result_no: @new_item_use.result_no } }
assert_redirected_to new_item_use_url(@new_item_use)
end
test "should destroy new_item_use" do
assert_difference('NewItemUse.count', -1) do
delete new_item_use_url(@new_item_use)
end
assert_redirected_to new_item_uses_url
end
end
| 27.44898 | 173 | 0.754647 |
edf3faccd3b17d531df9ba6bcd52dd4b24c3dd69 | 123 | require "test_helper"
class CharacterTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 15.375 | 45 | 0.707317 |
ffba2da05e5faabb33ff2972a18128e01d4ff5d8 | 248 | puts "Simple calculator - Division"
25.times { print "-" }
puts
puts "Enter the first number"
num_1 = gets.chomp
puts "Enter the second number"
num_2 = gets.chomp
puts "The first number divided by the second number is #{num_1.to_f / num_2.to_f}"
| 22.545455 | 82 | 0.729839 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.