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
|
---|---|---|---|---|---|
267ebb58aa3fe270efe43f7e19176817efe2bc9d | 486 | cask "dbeaver-community" do
version "21.0.3"
sha256 "c791977ef72976168f3761bdf633802a8b245ed36968b7b42ad169052b5dd068"
url "https://dbeaver.io/files/#{version}/dbeaver-ce-#{version}-macos.dmg"
name "DBeaver Community Edition"
desc "Free universal database tool and SQL client"
homepage "https://dbeaver.io/"
livecheck do
url "https://github.com/dbeaver/dbeaver"
strategy :github_latest
end
app "DBeaver.app"
caveats do
depends_on_java "8+"
end
end
| 23.142857 | 75 | 0.73251 |
d55031478b9e2f3c1943f7b6aa4cd4b03a131316 | 1,407 | module Squall
# OnApp Role
class Role < Base
# Return a list of Roles
def list
response = request(:get, '/roles.json')
response.collect { |role| role['role']}
end
# Returns a Hash of the given Role
def show(id)
response = request(:get, "/roles/#{id}.json")
response.first[1]
end
# Edit a Role
#
# ==== Options
#
# * +options+ - Params for editing the Role
# ==== Example
#
# edit :label => 'myrole', :permission => [1,3]
# edit :label => 'myrole', :permission => 1
def edit(id, options = {})
params.accepts(:label, :permission).validate!(options)
response = request(:put, "/roles/#{id}.json", default_params(options))
end
# Delete a Role
def delete(id)
request(:delete, "/roles/#{id}.json")
end
# Returns a list of permissions available
def permissions
response = request(:get, '/permissions.json')
response.collect { |perm| perm['permission'] }
end
# Create a new Role
#
# ==== Options
#
# * +options+ - Params for creating the Role
#
# ==== Example
#
# create :label => 'mypriv', :identifier => 'magic'
def create(options = {})
params.required(:label, :identifier).validate!(options)
response = request(:post, '/roles.json', default_params(options))
response.first[1]
end
end
end
| 24.684211 | 76 | 0.571429 |
012c052310464834339a489a3f3242a4e9594541 | 145 | FactoryGirl.define do
factory :pagemeta, class: Wordpress::Pagemeta do
meta_key "foo"
meta_value "FOO"
association :page
end
end
| 18.125 | 50 | 0.710345 |
21d335da5fbabc21331e74cb3312ceab41c70a6d | 4,663 | require 'digest/md5'
# get a temporary name for a script file to hold concatenated
# scripts in an html file
def concat_script_name html_name
name = "contcatenated-#{ html_name }#{'.js'}"
name.gsub /\//, "" #get rid of any /'s
end
# generate a name for a script file by taking a MD5
# hash of its contents
def hash_script_name path, opts = {}
opts[:prefix] ||= ""
opts[:ext] ||= ".js"
# hash the file and append.js
"#{opts[:prefix]}#{Digest::MD5.file(path).to_s}.js"
end
# concatenate the list of scripts, in order in one file
# specified by @output_path
def concat_scripts script_files, output_path
File.open output_path, "w" do |out|
script_files.each { |in_path| out.puts(IO.read(in_path)) }
end
end
# generate an html script tag for given src path
def script_tag src
"<script src='#{src}' type='text/javascript'></script>"
end
# create all leading dirs in a path if they do not
# exist
def create_leading_dirs path
dir_path = File.dirname(path)
FileUtils.mkdir_p dir_path unless File.exists? dir_path
end
namespace :build do
desc "build extension"
task :crx do
path = File.join @config[:proj_root_dir], @config[:publish_dir]
puts "packaging contents of #{path} as a .crx"
puts `#{@config[:chrome_command]} --pack-extension=#{path} --pack-extension-key=#{@config[:pem_path]}`
# have to manually move it where it needs to go:
`mv #{@config[:publish_dir]}.crx #{@config[:crx_path]}`
end
# TODO publishing to the chrome web store does not require a packed extension
# only a zip of its contents.
# desc "build extension"
# task :crx do
# `zip readium.zip -r readium/*`
# end
desc "Minify and copy all scripts into publish dir"
task :scripts => "create_workspace" do
puts "compressing the individual scripts and moving into #{@config[:publish_dir]}"
jsfiles = File.join(@config[:scripts_dir], "**", "*.js")
script_list = Dir.glob(jsfiles)
# remove any scripts that should be excluded
script_list.reject! {|path| @config[:exclude_scripts].include? path }
script_list.each do |in_path|
out_path = File.join(@config[:publish_dir], in_path)
# we need to create the leading subdirs because
# yui will fail if they do not exist
dir_path = File.dirname(out_path)
FileUtils.mkdir_p dir_path unless File.exists? dir_path
puts "compressing #{in_path}"
output = `java -jar #{@config[:cc_jar_path]} --js #{in_path} --js_output_file #{out_path}`
end
end
desc "copy over files that require no processing"
task :copy do
cops = @config[:simple_copies] + @config[:js_libs]
cops.each do |pattrn|
Dir.glob(pattrn).each do |in_path|
out_path = File.join(@config[:publish_dir], in_path)
create_leading_dirs out_path
if File.directory? in_path
FileUtils.mkdir_p out_path
else
FileUtils.cp in_path, out_path
end
end
end
end
desc "copy over the html files and replace script tags with ref to one concat script"
task :html do
@config[:html_files].each do |in_path|
out_path = File.join(@config[:publish_dir], in_path)
content = IO.read(in_path)
puts in_path
script_name = concat_script_name in_path
script_name = File.join @config[:publish_dir], @config[:scripts_dir], script_name
puts "concatenating scripts into #{script_name}"
x = @config[:scripts_regex].match content
x ||= ""
srcs = []
x.to_s.scan(/<script src=(['"])(.+?)\1 .+?<\/script>/) { |res| srcs << res[1]}
srcs.map! {|src| File.join @config[:publish_dir], src }
concat_scripts srcs, script_name
hash_name = hash_script_name script_name
hash_name = File.join "/", @config[:scripts_dir], hash_name
File.rename script_name, File.join(@config[:publish_dir], hash_name)
x = content.gsub @config[:scripts_regex], script_tag(hash_name)
out_path = File.join(@config[:publish_dir], in_path)
create_leading_dirs out_path
File.open out_path, "w" do |out|
out.puts x
end
end
end
desc "Create working dirs for the build process"
task :create_workspace => "clean:total" do
puts "creating the working dir"
puts `mkdir #{@config[:publish_dir]}`
end
namespace :clean do
desc "clean up the results of the last build"
task :total => ["publish", "crx"]
desc "remove the pubish direcory"
task :publish do
puts "removing the old publish dir if it exists"
`rm -rf #{@config[:publish_dir]}`
end
desc "remove the .crx file"
task :crx do
puts "removing the .crx file"
`rm #{@config[:crx_path]}`
end
end
desc "The default clean task"
task :clean => "clean:total"
end
#define the default build process
task :build => ["build:scripts", "build:copy", "build:html", "build:crx"] | 27.755952 | 104 | 0.695046 |
87aa44d7d0cbf0e6a30ceda84e4af6fb14d44d5d | 6,232 | module Xeroizer
module Record
class CreditNoteModel < BaseModel
set_permissions :read, :write, :update
include AttachmentModel::Extensions
public
# Retrieve the PDF version of the credit matching the `id`.
# @param [String] id invoice's ID.
# @param [String] filename optional filename to store the PDF in instead of returning the data.
def pdf(id, filename = nil)
pdf_data = @application.http_get(@application.client, "#{url}/#{CGI.escape(id)}", :response => :pdf)
if filename
File.open(filename, "w") { | fp | fp.write pdf_data }
nil
else
pdf_data
end
end
end
class CreditNote < Base
CREDIT_NOTE_STATUS = {
'AUTHORISED' => 'Approved credit_notes awaiting payment',
'DELETED' => 'Draft credit_notes that are deleted',
'DRAFT' => 'CreditNotes saved as draft or entered via API',
'PAID' => 'CreditNotes approved and fully paid',
'SUBMITTED' => 'CreditNotes entered by an employee awaiting approval',
'VOIDED' => 'Approved credit_notes that are voided'
} unless defined?(CREDIT_NOTE_STATUS)
CREDIT_NOTE_STATUSES = CREDIT_NOTE_STATUS.keys.sort
CREDIT_NOTE_TYPE = {
'ACCRECCREDIT' => 'Accounts Receivable',
'ACCPAYCREDIT' => 'Accounts Payable'
} unless defined?(CREDIT_NOTE_TYPE)
CREDIT_NOTE_TYPES = CREDIT_NOTE_TYPE.keys.sort
include Attachment::Extensions
set_primary_key :credit_note_id
set_possible_primary_keys :credit_note_id, :credit_note_number
list_contains_summary_only true
guid :credit_note_id
string :credit_note_number
string :reference
guid :branding_theme_id
string :type
date :date
date :due_date
string :status
string :line_amount_types
decimal :sub_total, :calculated => true
decimal :total_tax, :calculated => true
decimal :total, :calculated => true
datetime_utc :updated_date_utc, :api_name => 'UpdatedDateUTC'
string :currency_code
decimal :currency_rate
datetime :fully_paid_on_date
boolean :sent_to_contact
decimal :remaining_credit
decimal :applied_amount
boolean :has_attachments
belongs_to :contact
has_many :line_items
has_many :allocations
validates_inclusion_of :type, :in => CREDIT_NOTE_TYPES
validates_inclusion_of :status, :in => CREDIT_NOTE_STATUSES, :allow_blanks => true
validates_associated :contact
validates_associated :line_items
validates_associated :allocations, :allow_blanks => true
public
# Access the contact name without forcing a download of
# an incomplete, summary credit note.
def contact_name
attributes[:contact] && attributes[:contact][:name]
end
# Access the contact ID without forcing a download of an
# incomplete, summary credit note.
def contact_id
attributes[:contact] && attributes[:contact][:contact_id]
end
# Swallow assignment of attributes that should only be calculated automatically.
def sub_total=(value); raise SettingTotalDirectlyNotSupported.new(:sub_total); end
def total_tax=(value); raise SettingTotalDirectlyNotSupported.new(:total_tax); end
def total=(value); raise SettingTotalDirectlyNotSupported.new(:total); end
# Calculate sub_total from line_items.
def sub_total(always_summary = false)
if !always_summary && (new_record? || (!new_record? && line_items && line_items.size > 0))
overall_sum = (line_items || []).inject(BigDecimal.new('0')) { | sum, line_item | sum + line_item.line_amount }
# If the default amount types are inclusive of 'tax' then remove the tax amount from this sub-total.
overall_sum -= total_tax if line_amount_types == 'Inclusive'
overall_sum
else
attributes[:sub_total]
end
end
# Calculate total_tax from line_items.
def total_tax(always_summary = false)
if !always_summary && (new_record? || (!new_record? && line_items && line_items.size > 0))
(line_items || []).inject(BigDecimal('0')) { | sum, line_item | sum + line_item.tax_amount }
else
attributes[:total_tax]
end
end
# Calculate the total from line_items.
def total(always_summary = false)
unless always_summary
sub_total + total_tax
else
attributes[:total]
end
end
# Retrieve the PDF version of this credit note.
# @param [String] filename optional filename to store the PDF in instead of returning the data.
def pdf(filename = nil)
parent.pdf(id, filename)
end
def save
# Calling parse_save_response() on the credit note will wipe out
# the allocations, so we have to manually preserve them.
allocations_backup = self.allocations
if super
self.allocations = allocations_backup
allocate unless self.allocations.empty?
true
end
end
def allocate
if self.class.possible_primary_keys && self.class.possible_primary_keys.all? { | possible_key | self[possible_key].nil? }
raise RecordKeyMustBeDefined.new(self.class.possible_primary_keys)
end
request = association_to_xml(:allocations)
allocations_url = "#{parent.url}/#{CGI.escape(id)}/Allocations"
log "[ALLOCATION SENT] (#{__FILE__}:#{__LINE__}) \r\n#{request}"
response = parent.application.http_put(parent.application.client, allocations_url, request)
log "[ALLOCATION RECEIVED] (#{__FILE__}:#{__LINE__}) \r\n#{response}"
parse_save_response(response)
end
end
end
end
| 37.542169 | 131 | 0.616656 |
f7dc6858a90d1c93d898bb96f4e67f9ef1cc27f1 | 816 | module SpecSupport
module Carrierwave
RSpec.configure do |config|
config.after(:suite) do
FileUtils.rm_rf(Rails.root.join('spec', 'support', 'uploads'))
FileUtils.rm_rf(Rails.root.join('public', 'uploads', 'tmp'))
end
end
def test_image file_name, extension = 'png'
Rack::Test::UploadedFile.new(
File.join(Rails.root, 'spec', 'fixtures', "#{file_name}.#{extension}")
)
end
def sample_image
test_image :placeholder
end
def valid_image
test_image :profile_photo_valid
end
def too_small_dimensions_image
test_image :profile_photo_too_small_dimensions
end
def large_image
test_image :profile_photo_large
end
def non_white_list_image
test_image :placeholder, :bmp
end
end
end
| 21.473684 | 78 | 0.659314 |
1df637c41721223b50fdb79ff391bb7a14626eda | 729 | require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class I18nTest < ActiveSupport::TestCase
test "/config/locale/rails/de.yml is included in the I18n load_path" do
paths = I18n.load_path.map{|path| path.gsub(%r(.*/adva_cms/), '') }
paths.should include('locale/rails/de.yml')
end
test "correctly looks up english ar errormessage :invalid" do
I18n.t(:"activerecord.errors.messages.invalid").should == "is invalid"
end
test "correctly looks up german ar errormessage :invalid" do
I18n.t(:"activerecord.errors.messages.invalid", :locale => :de).should == "ist nicht gültig"
end
test "foo" do
true.should be_true
false.should be_false
nil.should be_nil
end
end
| 31.695652 | 96 | 0.70096 |
bb1241b1981aa7bfc13b9d5daa3a5822cd02af2c | 328 | cask 'reveal' do
version '15'
sha256 '57186d7df6c74ac763853adfb541c5c21255e857c227b1d8833a034a95a76bae'
url "https://download.revealapp.com/Reveal.app-#{version}.zip"
appcast 'https://revealapp.com/download/'
name 'Reveal'
homepage 'https://revealapp.com/'
depends_on macos: '>= :sierra'
app 'Reveal.app'
end
| 23.428571 | 75 | 0.734756 |
acc6fa159479af416d8a29f59b47f327beb71f8d | 2,209 | Shindo.tests('Fog::Parsers', 'core') do
class TestParser < Fog::Parsers::Base
def reset
super
reset_my_array
end
def reset_my_array
@my_array = []
end
def end_element(name)
case name
when 'key1', 'key2', 'key3', 'longText'
@response[name] = value
when 'myArray'
@response[name] = @my_array
reset_my_array
when 'id'
@my_array << value.to_i
end
end
end
@xml = %{
<MyResponse>
<MyObject>
<key1>value1</key1>
<key2>value2</key2>
<myArray>
<id>1</id>
<id>2</id>
<id>3</id>
</myArray>
<longText>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec quis metus arcu, quis cursus turpis.
Aliquam leo lacus, luctus vel iaculis id,
posuere eu odio. Donec sodales, ante porta condimentum
</longText>
<key3>value3</key3>
</MyObject>
<MyResponse>
}
@xmlNS = %{
<myns:MyResponse>
<myns:MyObject>
<myns:key1>value1</myns:key1>
<myns:key2>value2</myns:key2>
<myns:myArray>
<myns:id>1</myns:id>
<myns:id>2</myns:id>
<myns:id>3</myns:id>
</myns:myArray>
<myns:longText>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec quis metus arcu, quis cursus turpis.
Aliquam leo lacus, luctus vel iaculis id,
posuere eu odio. Donec sodales, ante porta condimentum
</myns:longText>
<myns:key3>value3</myns:key3>
</myns:MyObject>
<myns:MyResponse>
}
@response = {
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
'myArray' => [1,2,3],
'longText' => %{
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec quis metus arcu, quis cursus turpis.
Aliquam leo lacus, luctus vel iaculis id,
posuere eu odio. Donec sodales, ante porta condimentum
}
}
tests('TestParser').returns(@response, "returns the response") do
test_parser = TestParser.new
Nokogiri::XML::SAX::Parser.new(test_parser).parse(@xml)
test_parser.response
end
tests('TestParser for namespaces').returns(@response, "returns the response") do
test_parser = TestParser.new
Nokogiri::XML::SAX::Parser.new(test_parser).parse(@xmlNS)
test_parser.response
end
end
| 23.5 | 82 | 0.642372 |
bfdbf1d98dea8620c81ddcd141e97f11f497ef86 | 2,834 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2018_10_01
module Models
#
# Response for the ListVirtualNetworks API service call.
#
class VirtualNetworkListResult
include MsRestAzure
include MsRest::JSONable
# @return [Array<VirtualNetwork>] Gets a list of VirtualNetwork resources
# in a resource group.
attr_accessor :value
# @return [String] The URL to get the next set of results.
attr_accessor :next_link
# return [Proc] with next page method call.
attr_accessor :next_method
#
# Gets the rest of the items for the request, enabling auto-pagination.
#
# @return [Array<VirtualNetwork>] operation results.
#
def get_all_items
items = @value
page = self
while page.next_link != nil && !page.next_link.strip.empty? do
page = page.get_next_page
items.concat(page.value)
end
items
end
#
# Gets the next page of results.
#
# @return [VirtualNetworkListResult] with next page content.
#
def get_next_page
response = @next_method.call(@next_link).value! unless @next_method.nil?
unless response.nil?
@next_link = response.body.next_link
@value = response.body.value
self
end
end
#
# Mapper for VirtualNetworkListResult class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'VirtualNetworkListResult',
type: {
name: 'Composite',
class_name: 'VirtualNetworkListResult',
model_properties: {
value: {
client_side_validation: true,
required: false,
serialized_name: 'value',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'VirtualNetworkElementType',
type: {
name: 'Composite',
class_name: 'VirtualNetwork'
}
}
}
},
next_link: {
client_side_validation: true,
required: false,
serialized_name: 'nextLink',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 28.34 | 80 | 0.531757 |
6ad7094fe1a85d5eed7b98aa13c408e8f41984b0 | 4,831 | module DateQueries
module Adapter
class OracleEnhancedAdapter
def self.condition_string_for_range(field, start_date, end_date, *skip_args)
# Oracle related conditions string with skipped arguments
if skip_args.present?
if skip_args.include?(:year)
if skip_args.include?(:month)
# condition with month and year skipped
if start_date.strftime('%d') > end_date.strftime('%d')
<<-QUERY
to_char(#{field}, 'DD') BETWEEN ('#{start_date.in_time_zone.strftime('%d')}' AND '31')
OR to_char(#{field}, 'DD') BETWEEN ('01' AND '#{end_date.in_time_zone.strftime('%d')}')
QUERY
else
<<-QUERY
to_char(#{field}, 'DD') BETWEEN
'#{start_date.in_time_zone.strftime('%d')}' AND '#{end_date.in_time_zone.strftime('%d')}'
QUERY
end
elsif skip_args.include?(:date)
# condition with year and date skipped
if start_date.strftime('%m') > end_date.strftime('%m')
<<-QUERY
to_char(#{field}, 'MM') BETWEEN ('#{start_date.in_time_zone.strftime('%m')}' AND '12')
OR to_char(#{field}, 'MM') BETWEEN ('01' AND '#{end_date.in_time_zone.strftime('%m')}')
QUERY
else
<<-QUERY
to_char(#{field}, 'MM') BETWEEN
'#{start_date.in_time_zone.strftime('%m')}' AND '#{end_date.in_time_zone.strftime('%m')}'
QUERY
end
else
# condition with only year skipped
if start_date.strftime('%m%d') > end_date.strftime('%m%d')
<<-QUERY
to_char(#{field}, 'MMDD') BETWEEN ('#{start_date.in_time_zone.strftime('%m%d')}' AND '1231')
OR to_char(#{field}, 'MMDD') BETWEEN ('0101' AND '#{end_date.in_time_zone.strftime('%m%d')}')
QUERY
else
<<-QUERY
to_char(#{field}, 'MMDD') BETWEEN
'#{start_date.in_time_zone.strftime('%m%d')}' AND '#{end_date.in_time_zone.strftime('%m%d')}'
QUERY
end
end
elsif skip_args.include?(:month)
if skip_args.include?(:date)
# condition with month and date skipped
<<-QUERY
to_char(#{field}, 'YYYY') BETWEEN
'#{start_date.in_time_zone.strftime('%Y')}' AND '#{end_date.in_time_zone.strftime('%Y')}'
QUERY
else
# condition with only month skipped
<<-QUERY
to_char(#{field}, 'YYYYDD') BETWEEN
'#{start_date.in_time_zone.strftime('%Y%d')}' AND '#{end_date.in_time_zone.strftime('%Y%d')}'
QUERY
end
elsif skip_args.include?(:date)
# condition with only date skipped
<<-QUERY
to_char(#{field}, 'YYYYMM') BETWEEN
'#{start_date.in_time_zone.strftime('%Y%m')}' AND '#{end_date.in_time_zone.strftime('%Y%m')}'
QUERY
end
end
end
def self.condition_string_for_current_time(field, date, *skip_args)
if skip_args.include?(:year)
if skip_args.include?(:month)
# condition for date only
<<-QUERY
to_char(#{field}, 'DD') = '#{date.in_time_zone.strftime('%d')}'
QUERY
elsif skip_args.include?(:date)
# condition for month only
<<-QUERY
to_char(#{field}, 'MM') = '#{date.in_time_zone.strftime('%m')}'
QUERY
else
# condition for month and day only
<<-QUERY
to_char(#{field}, 'MMDD') = '#{date.in_time_zone.strftime('%m%d')}'
QUERY
end
elsif skip_args.include?(:month)
if skip_args.include?(:date)
# condition for year only
<<-QUERY
to_char(#{field}, 'YYYY') = '#{date.in_time_zone.strftime('%Y')}'
QUERY
else
# condition for year and date only
<<-QUERY
to_char(#{field}, 'YYYYDD') = '#{date.in_time_zone.strftime('%Y%d')}'
QUERY
end
elsif skip_args.include?(:date)
# condition for month and year only.
<<-QUERY
to_char(#{field}, 'YYYYMM') = '#{date.in_time_zone.strftime('%Y%m')}'
QUERY
else
# condition for checking current date without time
<<-QUERY
to_char(#{field}, 'YYYYMMDD') = '#{date.in_time_zone.strftime('%Y%m%d')}'
QUERY
end
end
end
end
end
| 39.598361 | 113 | 0.500931 |
87c2a2b5d01c1d354adcb20d689bbe70eb3176ee | 2,305 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe Course::Material::Folder, type: :model do
let!(:instance) { Instance.default }
with_tenant(:instance) do
subject(:ability) { Ability.new(user) }
let(:course) { create(:course) }
let(:root_folder) { course.root_folder }
let(:valid_folder) { build_stubbed(:folder, course: course) }
let(:not_started_folder) { build_stubbed(:folder, :not_started, course: course) }
let(:ended_folder) { build_stubbed(:folder, :ended, course: course) }
let(:started_linked_folder) do
create(:assessment, course: course, start_at: 1.day.ago).folder
end
let(:not_started_linked_folder) do
create(:assessment, course: course, start_at: 1.day.from_now).folder
end
context 'when the user is a Course Student' do
let(:user) { create(:course_student, course: course).user }
it { is_expected.to be_able_to(:show, valid_folder) }
it { is_expected.not_to be_able_to(:show, not_started_folder) }
it { is_expected.not_to be_able_to(:show, ended_folder) }
it { is_expected.to be_able_to(:show, started_linked_folder) }
it { is_expected.not_to be_able_to(:show, not_started_linked_folder) }
end
context 'when the user is a Course Staff' do
let(:user) { create(:course_manager, course: course).user }
it { is_expected.to be_able_to(:manage, valid_folder) }
it { is_expected.to be_able_to(:manage, not_started_folder) }
it { is_expected.to be_able_to(:manage, ended_folder) }
it { is_expected.not_to be_able_to(:manage, started_linked_folder) }
it { is_expected.to be_able_to(:show, started_linked_folder) }
it { is_expected.to be_able_to(:show, not_started_linked_folder) }
end
context 'when the user is a System Administrator' do
let(:user) { create(:administrator) }
it { is_expected.not_to be_able_to(:update, started_linked_folder) }
it { is_expected.not_to be_able_to(:edit, started_linked_folder) }
it { is_expected.not_to be_able_to(:destroy, started_linked_folder) }
it { is_expected.not_to be_able_to(:update, root_folder) }
it { is_expected.not_to be_able_to(:edit, root_folder) }
it { is_expected.not_to be_able_to(:destroy, root_folder) }
end
end
end
| 43.490566 | 85 | 0.704121 |
91d9fe8f398a7d0753252c942b8bdc72f74c6d80 | 1,020 | # provides a "random" value to cron based on the last bit of the machine IP address.
# used to avoid starting a certain cron job at the same time on all servers.
# if used with no parameters, it will return a single value between 0-59
# first argument is the occournce within a timeframe, for example if you want it to run 2 times per hour
# the second argument is the timeframe, by default its 60 minutes, but it could also be 24 hours etc
#
# example usage
# ip_to_cron() - returns one value between 0..59
# ip_to_cron(2) - returns an array of two values between 0..59
# ip_to_cron(2,24) - returns an array of two values between 0..23
module Puppet::Parser::Functions
newfunction(:ip_to_cron, :type => :rvalue) do |args|
occours = (args[0] || 1).to_i
scope = (args[1] || 60).to_i
ip = lookupvar('ipaddress').to_s.split('.')[3].to_i
base = ip % scope
if occours == 1
base
else
(1..occours).map { |i| (base - (scope / occours * i)) % scope }.sort
end
end
end
| 42.5 | 104 | 0.673529 |
ac21f81034979227b2e663a9af52d3a507ff6038 | 898 | class StatsController < ApplicationController
def show
render 'stats'
end
def gender_distribution
render json: {
male: Person.where(gender: Person::MALE).count,
female: Person.where(gender: Person::FEMALE).count
}
end
def average_lifespan_by_century
render json: lifespans
end
def name_popularity
render json: {
first_names: Person.all.group(:first_name).count,
last_names: Person.all.group(:last_name).count
}
end
private
# { 19: 66, 20: 80 }
def lifespans
Person
.all
.joins(:death)
.joins(:birth)
.where.not('deaths.date' => nil)
.where.not('births.date' => nil)
.group_by { |p| p.death.date.century }
.map do |century, people|
lifespan = people.map { |p| p.age(p.death.date) }.sum / people.count
{ century: century, lifespan: lifespan }
end
end
end
| 21.902439 | 76 | 0.624722 |
183df51973cad0286622f0dbf4020465c7b0b746 | 557 | class OwnersController < ApplicationController
def index
@owners = Owner.all
render json: @owners
end
def create
@owner = Owner.create(user_id: params[:user_id], player_id: params[:player_id])
players = PlayerValue.all
#write an object that takes the user_id as a key and then totals the position numbers
#write a short circuit function that says so long as the values don't exceed certain limits then save the post
render json: @owner
end
def destroy
@owner = Owner.findby(:id)
Owner.destroy(@owner)
end
end
| 23.208333 | 115 | 0.718133 |
5d7a480668812303917fe4e82c19d93fec39db8b | 943 | class Skewer < Formula
desc "Fast and accurate NGS adapter trimmer"
homepage "http://sourceforge.net/projects/skewer/"
# tag "bioinformatics"
# doi "10.1186/1471-2105-15-182"
url "https://github.com/relipmoc/skewer.git",
:revision => "e8e05fc506e94f964d671c7f0349585baf8d286c"
version "0.1.126"
bottle do
cellar :any_skip_relocation
sha256 "8d7c6e923b77aa9afb8c1334fa531dc34ecb77a00ebd5a0b7c0a5f499c1ddaf2" => :el_capitan
sha256 "a1396d4d7a617f8abd23b08e1d8ac0d9a995fa1872a556a6dff184513020a4dc" => :yosemite
sha256 "4f7f544bb0ec00a4ab303a4022cfa1c454034bc5b2be7f5613e3cc553e69d596" => :mavericks
sha256 "3d7443bd5e0356d3d1ec6e3185f818e5cedd3cf0d2e3e2444e16e1c22326f269" => :x86_64_linux
end
def install
system "make", "CXXFLAGS=-O2 -c"
bin.install "skewer"
doc.install "README.md", "LICENSE"
end
test do
assert_match "Nextera", shell_output("skewer --help 2>&1", 1)
end
end
| 32.517241 | 94 | 0.756098 |
6a072a6327ef0a240464e287ff637375f1c0aacd | 3,369 | module SimpleTk
##
# A helper class to make hash instance variables more accessible.
class GetSetHelper
##
# Creates a helper for a specific hash in a parent object.
#
# This helper does not support adding items to the connected hash.
#
# Parameters:
# parent::
# The parent object this helper accesses.
# hash_ivar::
# The name (as a symbol) of the instance variable in the parent object to access.
# (eg - :@data)
# auto_symbol::
# Should names be converted to symbols in the accessors, defaults to true.
# getter::
# The method or proc to call when getting a value.
# If this is a Symbol then it defines the method name of the retrieved value to call.
# If this is a Proc then it will be called with the retrieved value as an argument.
# If this is nil then the retrieved value is returned.
# setter::
# The method or proc to call when setting a value.
# If this is a Symbol then it defines the method name of the retrieved value to call with the new value.
# If this ia a Proc then it will be called with the retrieved value and the new value as arguments.
# If this is nil then the hash value is replaced with the new value.
# key_filter::
# If set to a proc keys are passed to this proc and only kept if the proc returns a true value.
# Any key rejected by the filter become unavailable via the helper.
#
# GetSetHelper.new(my_obj, :@data)
# GetSetHelper.new(my_obj, :@data, true, :value, :value=)
# GetSetHelper.new(my_obj, :@data, true, ->(v){ v.value }, ->(i,v){ i.value = v })
def initialize(parent, hash_ivar, auto_symbol = true, getter = nil, setter = nil, key_filter = nil)
@parent = parent
@hash_ivar = hash_ivar
@auto_symbol = auto_symbol
@getter = getter
@setter = setter
@key_filter = key_filter.is_a?(Proc) ? key_filter : nil
end
##
# Gets the available keys.
def keys
h = @parent.instance_variable_get(@hash_ivar)
if @key_filter
h.keys.select &@key_filter
else
h.keys.dup
end
end
##
# Gets the value for the given name.
def [](name)
name = name.to_sym if @auto_symbol
h = @parent.instance_variable_get(@hash_ivar)
if keys.include?(name)
v = h[name]
if @getter.is_a?(Symbol)
v.send @getter
elsif @getter.is_a?(Proc)
@getter.call v
else
v
end
else
raise IndexError
end
end
##
# Sets the value for the given name.
def []=(name, value)
name = name.to_sym if @auto_symbol
h = @parent.instance_variable_get(@hash_ivar)
if keys.include?(name)
if @setter.is_a?(Symbol)
h[name].send @setter, value
elsif @setter.is_a?(Proc)
@setter.call h[name], value
else
h[name] = value
end
else
raise IndexError
end
end
##
# Iterates over the hash.
def each
h = @parent.instance_variable_get(@hash_ivar)
if block_given?
keys.each do |k|
yield k, h[k]
end
elsif @key_filter
h.dup.keep_if{ |k,v| @key_filter.call(k) }.each
else
h.each
end
end
end
end | 30.908257 | 112 | 0.599584 |
b97e8cbc5c2818d67c4a30f46d9dee4f336075b3 | 1,704 | require 'test_helper'
class NullAssociationsTest < Minitest::Test
def test_non_null_object_belongs_to
supplier = Supplier.create!(name: 'test')
account = Account.create!(account_number: 1, supplier: supplier)
assert account.supplier_id == supplier.id
assert account.supplier.null? == false
end
def test_null_object_belongs_to
account = Account.create!(account_number: 1, supplier: nil)
assert account.supplier.is_a?(NullSupplier) == true
assert account.supplier.null? == true
end
def test_non_null_object_has_one
supplier = Supplier.create!(name: 'test')
account = Account.create!(account_number: 1, supplier: supplier)
assert supplier.account.id == account.id
assert supplier.account.null? == false
end
def test_null_object_has_one
supplier = Supplier.create!(name: 'test')
assert supplier.account.is_a?(NullAccount) == true
assert supplier.account.null? == true
end
def test_config_error
mock = Minitest::Mock.new
mock.expect(:config, mock)
mock.expect(:active_record, mock)
mock.expect(:belongs_to_required_by_default, true)
Rails::Application.stub(:new, mock) do
assert_raises ArgumentError do
Account.class_eval do
belongs_to :supplier, null_object: NullSupplier
end
end
end
end
def test_optional_false
assert_raises ArgumentError do
Account.class_eval do
belongs_to :supplier, optional: false, null_object: NullSupplier
end
end
end
def test_required_true
assert_raises ArgumentError do
Account.class_eval do
belongs_to :supplier, required: true, null_object: NullSupplier
end
end
end
end
| 27.934426 | 72 | 0.713615 |
bb2a53b9429c89466c69d18098e16b076e9ef6d9 | 109 | require "stripe"
Stripe.api_key = Rails.application.secrets.stripe_api_key
Stripe.api_version = "2015-10-16" | 27.25 | 57 | 0.807339 |
61bba28cbecdd7f1cae0b141de398712be0d4631 | 116 | class PublicKeysController < ApplicationController
def index
@public_keys = [Token.public_key.to_s]
end
end
| 19.333333 | 50 | 0.775862 |
e918e9c563833dfc54eadfff50eebecdb16dee54 | 1,565 | #
# Open Source Billing - A super simple software to create & send invoices to your customers and
# collect payments.
# Copyright (C) 2013 Mark Mian <[email protected]>
#
# This file is part of Open Source Billing.
#
# Open Source Billing 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 3 of the License, or
# (at your option) any later version.
#
# Open Source Billing 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 Open Source Billing. If not, see <http://www.gnu.org/licenses/>.
#
module DashboardHelper
def invoices_by_period period
Reporting::Dashboard.get_invoices_by_period period
end
def number_to_currency_dashboard(number, options={})
return nil unless number
symbol = options[:unit] || 'USD'
precision = options[:precision] || 2
old_currency = number_to_currency(number, {precision: precision})
old_currency.chr=='-' ? old_currency.slice!(1) : old_currency.slice!(0)
("#{old_currency} <#{options[:dom]}>#{symbol} </#{options[:dom]}>").html_safe
end
def aged_progress_width(amount, total)
return 0 if total.to_i.eql?(0) or (amount == 0 or amount == nil)
((amount * 100)/total).round
end
end
| 39.125 | 95 | 0.728435 |
28620236fa127006dc7a00bacdb483ab64969c51 | 20,630 | # frozen_string_literal: true
require 'spec_helper'
describe API::Groups do
include GroupAPIHelpers
let_it_be(:group, reload: true) { create(:group) }
let_it_be(:private_group) { create(:group, :private) }
let_it_be(:project) { create(:project, group: group) }
let_it_be(:user) { create(:user) }
let_it_be(:another_user) { create(:user) }
let(:admin) { create(:admin) }
before do
group.add_owner(user)
group.ldap_group_links.create cn: 'ldap-group', group_access: Gitlab::Access::MAINTAINER, provider: 'ldap'
end
describe "GET /groups" do
context "when authenticated as user" do
it "returns ldap details" do
get api("/groups", user)
expect(json_response).to(
satisfy_one { |group_json| group_json['ldap_cn'] == group.ldap_cn })
expect(json_response).to(
satisfy_one do |group_json|
group_json['ldap_access'] == group.ldap_access
end
)
expect(json_response).to(
satisfy_one do |group_json|
ldap_group_link = group_json['ldap_group_links'].first
ldap_group_link['cn'] == group.ldap_cn &&
ldap_group_link['group_access'] == group.ldap_access &&
ldap_group_link['provider'] == 'ldap'
end
)
end
end
end
describe 'GET /groups/:id' do
context 'group_ip_restriction' do
before do
create(:ip_restriction, group: private_group)
private_group.add_maintainer(user)
end
context 'when the group_ip_restriction feature is not available' do
before do
stub_licensed_features(group_ip_restriction: false)
end
it 'returns 200' do
get api("/groups/#{private_group.id}", user)
expect(response).to have_gitlab_http_status(:ok)
end
end
context 'when the group_ip_restriction feature is available' do
before do
stub_licensed_features(group_ip_restriction: true)
end
it 'returns 404 for request from ip not in the range' do
get api("/groups/#{private_group.id}", user)
expect(response).to have_gitlab_http_status(:not_found)
end
it 'returns 200 for request from ip in the range' do
get api("/groups/#{private_group.id}", user), headers: { 'REMOTE_ADDR' => '192.168.0.0' }
expect(response).to have_gitlab_http_status(:ok)
end
end
end
context 'marked_for_deletion_on attribute' do
context 'when feature is available' do
before do
stub_licensed_features(adjourned_deletion_for_projects_and_groups: true)
end
it 'is exposed' do
get api("/groups/#{group.id}", user)
expect(json_response).to have_key 'marked_for_deletion_on'
end
end
context 'when feature is not available' do
before do
stub_licensed_features(adjourned_deletion_for_projects_and_groups: false)
end
it 'is not exposed' do
get api("/groups/#{group.id}", user)
expect(json_response).not_to have_key 'marked_for_deletion_on'
end
end
end
end
describe 'PUT /groups/:id' do
subject { put api("/groups/#{group.id}", user), params: params }
context 'file_template_project_id' do
let(:params) { { file_template_project_id: project.id } }
it 'does not update file_template_project_id if unlicensed' do
stub_licensed_features(custom_file_templates_for_namespace: false)
expect { subject }.not_to change { group.reload.file_template_project_id }
expect(response).to have_gitlab_http_status(:ok)
expect(json_response).not_to have_key('file_template_project_id')
end
it 'updates file_template_project_id if licensed' do
stub_licensed_features(custom_file_templates_for_namespace: true)
expect { subject }.to change { group.reload.file_template_project_id }.to(project.id)
expect(response).to have_gitlab_http_status(:ok)
expect(json_response['file_template_project_id']).to eq(project.id)
end
end
context 'shared_runners_minutes_limit' do
let(:params) { { shared_runners_minutes_limit: 133 } }
context 'when authenticated as the group owner' do
it 'returns 200 if shared_runners_minutes_limit is not changing' do
group.update(shared_runners_minutes_limit: 133)
expect do
put api("/groups/#{group.id}", user), params: { shared_runners_minutes_limit: 133 }
end.not_to change { group.shared_runners_minutes_limit }
expect(response).to have_gitlab_http_status(:ok)
end
end
context 'when authenticated as the admin' do
let(:user) { create(:admin) }
it 'updates the group for shared_runners_minutes_limit' do
expect { subject }.to(
change { group.reload.shared_runners_minutes_limit }.from(nil).to(133))
expect(response).to have_gitlab_http_status(:ok)
expect(json_response['shared_runners_minutes_limit']).to eq(133)
end
end
end
end
describe "POST /groups" do
context "when authenticated as user with group permissions" do
it "creates an ldap_group_link if ldap_cn and ldap_access are supplied" do
group_attributes = attributes_for_group_api ldap_cn: 'ldap-group', ldap_access: Gitlab::Access::DEVELOPER
expect { post api("/groups", admin), params: group_attributes }.to change { LdapGroupLink.count }.by(1)
end
context 'when shared_runners_minutes_limit is given' do
context 'when the current user is not an admin' do
it "does not create a group with shared_runners_minutes_limit" do
group = attributes_for_group_api shared_runners_minutes_limit: 133
expect do
post api("/groups", another_user), params: group
end.not_to change { Group.count }
expect(response).to have_gitlab_http_status(:forbidden)
end
end
context 'when the current user is an admin' do
it "creates a group with shared_runners_minutes_limit" do
group = attributes_for_group_api shared_runners_minutes_limit: 133
expect do
post api("/groups", admin), params: group
end.to change { Group.count }.by(1)
created_group = Group.find(json_response['id'])
expect(created_group.shared_runners_minutes_limit).to eq(133)
expect(response).to have_gitlab_http_status(:created)
expect(json_response['shared_runners_minutes_limit']).to eq(133)
end
end
end
end
end
describe 'POST /groups/:id/ldap_sync' do
before do
allow(Gitlab::Auth::Ldap::Config).to receive(:enabled?).and_return(true)
end
context 'when the ldap_group_sync feature is available' do
before do
stub_licensed_features(ldap_group_sync: true)
end
context 'when authenticated as the group owner' do
context 'when the group is ready to sync' do
it 'returns 202 Accepted' do
ldap_sync(group.id, user, :disable!)
expect(response).to have_gitlab_http_status(:accepted)
end
it 'queues a sync job' do
expect { ldap_sync(group.id, user, :fake!) }.to change(LdapGroupSyncWorker.jobs, :size).by(1)
end
it 'sets the ldap_sync state to pending' do
ldap_sync(group.id, user, :disable!)
expect(group.reload.ldap_sync_pending?).to be_truthy
end
end
context 'when the group is already pending a sync' do
before do
group.pending_ldap_sync!
end
it 'returns 202 Accepted' do
ldap_sync(group.id, user, :disable!)
expect(response).to have_gitlab_http_status(:accepted)
end
it 'does not queue a sync job' do
expect { ldap_sync(group.id, user, :fake!) }.not_to change(LdapGroupSyncWorker.jobs, :size)
end
it 'does not change the ldap_sync state' do
expect do
ldap_sync(group.id, user, :disable!)
end.not_to change { group.reload.ldap_sync_status }
end
end
it 'returns 404 for a non existing group' do
ldap_sync(non_existing_record_id, user, :disable!)
expect(response).to have_gitlab_http_status(:not_found)
end
end
context 'when authenticated as the admin' do
it 'returns 202 Accepted' do
ldap_sync(group.id, admin, :disable!)
expect(response).to have_gitlab_http_status(:accepted)
end
end
context 'when authenticated as a non-owner user that can see the group' do
it 'returns 403' do
ldap_sync(group.id, another_user, :disable!)
expect(response).to have_gitlab_http_status(:forbidden)
end
end
context 'when authenticated as an user that cannot see the group' do
it 'returns 404' do
ldap_sync(private_group.id, user, :disable!)
expect(response).to have_gitlab_http_status(:not_found)
end
end
end
context 'when the ldap_group_sync feature is not available' do
before do
stub_licensed_features(ldap_group_sync: false)
end
it 'returns 404 (same as CE would)' do
ldap_sync(group.id, admin, :disable!)
expect(response).to have_gitlab_http_status(:not_found)
end
end
end
describe "GET /groups/:id/projects" do
context "when authenticated as user" do
let(:project_with_reports) { create(:project, :public, group: group) }
let!(:project_without_reports) { create(:project, :public, group: group) }
before do
create(:ee_ci_job_artifact, :sast, project: project_with_reports)
end
subject { get api("/groups/#{group.id}/projects", user), params: { with_security_reports: true } }
context 'when security dashboard is enabled for a group' do
let(:group) { create(:group_with_plan, plan: :gold_plan) } # overriding group from parent context
before do
stub_licensed_features(security_dashboard: true)
enable_namespace_license_check!
end
it "returns only projects with security reports" do
subject
expect(json_response.map { |p| p['id'] }).to contain_exactly(project_with_reports.id)
end
end
context 'when security dashboard is disabled for a group' do
it "returns all projects regardless of the security reports" do
subject
# using `include` since other projects may be added to this group from different contexts
expect(json_response.map { |p| p['id'] }).to include(project_with_reports.id, project_without_reports.id)
end
end
end
end
describe 'GET group/:id/audit_events' do
let(:path) { "/groups/#{group.id}/audit_events" }
context 'when authenticated, as a user' do
it_behaves_like '403 response' do
let(:request) { get api(path, create(:user)) }
end
end
context 'when authenticated, as a group owner' do
context 'audit events feature is not available' do
before do
stub_licensed_features(audit_events: false)
end
it_behaves_like '403 response' do
let(:request) { get api(path, user) }
end
end
context 'audit events feature is available' do
let_it_be(:group_audit_event_1) { create(:group_audit_event, created_at: Date.new(2000, 1, 10), entity_id: group.id) }
let_it_be(:group_audit_event_2) { create(:group_audit_event, created_at: Date.new(2000, 1, 15), entity_id: group.id) }
let_it_be(:group_audit_event_3) { create(:group_audit_event, created_at: Date.new(2000, 1, 20), entity_id: group.id) }
before do
stub_licensed_features(audit_events: true)
end
it 'returns 200 response' do
get api(path, user)
expect(response).to have_gitlab_http_status(:ok)
end
it 'includes the correct pagination headers' do
audit_events_counts = 3
get api(path, user)
expect(response).to include_pagination_headers
expect(response.headers['X-Total']).to eq(audit_events_counts.to_s)
expect(response.headers['X-Page']).to eq('1')
end
it 'does not include audit events of a different group' do
group = create(:group)
audit_event = create(:group_audit_event, created_at: Date.new(2000, 1, 20), entity_id: group.id)
get api(path, user)
audit_event_ids = json_response.map { |audit_event| audit_event['id'] }
expect(audit_event_ids).not_to include(audit_event.id)
end
context 'parameters' do
context 'created_before parameter' do
it "returns audit events created before the given parameter" do
created_before = '2000-01-20T00:00:00.060Z'
get api(path, user), params: { created_before: created_before }
expect(json_response.size).to eq 3
expect(json_response.first["id"]).to eq(group_audit_event_3.id)
expect(json_response.last["id"]).to eq(group_audit_event_1.id)
end
end
context 'created_after parameter' do
it "returns audit events created after the given parameter" do
created_after = '2000-01-12T00:00:00.060Z'
get api(path, user), params: { created_after: created_after }
expect(json_response.size).to eq 2
expect(json_response.first["id"]).to eq(group_audit_event_3.id)
expect(json_response.last["id"]).to eq(group_audit_event_2.id)
end
end
end
context 'response schema' do
it 'matches the response schema' do
get api(path, user)
expect(response).to match_response_schema('public_api/v4/audit_events', dir: 'ee')
end
end
end
end
end
describe 'GET group/:id/audit_events/:audit_event_id' do
let(:path) { "/groups/#{group.id}/audit_events/#{group_audit_event.id}" }
let_it_be(:group_audit_event) { create(:group_audit_event, created_at: Date.new(2000, 1, 10), entity_id: group.id) }
context 'when authenticated, as a user' do
it_behaves_like '403 response' do
let(:request) { get api(path, create(:user)) }
end
end
context 'when authenticated, as a group owner' do
context 'audit events feature is not available' do
before do
stub_licensed_features(audit_events: false)
end
it_behaves_like '403 response' do
let(:request) { get api(path, user) }
end
end
context 'audit events feature is available' do
before do
stub_licensed_features(audit_events: true)
end
context 'existent audit event' do
it 'returns 200 response' do
get api(path, user)
expect(response).to have_gitlab_http_status(:ok)
end
context 'response schema' do
it 'matches the response schema' do
get api(path, user)
expect(response).to match_response_schema('public_api/v4/audit_event', dir: 'ee')
end
end
context 'invalid audit_event_id' do
let(:path) { "/groups/#{group.id}/audit_events/an-invalid-id" }
it_behaves_like '400 response' do
let(:request) { get api(path, user) }
end
end
context 'non existent audit event' do
context 'non existent audit event of a group' do
let(:path) { "/groups/#{group.id}/audit_events/666777" }
it_behaves_like '404 response' do
let(:request) { get api(path, user) }
end
end
context 'existing audit event of a different group' do
let(:new_group) { create(:group) }
let(:audit_event) { create(:group_audit_event, created_at: Date.new(2000, 1, 10), entity_id: new_group.id) }
let(:path) { "/groups/#{group.id}/audit_events/#{audit_event.id}" }
it_behaves_like '404 response' do
let(:request) { get api(path, user) }
end
end
end
end
end
end
end
describe "DELETE /groups/:id" do
subject { delete api("/groups/#{group.id}", user) }
shared_examples_for 'immediately enqueues the job to delete the group' do
it do
Sidekiq::Testing.fake! do
expect { subject }.to change(GroupDestroyWorker.jobs, :size).by(1)
end
expect(response).to have_gitlab_http_status(:accepted)
end
end
context 'feature is available' do
before do
stub_licensed_features(adjourned_deletion_for_projects_and_groups: true)
end
context 'period for adjourned deletion is greater than 0' do
before do
stub_application_setting(deletion_adjourned_period: 1)
end
context 'success' do
it 'marks the group for adjourned deletion' do
subject
group.reload
expect(response).to have_gitlab_http_status(:accepted)
expect(group.marked_for_deletion_on).to eq(Date.today)
expect(group.deleting_user).to eq(user)
end
it 'does not immediately enqueue the job to delete the group' do
expect { subject }.not_to change(GroupDestroyWorker.jobs, :size)
end
end
context 'failure' do
before do
allow(::Groups::MarkForDeletionService).to receive_message_chain(:new, :execute).and_return({ status: :error, message: 'error' })
end
it 'returns error' do
subject
expect(response).to have_gitlab_http_status(:bad_request)
expect(json_response['message']).to eq('error')
end
end
end
context 'period of adjourned deletion is set to 0' do
before do
stub_application_setting(deletion_adjourned_period: 0)
end
it_behaves_like 'immediately enqueues the job to delete the group'
end
end
context 'feature is not available' do
before do
stub_licensed_features(adjourned_deletion_for_projects_and_groups: false)
end
it_behaves_like 'immediately enqueues the job to delete the group'
end
end
describe "POST /groups/:id/restore" do
let(:group) do
create(:group_with_deletion_schedule,
marked_for_deletion_on: 1.day.ago,
deleting_user: user)
end
subject { post api("/groups/#{group.id}/restore", user) }
context 'feature is available' do
before do
stub_licensed_features(adjourned_deletion_for_projects_and_groups: true)
end
context 'authenticated as owner' do
context 'restoring is successful' do
it 'restores the group to original state' do
subject
expect(response).to have_gitlab_http_status(:created)
expect(json_response['marked_for_deletion_on']).to be_falsey
end
end
context 'restoring fails' do
before do
allow(::Groups::RestoreService).to receive_message_chain(:new, :execute).and_return({ status: :error, message: 'error' })
end
it 'returns error' do
subject
expect(response).to have_gitlab_http_status(:bad_request)
expect(json_response['message']).to eq('error')
end
end
end
context 'authenticated as user without access to the group' do
subject { post api("/groups/#{group.id}/restore", another_user) }
it 'returns 403' do
subject
expect(response).to have_gitlab_http_status(:forbidden)
end
end
end
context 'feature is not available' do
before do
stub_licensed_features(adjourned_deletion_for_projects_and_groups: false)
end
it 'returns 404' do
subject
expect(response).to have_gitlab_http_status(:not_found)
end
end
end
def ldap_sync(group_id, user, sidekiq_testing_method)
Sidekiq::Testing.send(sidekiq_testing_method) do
post api("/groups/#{group_id}/ldap_sync", user)
end
end
end
| 32.437107 | 141 | 0.630441 |
ffbe18d7bd653610504e524228cbd6881b326fbd | 91 | class LogInController < ApplicationController
skip_before_action :authenticate_user!
end
| 22.75 | 45 | 0.868132 |
4a43ca1bf325e6af549fbc994d7734bcda07cb43 | 280 | module Exhibit
class PresenterGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
hook_for :test_framework
def create_presenter
template "presenter.rb", "app/presenters/#{file_name}_presenter.rb"
end
end
end
| 23.333333 | 73 | 0.735714 |
d56241f9cd5f1a483910d19ba70ab4226163302c | 25,815 | require 'abstract_unit'
require "active_support/log_subscriber/test_helper"
# common controller actions
module RequestForgeryProtectionActions
def index
render :inline => "<%= form_tag('/') {} %>"
end
def show_button
render :inline => "<%= button_to('New', '/') %>"
end
def unsafe
render plain: 'pwn'
end
def meta
render :inline => "<%= csrf_meta_tags %>"
end
def form_for_remote
render :inline => "<%= form_for(:some_resource, :remote => true ) {} %>"
end
def form_for_remote_with_token
render :inline => "<%= form_for(:some_resource, :remote => true, :authenticity_token => true ) {} %>"
end
def form_for_with_token
render :inline => "<%= form_for(:some_resource, :authenticity_token => true ) {} %>"
end
def form_for_remote_with_external_token
render :inline => "<%= form_for(:some_resource, :remote => true, :authenticity_token => 'external_token') {} %>"
end
def same_origin_js
render js: 'foo();'
end
def negotiate_same_origin
respond_to do |format|
format.js { same_origin_js }
end
end
def cross_origin_js
same_origin_js
end
def negotiate_cross_origin
negotiate_same_origin
end
end
# sample controllers
class RequestForgeryProtectionControllerUsingResetSession < ActionController::Base
include RequestForgeryProtectionActions
protect_from_forgery :only => %w(index meta same_origin_js negotiate_same_origin), :with => :reset_session
end
class RequestForgeryProtectionControllerUsingException < ActionController::Base
include RequestForgeryProtectionActions
protect_from_forgery :only => %w(index meta same_origin_js negotiate_same_origin), :with => :exception
end
class RequestForgeryProtectionControllerUsingNullSession < ActionController::Base
protect_from_forgery :with => :null_session
def signed
cookies.signed[:foo] = 'bar'
head :ok
end
def encrypted
cookies.encrypted[:foo] = 'bar'
head :ok
end
def try_to_reset_session
reset_session
head :ok
end
end
class PrependProtectForgeryBaseController < ActionController::Base
before_action :custom_action
attr_accessor :called_callbacks
def index
render inline: 'OK'
end
protected
def add_called_callback(name)
@called_callbacks ||= []
@called_callbacks << name
end
def custom_action
add_called_callback("custom_action")
end
def verify_authenticity_token
add_called_callback("verify_authenticity_token")
end
end
class FreeCookieController < RequestForgeryProtectionControllerUsingResetSession
self.allow_forgery_protection = false
def index
render :inline => "<%= form_tag('/') {} %>"
end
def show_button
render :inline => "<%= button_to('New', '/') %>"
end
end
class CustomAuthenticityParamController < RequestForgeryProtectionControllerUsingResetSession
def form_authenticity_param
'foobar'
end
end
class PerFormTokensController < ActionController::Base
protect_from_forgery :with => :exception
self.per_form_csrf_tokens = true
def index
render inline: "<%= form_tag (params[:form_path] || '/per_form_tokens/post_one'), method: params[:form_method] %>"
end
def button_to
render inline: "<%= button_to 'Button', (params[:form_path] || '/per_form_tokens/post_one'), method: params[:form_method] %>"
end
def post_one
render plain: ''
end
def post_two
render plain: ''
end
end
# common test methods
module RequestForgeryProtectionTests
def setup
@token = Base64.strict_encode64('railstestrailstestrailstestrails')
@old_request_forgery_protection_token = ActionController::Base.request_forgery_protection_token
ActionController::Base.request_forgery_protection_token = :custom_authenticity_token
end
def teardown
ActionController::Base.request_forgery_protection_token = @old_request_forgery_protection_token
end
def test_should_render_form_with_token_tag
@controller.stub :form_authenticity_token, @token do
assert_not_blocked do
get :index
end
assert_select 'form>input[name=?][value=?]', 'custom_authenticity_token', @token
end
end
def test_should_render_button_to_with_token_tag
@controller.stub :form_authenticity_token, @token do
assert_not_blocked do
get :show_button
end
assert_select 'form>input[name=?][value=?]', 'custom_authenticity_token', @token
end
end
def test_should_render_form_without_token_tag_if_remote
assert_not_blocked do
get :form_for_remote
end
assert_no_match(/authenticity_token/, response.body)
end
def test_should_render_form_with_token_tag_if_remote_and_embedding_token_is_on
original = ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms
begin
ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = true
assert_not_blocked do
get :form_for_remote
end
assert_match(/authenticity_token/, response.body)
ensure
ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = original
end
end
def test_should_render_form_with_token_tag_if_remote_and_external_authenticity_token_requested_and_embedding_is_on
original = ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms
begin
ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = true
assert_not_blocked do
get :form_for_remote_with_external_token
end
assert_select 'form>input[name=?][value=?]', 'custom_authenticity_token', 'external_token'
ensure
ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = original
end
end
def test_should_render_form_with_token_tag_if_remote_and_external_authenticity_token_requested
assert_not_blocked do
get :form_for_remote_with_external_token
end
assert_select 'form>input[name=?][value=?]', 'custom_authenticity_token', 'external_token'
end
def test_should_render_form_with_token_tag_if_remote_and_authenticity_token_requested
@controller.stub :form_authenticity_token, @token do
assert_not_blocked do
get :form_for_remote_with_token
end
assert_select 'form>input[name=?][value=?]', 'custom_authenticity_token', @token
end
end
def test_should_render_form_with_token_tag_with_authenticity_token_requested
@controller.stub :form_authenticity_token, @token do
assert_not_blocked do
get :form_for_with_token
end
assert_select 'form>input[name=?][value=?]', 'custom_authenticity_token', @token
end
end
def test_should_allow_get
assert_not_blocked { get :index }
end
def test_should_allow_head
assert_not_blocked { head :index }
end
def test_should_allow_post_without_token_on_unsafe_action
assert_not_blocked { post :unsafe }
end
def test_should_not_allow_post_without_token
assert_blocked { post :index }
end
def test_should_not_allow_post_without_token_irrespective_of_format
assert_blocked { post :index, format: 'xml' }
end
def test_should_not_allow_patch_without_token
assert_blocked { patch :index }
end
def test_should_not_allow_put_without_token
assert_blocked { put :index }
end
def test_should_not_allow_delete_without_token
assert_blocked { delete :index }
end
def test_should_not_allow_xhr_post_without_token
assert_blocked { post :index, xhr: true }
end
def test_should_allow_post_with_token
session[:_csrf_token] = @token
@controller.stub :form_authenticity_token, @token do
assert_not_blocked { post :index, params: { custom_authenticity_token: @token } }
end
end
def test_should_allow_patch_with_token
session[:_csrf_token] = @token
@controller.stub :form_authenticity_token, @token do
assert_not_blocked { patch :index, params: { custom_authenticity_token: @token } }
end
end
def test_should_allow_put_with_token
session[:_csrf_token] = @token
@controller.stub :form_authenticity_token, @token do
assert_not_blocked { put :index, params: { custom_authenticity_token: @token } }
end
end
def test_should_allow_delete_with_token
session[:_csrf_token] = @token
@controller.stub :form_authenticity_token, @token do
assert_not_blocked { delete :index, params: { custom_authenticity_token: @token } }
end
end
def test_should_allow_post_with_token_in_header
session[:_csrf_token] = @token
@request.env['HTTP_X_CSRF_TOKEN'] = @token
assert_not_blocked { post :index }
end
def test_should_allow_delete_with_token_in_header
session[:_csrf_token] = @token
@request.env['HTTP_X_CSRF_TOKEN'] = @token
assert_not_blocked { delete :index }
end
def test_should_allow_patch_with_token_in_header
session[:_csrf_token] = @token
@request.env['HTTP_X_CSRF_TOKEN'] = @token
assert_not_blocked { patch :index }
end
def test_should_allow_put_with_token_in_header
session[:_csrf_token] = @token
@request.env['HTTP_X_CSRF_TOKEN'] = @token
assert_not_blocked { put :index }
end
def test_should_allow_post_with_origin_checking_and_correct_origin
forgery_protection_origin_check do
session[:_csrf_token] = @token
@controller.stub :form_authenticity_token, @token do
assert_not_blocked do
@request.set_header 'HTTP_ORIGIN', 'http://test.host'
post :index, params: { custom_authenticity_token: @token }
end
end
end
end
def test_should_allow_post_with_origin_checking_and_no_origin
forgery_protection_origin_check do
session[:_csrf_token] = @token
@controller.stub :form_authenticity_token, @token do
assert_not_blocked do
post :index, params: { custom_authenticity_token: @token }
end
end
end
end
def test_should_block_post_with_origin_checking_and_wrong_origin
forgery_protection_origin_check do
session[:_csrf_token] = @token
@controller.stub :form_authenticity_token, @token do
assert_blocked do
@request.set_header 'HTTP_ORIGIN', 'http://bad.host'
post :index, params: { custom_authenticity_token: @token }
end
end
end
end
def test_should_warn_on_missing_csrf_token
old_logger = ActionController::Base.logger
logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new
ActionController::Base.logger = logger
begin
assert_blocked { post :index }
assert_equal 1, logger.logged(:warn).size
assert_match(/CSRF token authenticity/, logger.logged(:warn).last)
ensure
ActionController::Base.logger = old_logger
end
end
def test_should_not_warn_if_csrf_logging_disabled
old_logger = ActionController::Base.logger
logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new
ActionController::Base.logger = logger
ActionController::Base.log_warning_on_csrf_failure = false
begin
assert_blocked { post :index }
assert_equal 0, logger.logged(:warn).size
ensure
ActionController::Base.logger = old_logger
ActionController::Base.log_warning_on_csrf_failure = true
end
end
def test_should_only_allow_same_origin_js_get_with_xhr_header
assert_cross_origin_blocked { get :same_origin_js }
assert_cross_origin_blocked { get :same_origin_js, format: 'js' }
assert_cross_origin_blocked do
@request.accept = 'text/javascript'
get :negotiate_same_origin
end
assert_cross_origin_not_blocked { get :same_origin_js, xhr: true }
assert_cross_origin_not_blocked { get :same_origin_js, xhr: true, format: 'js'}
assert_cross_origin_not_blocked do
@request.accept = 'text/javascript'
get :negotiate_same_origin, xhr: true
end
end
# Allow non-GET requests since GET is all a remote <script> tag can muster.
def test_should_allow_non_get_js_without_xhr_header
session[:_csrf_token] = @token
assert_cross_origin_not_blocked { post :same_origin_js, params: { custom_authenticity_token: @token } }
assert_cross_origin_not_blocked { post :same_origin_js, params: { format: 'js', custom_authenticity_token: @token } }
assert_cross_origin_not_blocked do
@request.accept = 'text/javascript'
post :negotiate_same_origin, params: { custom_authenticity_token: @token}
end
end
def test_should_only_allow_cross_origin_js_get_without_xhr_header_if_protection_disabled
assert_cross_origin_not_blocked { get :cross_origin_js }
assert_cross_origin_not_blocked { get :cross_origin_js, format: 'js' }
assert_cross_origin_not_blocked do
@request.accept = 'text/javascript'
get :negotiate_cross_origin
end
assert_cross_origin_not_blocked { get :cross_origin_js, xhr: true }
assert_cross_origin_not_blocked { get :cross_origin_js, xhr: true, format: 'js' }
assert_cross_origin_not_blocked do
@request.accept = 'text/javascript'
get :negotiate_cross_origin, xhr: true
end
end
def test_should_not_raise_error_if_token_is_not_a_string
assert_blocked do
patch :index, params: { custom_authenticity_token: { foo: 'bar' } }
end
end
def assert_blocked
session[:something_like_user_id] = 1
yield
assert_nil session[:something_like_user_id], "session values are still present"
assert_response :success
end
def assert_not_blocked
assert_nothing_raised { yield }
assert_response :success
end
def assert_cross_origin_blocked
assert_raises(ActionController::InvalidCrossOriginRequest) do
yield
end
end
def assert_cross_origin_not_blocked
assert_not_blocked { yield }
end
def forgery_protection_origin_check
old_setting = ActionController::Base.forgery_protection_origin_check
ActionController::Base.forgery_protection_origin_check = true
begin
yield
ensure
ActionController::Base.forgery_protection_origin_check = old_setting
end
end
end
# OK let's get our test on
class RequestForgeryProtectionControllerUsingResetSessionTest < ActionController::TestCase
include RequestForgeryProtectionTests
setup do
@old_request_forgery_protection_token = ActionController::Base.request_forgery_protection_token
ActionController::Base.request_forgery_protection_token = :custom_authenticity_token
end
teardown do
ActionController::Base.request_forgery_protection_token = @old_request_forgery_protection_token
end
test 'should emit a csrf-param meta tag and a csrf-token meta tag' do
@controller.stub :form_authenticity_token, @token + '<=?' do
get :meta
assert_select 'meta[name=?][content=?]', 'csrf-param', 'custom_authenticity_token'
assert_select 'meta[name=?]', 'csrf-token'
regexp = "#{@token}<=\?"
assert_match(/#{regexp}/, @response.body)
end
end
end
class RequestForgeryProtectionControllerUsingNullSessionTest < ActionController::TestCase
class NullSessionDummyKeyGenerator
def generate_key(secret)
'03312270731a2ed0d11ed091c2338a06'
end
end
def setup
@request.env[ActionDispatch::Cookies::GENERATOR_KEY] = NullSessionDummyKeyGenerator.new
end
test 'should allow to set signed cookies' do
post :signed
assert_response :ok
end
test 'should allow to set encrypted cookies' do
post :encrypted
assert_response :ok
end
test 'should allow reset_session' do
post :try_to_reset_session
assert_response :ok
end
end
class RequestForgeryProtectionControllerUsingExceptionTest < ActionController::TestCase
include RequestForgeryProtectionTests
def assert_blocked
assert_raises(ActionController::InvalidAuthenticityToken) do
yield
end
end
end
class PrependProtectForgeryBaseControllerTest < ActionController::TestCase
PrependTrueController = Class.new(PrependProtectForgeryBaseController) do
protect_from_forgery prepend: true
end
PrependFalseController = Class.new(PrependProtectForgeryBaseController) do
protect_from_forgery prepend: false
end
PrependDefaultController = Class.new(PrependProtectForgeryBaseController) do
protect_from_forgery
end
def test_verify_authenticity_token_is_prepended
@controller = PrependTrueController.new
get :index
expected_callback_order = ["verify_authenticity_token", "custom_action"]
assert_equal(expected_callback_order, @controller.called_callbacks)
end
def test_verify_authenticity_token_is_not_prepended
@controller = PrependFalseController.new
get :index
expected_callback_order = ["custom_action", "verify_authenticity_token"]
assert_equal(expected_callback_order, @controller.called_callbacks)
end
def test_verify_authenticity_token_is_not_prepended_by_default
@controller = PrependDefaultController.new
get :index
expected_callback_order = ["custom_action", "verify_authenticity_token"]
assert_equal(expected_callback_order, @controller.called_callbacks)
end
end
class FreeCookieControllerTest < ActionController::TestCase
def setup
@controller = FreeCookieController.new
@token = "cf50faa3fe97702ca1ae"
super
end
def test_should_not_render_form_with_token_tag
SecureRandom.stub :base64, @token do
get :index
assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false
end
end
def test_should_not_render_button_to_with_token_tag
SecureRandom.stub :base64, @token do
get :show_button
assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false
end
end
def test_should_allow_all_methods_without_token
SecureRandom.stub :base64, @token do
[:post, :patch, :put, :delete].each do |method|
assert_nothing_raised { send(method, :index)}
end
end
end
test 'should not emit a csrf-token meta tag' do
SecureRandom.stub :base64, @token do
get :meta
assert @response.body.blank?
end
end
end
class CustomAuthenticityParamControllerTest < ActionController::TestCase
def setup
super
@old_logger = ActionController::Base.logger
@logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new
@token = Base64.strict_encode64(SecureRandom.random_bytes(32))
@old_request_forgery_protection_token = ActionController::Base.request_forgery_protection_token
ActionController::Base.request_forgery_protection_token = @token
end
def teardown
ActionController::Base.request_forgery_protection_token = @old_request_forgery_protection_token
super
end
def test_should_not_warn_if_form_authenticity_param_matches_form_authenticity_token
ActionController::Base.logger = @logger
begin
@controller.stub :valid_authenticity_token?, :true do
post :index, params: { custom_token_name: 'foobar' }
assert_equal 0, @logger.logged(:warn).size
end
ensure
ActionController::Base.logger = @old_logger
end
end
def test_should_warn_if_form_authenticity_param_does_not_match_form_authenticity_token
ActionController::Base.logger = @logger
begin
post :index, params: { custom_token_name: 'bazqux' }
assert_equal 1, @logger.logged(:warn).size
ensure
ActionController::Base.logger = @old_logger
end
end
end
class PerFormTokensControllerTest < ActionController::TestCase
def test_per_form_token_is_same_size_as_global_token
get :index
expected = ActionController::RequestForgeryProtection::AUTHENTICITY_TOKEN_LENGTH
actual = @controller.send(:per_form_csrf_token, session, '/path', 'post').size
assert_equal expected, actual
end
def test_accepts_token_for_correct_path_and_method
get :index
form_token = assert_presence_and_fetch_form_csrf_token
assert_matches_session_token_on_server form_token
# This is required because PATH_INFO isn't reset between requests.
@request.env['PATH_INFO'] = '/per_form_tokens/post_one'
assert_nothing_raised do
post :post_one, params: {custom_authenticity_token: form_token}
end
assert_response :success
end
def test_rejects_token_for_incorrect_path
get :index
form_token = assert_presence_and_fetch_form_csrf_token
assert_matches_session_token_on_server form_token
# This is required because PATH_INFO isn't reset between requests.
@request.env['PATH_INFO'] = '/per_form_tokens/post_two'
assert_raises(ActionController::InvalidAuthenticityToken) do
post :post_two, params: {custom_authenticity_token: form_token}
end
end
def test_rejects_token_for_incorrect_method
get :index
form_token = assert_presence_and_fetch_form_csrf_token
assert_matches_session_token_on_server form_token
# This is required because PATH_INFO isn't reset between requests.
@request.env['PATH_INFO'] = '/per_form_tokens/post_one'
assert_raises(ActionController::InvalidAuthenticityToken) do
patch :post_one, params: {custom_authenticity_token: form_token}
end
end
def test_rejects_token_for_incorrect_method_button_to
get :button_to, params: { form_method: 'delete' }
form_token = assert_presence_and_fetch_form_csrf_token
assert_matches_session_token_on_server form_token, 'delete'
# This is required because PATH_INFO isn't reset between requests.
@request.env['PATH_INFO'] = '/per_form_tokens/post_one'
assert_raises(ActionController::InvalidAuthenticityToken) do
patch :post_one, params: { custom_authenticity_token: form_token }
end
end
test "Accepts proper token for implicit post method on button_to tag" do
get :button_to
form_token = assert_presence_and_fetch_form_csrf_token
assert_matches_session_token_on_server form_token, 'post'
# This is required because PATH_INFO isn't reset between requests.
@request.env['PATH_INFO'] = '/per_form_tokens/post_one'
assert_nothing_raised do
post :post_one, params: { custom_authenticity_token: form_token }
end
end
%w{delete post patch}.each do |verb|
test "Accepts proper token for #{verb} method on button_to tag" do
get :button_to, params: { form_method: verb }
form_token = assert_presence_and_fetch_form_csrf_token
assert_matches_session_token_on_server form_token, verb
# This is required because PATH_INFO isn't reset between requests.
@request.env['PATH_INFO'] = '/per_form_tokens/post_one'
assert_nothing_raised do
send verb, :post_one, params: { custom_authenticity_token: form_token }
end
end
end
def test_accepts_global_csrf_token
get :index
token = @controller.send(:form_authenticity_token)
# This is required because PATH_INFO isn't reset between requests.
@request.env['PATH_INFO'] = '/per_form_tokens/post_one'
assert_nothing_raised do
post :post_one, params: {custom_authenticity_token: token}
end
assert_response :success
end
def test_ignores_params
get :index, params: {form_path: '/per_form_tokens/post_one?foo=bar'}
form_token = assert_presence_and_fetch_form_csrf_token
assert_matches_session_token_on_server form_token
# This is required because PATH_INFO isn't reset between requests.
@request.env['PATH_INFO'] = '/per_form_tokens/post_one?foo=baz'
assert_nothing_raised do
post :post_one, params: {custom_authenticity_token: form_token, baz: 'foo'}
end
assert_response :success
end
def test_ignores_trailing_slash_during_generation
get :index, params: {form_path: '/per_form_tokens/post_one/'}
form_token = assert_presence_and_fetch_form_csrf_token
# This is required because PATH_INFO isn't reset between requests.
@request.env['PATH_INFO'] = '/per_form_tokens/post_one'
assert_nothing_raised do
post :post_one, params: {custom_authenticity_token: form_token}
end
assert_response :success
end
def test_ignores_origin_during_generation
get :index, params: {form_path: 'https://example.com/per_form_tokens/post_one/'}
form_token = assert_presence_and_fetch_form_csrf_token
# This is required because PATH_INFO isn't reset between requests.
@request.env['PATH_INFO'] = '/per_form_tokens/post_one'
assert_nothing_raised do
post :post_one, params: {custom_authenticity_token: form_token}
end
assert_response :success
end
def test_ignores_trailing_slash_during_validation
get :index
form_token = assert_presence_and_fetch_form_csrf_token
# This is required because PATH_INFO isn't reset between requests.
@request.env['PATH_INFO'] = '/per_form_tokens/post_one/'
assert_nothing_raised do
post :post_one, params: {custom_authenticity_token: form_token}
end
assert_response :success
end
def test_method_is_case_insensitive
get :index, params: {form_method: "POST"}
form_token = assert_presence_and_fetch_form_csrf_token
# This is required because PATH_INFO isn't reset between requests.
@request.env['PATH_INFO'] = '/per_form_tokens/post_one/'
assert_nothing_raised do
post :post_one, params: {custom_authenticity_token: form_token}
end
assert_response :success
end
private
def assert_presence_and_fetch_form_csrf_token
assert_select 'input[name="custom_authenticity_token"]' do |input|
form_csrf_token = input.first['value']
assert_not_nil form_csrf_token
return form_csrf_token
end
end
def assert_matches_session_token_on_server(form_token, method = 'post')
actual = @controller.send(:unmask_token, Base64.strict_decode64(form_token))
expected = @controller.send(:per_form_csrf_token, session, '/per_form_tokens/post_one', method)
assert_equal expected, actual
end
end
| 30.842294 | 129 | 0.753593 |
265a981840a00b57711326126c4173e0a82dd7da | 5,267 | =begin
PureCloud Platform API
With the PureCloud Platform API, you can control all aspects of your PureCloud environment. With the APIs you can access the system configuration, manage conversations and more.
OpenAPI spec version: v2
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
License: UNLICENSED
https://help.mypurecloud.com/articles/terms-and-conditions/
Terms of Service: https://help.mypurecloud.com/articles/terms-and-conditions/
=end
require 'date'
module PureCloud
class QueueConversationScreenShareEventTopicJourneyCustomerSession
attr_accessor :id
attr_accessor :type
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'id' => :'id',
:'type' => :'type'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'id' => :'String',
:'type' => :'String'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v}
if attributes.has_key?(:'id')
self.id = attributes[:'id']
end
if attributes.has_key?(:'type')
self.type = attributes[:'type']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properies with the reasons
def list_invalid_properties
invalid_properties = Array.new
return invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
id == o.id &&
type == o.type
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[id, type].hash
end
# build the object from hash
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
else
#TODO show warning in debug mode
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
else
# data not found in attributes(hash), not an issue as the data can be optional
end
end
self
end
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /^(true|t|yes|y|1)$/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
_model = Object.const_get("PureCloud").const_get(type).new
_model.build_from_hash(value)
end
end
def to_s
to_hash.to_s
end
# to_body is an alias to to_body (backward compatibility))
def to_body
to_hash
end
# return the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Method to output non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
def _to_hash(value)
if value.is_a?(Array)
value.compact.map{ |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 23.202643 | 177 | 0.577179 |
3971a6c88372182812d195a727465dfeff515864 | 1,262 | class Ezstream < Formula
desc "Client for Icecast streaming servers"
homepage "https://icecast.org/ezstream/"
url "https://downloads.xiph.org/releases/ezstream/ezstream-0.6.0.tar.gz"
sha256 "f86eb8163b470c3acbc182b42406f08313f85187bd9017afb8b79b02f03635c9"
bottle do
cellar :any
rebuild 1
sha256 "8dda7ec4014a1c4f13a3a17f7e243b9e7153c069f5c8cff1a20c7b2518d78be6" => :high_sierra
sha256 "eee3cc2ed988d5c0e131d9ba8f0aef0e7bb520311096a9719b914c0a1ca6ffe4" => :sierra
sha256 "365c26a87addf50359e65ccd98ce4244b61f7e9015a335ff47bf55a90b35ad19" => :el_capitan
sha256 "dfa4b2537b1ce6b0da0c4214ccedca664bdd2e69962fa6579d9c437b1ff94e92" => :yosemite
sha256 "04e3a89b8b1e91ce160ec94c981b71d8fb08d7be8fef3da3f1c33b29dc9e3f8c" => :mavericks
end
depends_on "pkg-config" => :build
depends_on "libvorbis"
depends_on "libshout"
depends_on "theora"
depends_on "speex"
depends_on "libogg"
def install
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
test do
(testpath/"test.m3u").write test_fixtures("test.mp3").to_s
system bin/"ezstream", "-s", testpath/"test.m3u"
end
end
| 35.055556 | 93 | 0.733756 |
8771acb3798fa8e2898a97f86d08b15b0b144fbf | 1,567 | class Augeas < Formula
desc "Configuration editing tool and API"
homepage "https://augeas.net/"
url "http://download.augeas.net/augeas-1.12.0.tar.gz"
sha256 "321942c9cc32185e2e9cb72d0a70eea106635b50269075aca6714e3ec282cb87"
license "LGPL-2.1"
livecheck do
url "http://download.augeas.net/"
regex(/href=.*?augeas[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
sha256 "339c6898b7b3fd115fc3cc3c9a0cdb3eb6a1eab3f492e5f2de6513d7c6171c0e" => :big_sur
sha256 "00a45b8b446df0a95c2c45cbe608410df2d7be7787247f4b3a8fc1c2c19b41b6" => :catalina
sha256 "9a561491e3574dfe2cfe7da2a618c12d02218f88f760de46722d9b603e4f27ba" => :mojave
sha256 "0e1477f692cf67442dfcaf7c20a24733838df072ec867f59322070a7eaf3f925" => :high_sierra
sha256 "55b3fab93f2ec4a703dc2bb3b3d58c47375456bdb5f0308e0856b231d309c02d" => :sierra
end
head do
url "https://github.com/hercules-team/augeas.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "bison" => :build
depends_on "libtool" => :build
end
depends_on "pkg-config" => :build
depends_on "readline"
uses_from_macos "libxml2"
def install
args = %W[--disable-debug --disable-dependency-tracking --prefix=#{prefix}]
if build.head?
system "./autogen.sh", *args
else
system "./configure", *args
end
system "make", "install"
end
def caveats
<<~EOS
Lenses have been installed to:
#{HOMEBREW_PREFIX}/share/augeas/lenses/dist
EOS
end
test do
system bin/"augtool", "print", etc
end
end
| 27.017241 | 93 | 0.707722 |
4a4c7e8cceaa8e55a931fc0c0440babac076e0e5 | 2,410 | require 'helper'
class TestParserErrors < TestSlim
def test_correct_filename
source = %q{
doctype 5
div Invalid
}
assert_syntax_error "Unexpected indentation\n test.slim, Line 3\n div Invalid\n ^\n", source, :file => 'test.slim'
end
def test_unexpected_indentation
source = %q{
doctype 5
div Invalid
}
assert_syntax_error "Unexpected indentation\n (__TEMPLATE__), Line 3\n div Invalid\n ^\n", source
end
def test_unexpected_text_indentation
source = %q{
p
| text block
text
}
assert_syntax_error "Unexpected text indentation\n (__TEMPLATE__), Line 4\n text\n ^\n", source
end
def test_malformed_indentation
source = %q{
p
div Valid
div Invalid
}
assert_syntax_error "Malformed indentation\n (__TEMPLATE__), Line 4\n div Invalid\n ^\n", source
end
def test_unknown_line_indicator
source = %q{
p
div Valid
.valid
#valid
?invalid
}
assert_syntax_error "Unknown line indicator\n (__TEMPLATE__), Line 6\n ?invalid\n ^\n", source
end
def test_expected_closing_delimiter
source = %q{
p
img(src="img.jpg" title={title}
}
assert_syntax_error "Expected closing delimiter )\n (__TEMPLATE__), Line 3\n img(src=\"img.jpg\" title={title}\n ^\n", source
end
def test_expected_closing_attribute_delimiter
source = %q{
p
img src=[hash[1] + hash[2]
}
assert_syntax_error "Expected closing attribute delimiter ]\n (__TEMPLATE__), Line 3\n img src=[hash[1] + hash[2]\n ^\n", source
end
def test_expected_attribute
source = %q{
p
img(src='img.png' whatsthis?!)
}
assert_syntax_error "Expected attribute\n (__TEMPLATE__), Line 3\n img(src='img.png' whatsthis?!)\n ^\n", source
end
def test_invalid_empty_attribute
source = %q{
p
img{src= }
}
assert_syntax_error "Invalid empty attribute\n (__TEMPLATE__), Line 3\n img{src= }\n ^\n", source
end
def test_invalid_empty_attribute2
source = %q{
p
img{src=}
}
assert_syntax_error "Invalid empty attribute\n (__TEMPLATE__), Line 3\n img{src=}\n ^\n", source
end
def test_invalid_empty_attribute3
source = %q{
p
img src=
}
assert_syntax_error "Invalid empty attribute\n (__TEMPLATE__), Line 3\n img src=\n ^\n", source
end
end
| 22.314815 | 167 | 0.645643 |
e88f9f05cedb842c4b80ccabb1047e9f1d6abdbd | 2,284 | module Wrike3
class Base
def initialize(options={})
# API settings
Wrike3.api_version = options.fetch(:api_version) { 'v3' }
Wrike3.protocol = options.fetch(:protocol) { 'https' }
Wrike3.api_host = options.fetch(:api_host) { 'www.wrike.com' }
# Access settings
Wrike3.access_token = options.fetch(:access_token) { '' }
end
def site_url
"#{Wrike3.protocol}://#{Wrike3.api_host}"
end
# Returns the base url used in all Wrike API calls
def base_url
"#{site_url}/api/#{Wrike3.api_version}"
end
def account
@account ||= Wrike3::Account.new(self)
end
def attachment
@attachment ||= Wrike3::Attachment.new(self)
end
def comment
@comment ||= Wrike3::Comment.new(self)
end
def contact
@contact ||= Wrike3::Contact.new(self)
end
def folder
@folder ||= Wrike3::Folder.new(self)
end
def task
@task ||= Wrike3::Task.new(self)
end
def timelog
@timelog ||= Wrike3::Timelog.new(self)
end
def user
@user ||= Wrike3::User.new(self)
end
def workflow
@workflow ||= Wrike3::Workflow.new(self)
end
def token
@token ||= Wrike3::Token.new(self)
end
def execute(method, url, parameters = {}, request_headers = {}, include_auth_header = true, body = nil)
request_headers = auth_headers(request_headers) if include_auth_header
params = {:query => to_j(parameters), headers: request_headers}
params[:body] = body if body.present?
response = HTTParty.send(method.to_s, url, params)
response.parsed_response
end
private
def to_j(parameters = {})
parameters.each do |item|
if item.last.is_a?(Hash) || item.last.is_a?(Array)
parameters[item.first.to_s] = item.last.to_json
end
end
parameters
end
def auth_headers(options = {})
options.merge!('Authorization' => "Bearer #{Wrike3.access_token}")
options
end
end
class << self
attr_accessor :api_host,
:protocol,
:api_version,
:access_token
def configure
yield self
true
end
alias :config :configure
end
end
| 22.392157 | 107 | 0.593695 |
79f6393b446a99672fd1d0ba5a0e121fb72cff40 | 1,374 | module VCR
class Cassette
class Reader
def initialize(file_name, erb)
@file_name, @erb = file_name, erb
end
def read
return file_content unless use_erb?
binding = binding_for_variables if erb_variables
template.result(binding)
rescue NameError => e
handle_name_error(e)
end
private
def handle_name_error(e)
example_hash = (erb_variables || {}).merge(e.name => 'some value')
raise Errors::MissingERBVariableError.new(
"The ERB in the #{@file_name} cassette file references undefined variable #{e.name}. " +
"Pass it to the cassette using :erb => #{ example_hash.inspect }."
)
end
def use_erb?
!!@erb
end
def erb_variables
@erb if @erb.is_a?(Hash)
end
def file_content
@file_content ||= File.read(@file_name)
end
def template
@template ||= ERB.new(file_content)
end
@@struct_cache = Hash.new do |hash, attributes|
hash[attributes] = Struct.new(*attributes)
end
def variables_object
@variables_object ||= @@struct_cache[erb_variables.keys].new(*erb_variables.values)
end
def binding_for_variables
@binding_for_variables ||= variables_object.instance_eval { binding }
end
end
end
end
| 24.105263 | 99 | 0.60917 |
f81b1afdaff7acb00ac75e62e199ad061ee7947d | 12,016 | describe ResourceActionWorkflow do
let(:admin) { FactoryGirl.create(:user_with_group) }
context "#create" do
before do
@dialog = FactoryGirl.create(:dialog, :label => 'dialog')
@dialog_tab = FactoryGirl.create(:dialog_tab, :label => 'tab')
@dialog_group = FactoryGirl.create(:dialog_group, :label => 'group')
@dialog_field = FactoryGirl.create(:dialog_field_text_box, :label => 'field 1', :name => 'field_1')
@dialog_field2 = FactoryGirl.create(:dialog_field_text_box, :label => 'field 2', :name => 'field_2')
@dialog_tab.dialog_groups << @dialog_group
@dialog_group.dialog_fields << @dialog_field
@dialog_group.dialog_fields << @dialog_field2
@dialog.dialog_tabs << @dialog_tab
@resource_action = FactoryGirl.create(:resource_action, :action => "Provision", :dialog => @dialog)
end
it "new from resource_action" do
@wf = ResourceActionWorkflow.new({}, admin, @resource_action)
values = @wf.create_values_hash
expect(values.fetch_path(:workflow_settings, :resource_action_id)).to eq(@resource_action.id)
expect(@wf.dialog.id).to eq(@dialog.id)
end
it "new from hash" do
nh = {:workflow_settings => {:resource_action_id => @resource_action.id}}
@wf = ResourceActionWorkflow.new(nh, admin, nil)
values = @wf.create_values_hash
expect(values.fetch_path(:workflow_settings, :resource_action_id)).to eq(@resource_action.id)
expect(@wf.dialog.id).to eq(@dialog.id)
end
it "field_name_exists?" do
expect(@dialog.field_name_exist?('field_1')).to be_truthy
expect(@dialog.field_name_exist?('field_11')).to be_falsey
expect(@dialog.field_name_exist?('FIELD_11')).to be_falsey
expect(@dialog.field_name_exist?(:field_11)).to be_falsey
end
context "with workflow" do
let(:data) { {"parameters" => {"field_1" => "new_value"}} }
before do
@wf = ResourceActionWorkflow.new({}, admin, @resource_action)
end
it "set_value" do
@wf.set_value(:field_1, "test_var_1")
expect(@wf.value(:field_1)).to eq("test_var_1")
end
it "#validate" do
expect { @wf.validate(nil) }.to_not raise_error
end
it "#update_dialog_field_values" do
@wf.update_dialog_field_values(data)
expect(dialog_fields(@dialog)).to eq("field_1" => "new_value", "field_2" => nil)
end
end
context "#submit_request" do
subject { ResourceActionWorkflow.new({}, admin, resource_action, :target => target) }
let(:resource_action) { @resource_action }
context "with blank data" do
let(:data) { {} }
context "with request class" do
let(:target) { FactoryGirl.create(:service) }
it "creates requests" do
EvmSpecHelper.local_miq_server
expect(subject).to receive(:make_request).and_call_original
expect(AuditEvent).to receive(:success).with(
:event => "service_reconfigure_request_created",
:target_class => "Service",
:userid => admin.userid,
:message => "Service Reconfigure requested by <#{admin.userid}> for Service:[#{target.id}]"
)
expect(dialog_fields(@dialog)).to eq("field_1" => nil, "field_2" => nil)
response = subject.submit_request(data)
expect(response).to include(:errors => [])
end
end
context "without request class" do
subject { ResourceActionWorkflow.new({}, admin, resource_action, :target => target) }
let(:resource_action) { @resource_action }
let(:target) { FactoryGirl.create(:vm_vmware) }
it "calls automate" do
EvmSpecHelper.local_miq_server
expect(subject).not_to receive(:make_request)
expect_any_instance_of(ResourceAction).to receive(:deliver_to_automate_from_dialog).and_call_original
expect(MiqAeEngine).to receive(:deliver_queue) # calls into automate
expect(AuditEvent).not_to receive(:success)
expect(dialog_fields(@dialog)).to eq("field_2" => nil, "field_1" => nil)
response = subject.submit_request(data)
expect(response).to eq(:errors => [])
end
end
context "with custom button request" do
let(:target) { FactoryGirl.build(:service) }
let(:options) { {} }
let(:resource_action) do
@resource_action.tap do |ra|
ra.update_attributes(:resource => FactoryGirl.create(:custom_button, :applies_to_class => target.class.name, :options => options))
end
end
it "calls automate" do
expect(subject).not_to receive(:make_request)
expect_any_instance_of(ResourceAction).to receive(:deliver_to_automate_from_dialog)
subject.submit_request(data)
expect(dialog_fields(@dialog)).to eq("field_1" => nil, "field_2" => nil)
end
it "calls automate with miq_task" do
options[:open_url] = true
allow(resource_action).to(receive(:deliver_to_automate_from_dialog))
allow(subject).to(receive(:load_resource_action)).and_return(resource_action)
result = subject.submit_request
miq_task = MiqTask.find(result[:task_id])
expect(miq_task.state).to(eq(MiqTask::STATE_QUEUED))
expect(miq_task.status).to(eq(MiqTask::STATUS_OK))
expect(miq_task.message).to(eq('MiqTask has been queued.'))
end
end
end
context "with non-blank data" do
let(:data) { {"parameters" => {"field_1" => "new_value"}} }
context "with request class" do
let(:target) { FactoryGirl.create(:service) }
it "creates requests" do
EvmSpecHelper.local_miq_server
expect(subject).to receive(:make_request).and_call_original
expect(AuditEvent).to receive(:success).with(
:event => "service_reconfigure_request_created",
:target_class => "Service",
:userid => admin.userid,
:message => "Service Reconfigure requested by <#{admin.userid}> for Service:[#{target.id}]"
)
response = subject.submit_request(data)
expect(dialog_fields(@dialog)).to eq("field_1" => "new_value", "field_2" => nil)
expect(response).to include(:errors => [])
end
end
context "without request class" do
subject { ResourceActionWorkflow.new({}, admin, resource_action, :target => target) }
let(:resource_action) { @resource_action }
let(:target) { FactoryGirl.create(:vm_vmware) }
it "calls automate" do
EvmSpecHelper.local_miq_server
expect(subject).not_to receive(:make_request)
expect_any_instance_of(ResourceAction).to receive(:deliver_to_automate_from_dialog).and_call_original
expect(MiqAeEngine).to receive(:deliver_queue) # calls into automate
expect(AuditEvent).not_to receive(:success)
response = subject.submit_request(data)
expect(dialog_fields(@dialog)).to eq("field_2" => nil, "field_1" => "new_value")
expect(response).to eq(:errors => [])
end
end
context "with custom button request" do
let(:target) { FactoryGirl.build(:service) }
let(:options) { {} }
let(:resource_action) do
@resource_action.tap do |ra|
ra.update_attributes(:resource => FactoryGirl.create(:custom_button, :applies_to_class => target.class.name, :options => options))
end
end
it "calls automate" do
expect(subject).not_to receive(:make_request)
expect_any_instance_of(ResourceAction).to receive(:deliver_to_automate_from_dialog)
subject.submit_request(data)
expect(dialog_fields(@dialog)).to eq("field_2" => nil, "field_1" => "new_value")
end
it "calls automate with miq_task" do
options[:open_url] = true
allow(resource_action).to(receive(:deliver_to_automate_from_dialog))
allow(subject).to(receive(:load_resource_action)).and_return(resource_action)
result = subject.submit_request
miq_task = MiqTask.find(result[:task_id])
expect(miq_task.state).to(eq(MiqTask::STATE_QUEUED))
expect(miq_task.status).to(eq(MiqTask::STATUS_OK))
expect(miq_task.message).to(eq('MiqTask has been queued.'))
end
end
end
end
end
describe "#initialize #load_dialog" do
let(:resource_action) { instance_double("ResourceAction", :id => 123, :dialog => dialog) }
let(:dialog) { instance_double("Dialog", :id => 321) }
let(:values) { "the values" }
before do
allow(ResourceAction).to receive(:find).and_return(resource_action)
allow(dialog).to receive(:load_values_into_fields).with(values)
allow(dialog).to receive(:initialize_value_context).with(values)
allow(dialog).to receive(:init_fields_with_values_for_request).with(values)
allow(dialog).to receive(:target_resource=)
end
context "when the options set display_view_only to true" do
let(:options) { {:display_view_only => true} }
it "calls init_fields_with_values_for_request" do
expect(dialog).to receive(:init_fields_with_values_for_request).with(values)
ResourceActionWorkflow.new(values, nil, resource_action, options)
end
end
context "when the options set init_defaults to true" do
let(:options) { {:init_defaults => true} }
it "calls init_fields_with_values_for_request" do
expect(dialog).to receive(:initialize_value_context).with(values).ordered
expect(dialog).to receive(:load_values_into_fields).with(values, false).ordered
ResourceActionWorkflow.new(values, nil, resource_action, options)
end
end
context "when the options are set to a refresh request" do
let(:options) { {:refresh => true} }
it "loads the values into fields" do
expect(dialog).to receive(:load_values_into_fields).with(values)
ResourceActionWorkflow.new(values, nil, resource_action, options)
end
end
context "when the options are set to a reconfigure request" do
let(:options) { {:reconfigure => true} }
it "initializes the fields with the given values" do
expect(dialog).to receive(:initialize_with_given_values).with(values)
ResourceActionWorkflow.new(values, nil, resource_action, options)
end
end
context "when the options are set to a submit workflow request" do
let(:options) { {:submit_workflow => true} }
it "loads the values into fields" do
expect(dialog).to receive(:load_values_into_fields).with(values)
ResourceActionWorkflow.new(values, nil, resource_action, options)
end
end
context "when the options are set to a provision workflow request" do
let(:options) { {:provision_workflow => true} }
it "initializes the value context and then loads the values into fields" do
expect(dialog).to receive(:initialize_value_context).with(values).ordered
expect(dialog).to receive(:load_values_into_fields).with(values, false).ordered
ResourceActionWorkflow.new(values, nil, resource_action, options)
end
end
context "when neither display_view_only nor refresh are true" do
let(:options) { {} }
it "initializes the value context" do
expect(dialog).to receive(:initialize_value_context).with(values)
ResourceActionWorkflow.new(values, nil, resource_action, options)
end
end
end
def dialog_fields(dialog)
dialog.dialog_fields.map { |df| [df.name, df.value] }.to_h
end
end
| 41.150685 | 144 | 0.641561 |
e2fd642cc2e98de05bf7ecd9015c01d2fd1be77f | 2,388 | require 'spec_helper'
class TestController
include FacebookSession::Helper
def initialize(options = {})
@fb_session = options[:fb_session]
@signed_request = options[:signed_request]
end
def cookies
{ "fbsr_foo" => @fb_session }
end
def params
{ signed_request: @signed_request }
end
end
describe FacebookSession::Helper do
before(:all) { FacebookSession.configure(application_id: "foo", application_secret: "bar") }
let(:json) { '{"user_id": "123", "oauth_token": "abc", "algorithm": "sha256", "issued_at": "2014"}' }
let(:payload) { Base64.urlsafe_encode64(json) }
let(:digest) { Base64.urlsafe_encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), "bar", payload)) }
let(:message) { "#{digest}.#{payload}" }
let(:controller) { TestController.new }
describe "#facebook_session" do
subject { controller.facebook_session }
context "without session data" do
it { is_expected.to eq(nil) }
end
context "with session data" do
let(:controller) { TestController.new(fb_session: message) }
it { is_expected.to be_a(FacebookSession::Session) }
it "should decode the message" do
expect(subject.user_id).to eq("123")
end
end
end
describe "#facebook_session?" do
subject { controller.facebook_session? }
context "without session data" do
it { is_expected.to eq(false) }
end
context "with session data" do
let(:controller) { TestController.new(fb_session: message) }
it { is_expected.to eq(true) }
end
end
describe "#facebook_signed_request" do
subject { controller.facebook_signed_request }
context "without a signed request" do
it { is_expected.to eq(nil) }
end
context "with a signed request" do
let(:controller) { TestController.new(signed_request: message) }
it { is_expected.to be_a(FacebookSession::SignedRequest) }
it "should decode the message" do
expect(subject.user_id).to eq("123")
end
end
end
describe "#facebook_signed_request?" do
subject { controller.facebook_signed_request? }
context "without a signed request" do
it { is_expected.to eq(false) }
end
context "with a signed request" do
let(:controller) { TestController.new(signed_request: message) }
it { is_expected.to eq(true) }
end
end
end
| 27.767442 | 115 | 0.667923 |
613de514ffa63cef6d8bbb629292adfc7c037e9b | 24,142 | # frozen_string_literal: true
module API
class MergeRequests < ::API::Base
include PaginationParams
CONTEXT_COMMITS_POST_LIMIT = 20
before { authenticate_non_get! }
helpers Helpers::MergeRequestsHelpers
helpers Helpers::SSEHelpers
# These endpoints are defined in `TimeTrackingEndpoints` and is shared by
# API::Issues. In order to be able to define the feature category of these
# endpoints, we need to define them at the top-level by route.
feature_category :code_review, [
'/projects/:id/merge_requests/:merge_request_iid/time_estimate',
'/projects/:id/merge_requests/:merge_request_iid/reset_time_estimate',
'/projects/:id/merge_requests/:merge_request_iid/add_spent_time',
'/projects/:id/merge_requests/:merge_request_iid/reset_spent_time',
'/projects/:id/merge_requests/:merge_request_iid/time_stats'
]
# EE::API::MergeRequests would override the following helpers
helpers do
params :optional_params_ee do
end
params :optional_merge_requests_search_params do
end
end
def self.update_params_at_least_one_of
%i[
assignee_id
assignee_ids
reviewer_ids
description
labels
add_labels
remove_labels
milestone_id
remove_source_branch
allow_collaboration
allow_maintainer_to_push
squash
target_branch
title
state_event
discussion_locked
]
end
prepend_if_ee('EE::API::MergeRequests') # rubocop: disable Cop/InjectEnterpriseEditionModule
helpers do
# rubocop: disable CodeReuse/ActiveRecord
def find_merge_requests(args = {})
args = declared_params.merge(args)
args[:milestone_title] = args.delete(:milestone)
args[:not][:milestone_title] = args[:not]&.delete(:milestone)
args[:label_name] = args.delete(:labels)
args[:not][:label_name] = args[:not]&.delete(:labels)
args[:scope] = args[:scope].underscore if args[:scope]
merge_requests = MergeRequestsFinder.new(current_user, args).execute
.reorder(order_options_with_tie_breaker)
merge_requests = paginate(merge_requests)
.preload(:source_project, :target_project)
return merge_requests if args[:view] == 'simple'
merge_requests
.with_api_entity_associations
end
# rubocop: enable CodeReuse/ActiveRecord
def merge_request_pipelines_with_access
mr = find_merge_request_with_access(params[:merge_request_iid])
::Ci::PipelinesForMergeRequestFinder.new(mr, current_user).execute
end
def automatically_mergeable?(merge_when_pipeline_succeeds, merge_request)
pipeline_active = merge_request.head_pipeline_active? || merge_request.actual_head_pipeline_active?
merge_when_pipeline_succeeds && merge_request.mergeable_state?(skip_ci_check: true) && pipeline_active
end
def immediately_mergeable?(merge_when_pipeline_succeeds, merge_request)
if merge_when_pipeline_succeeds
merge_request.actual_head_pipeline_success?
else
merge_request.mergeable_state?
end
end
def serializer_options_for(merge_requests)
options = { with: Entities::MergeRequestBasic, current_user: current_user, with_labels_details: declared_params[:with_labels_details] }
if params[:view] == 'simple'
options[:with] = Entities::MergeRequestSimple
else
options[:skip_merge_status_recheck] = !declared_params[:with_merge_status_recheck]
end
options
end
def authorize_push_to_merge_request!(merge_request)
forbidden!('Source branch does not exist') unless
merge_request.source_branch_exists?
user_access = Gitlab::UserAccess.new(
current_user,
container: merge_request.source_project
)
forbidden!('Cannot push to source branch') unless
user_access.can_push_to_branch?(merge_request.source_branch)
end
params :merge_requests_params do
use :merge_requests_base_params
use :optional_merge_requests_search_params
use :pagination
end
end
resource :merge_requests do
desc 'List merge requests' do
success Entities::MergeRequestBasic
end
params do
use :merge_requests_params
use :optional_scope_param
end
get feature_category: :code_review do
authenticate! unless params[:scope] == 'all'
merge_requests = find_merge_requests
present merge_requests, serializer_options_for(merge_requests)
end
end
params do
requires :id, type: String, desc: 'The ID of a group'
end
resource :groups, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
desc 'Get a list of group merge requests' do
success Entities::MergeRequestBasic
end
params do
use :merge_requests_params
optional :non_archived, type: Boolean, desc: 'Return merge requests from non archived projects',
default: true
end
get ":id/merge_requests", feature_category: :code_review do
merge_requests = find_merge_requests(group_id: user_group.id, include_subgroups: true)
present merge_requests, serializer_options_for(merge_requests).merge(group: user_group)
end
end
params do
requires :id, type: String, desc: 'The ID of a project'
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
include TimeTrackingEndpoints
helpers do
params :optional_params do
optional :assignee_id, type: Integer, desc: 'The ID of a user to assign the merge request'
optional :assignee_ids, type: Array[Integer], coerce_with: ::API::Validations::Types::CommaSeparatedToIntegerArray.coerce, desc: 'Comma-separated list of assignee ids'
optional :reviewer_ids, type: Array[Integer], coerce_with: ::API::Validations::Types::CommaSeparatedToIntegerArray.coerce, desc: 'Comma-separated list of reviewer ids'
optional :description, type: String, desc: 'The description of the merge request'
optional :labels, type: Array[String], coerce_with: Validations::Types::CommaSeparatedToArray.coerce, desc: 'Comma-separated list of label names'
optional :add_labels, type: Array[String], coerce_with: Validations::Types::CommaSeparatedToArray.coerce, desc: 'Comma-separated list of label names'
optional :remove_labels, type: Array[String], coerce_with: Validations::Types::CommaSeparatedToArray.coerce, desc: 'Comma-separated list of label names'
optional :milestone_id, type: Integer, desc: 'The ID of a milestone to assign the merge request'
optional :remove_source_branch, type: Boolean, desc: 'Remove source branch when merging'
optional :allow_collaboration, type: Boolean, desc: 'Allow commits from members who can merge to the target branch'
optional :allow_maintainer_to_push, type: Boolean, as: :allow_collaboration, desc: '[deprecated] See allow_collaboration'
optional :squash, type: Grape::API::Boolean, desc: 'When true, the commits will be squashed into a single commit on merge'
use :optional_params_ee
end
end
desc 'List merge requests' do
success Entities::MergeRequestBasic
end
params do
use :merge_requests_params
optional :iids, type: Array[Integer], coerce_with: ::API::Validations::Types::CommaSeparatedToIntegerArray.coerce, desc: 'The IID array of merge requests'
end
get ":id/merge_requests", feature_category: :code_review do
authorize! :read_merge_request, user_project
merge_requests = find_merge_requests(project_id: user_project.id)
options = serializer_options_for(merge_requests).merge(project: user_project)
options[:project] = user_project
present merge_requests, options
end
desc 'Create a merge request' do
success Entities::MergeRequest
end
params do
requires :title, type: String, desc: 'The title of the merge request'
requires :source_branch, type: String, desc: 'The source branch'
requires :target_branch, type: String, desc: 'The target branch'
optional :target_project_id, type: Integer,
desc: 'The target project of the merge request defaults to the :id of the project'
use :optional_params
end
post ":id/merge_requests", feature_category: :code_review do
Gitlab::QueryLimiting.disable!('https://gitlab.com/gitlab-org/gitlab/-/issues/20770')
authorize! :create_merge_request_from, user_project
mr_params = declared_params(include_missing: false)
mr_params[:force_remove_source_branch] = mr_params.delete(:remove_source_branch)
mr_params = convert_parameters_from_legacy_format(mr_params)
merge_request = ::MergeRequests::CreateService.new(user_project, current_user, mr_params).execute
handle_merge_request_errors!(merge_request)
Gitlab::UsageDataCounters::EditorUniqueCounter.track_sse_edit_action(author: current_user) if request_from_sse?(user_project)
present merge_request, with: Entities::MergeRequest, current_user: current_user, project: user_project
end
desc 'Delete a merge request'
params do
requires :merge_request_iid, type: Integer, desc: 'The IID of a merge request'
end
delete ":id/merge_requests/:merge_request_iid", feature_category: :code_review do
merge_request = find_project_merge_request(params[:merge_request_iid])
authorize!(:destroy_merge_request, merge_request)
destroy_conditionally!(merge_request) do |merge_request|
Issuable::DestroyService.new(user_project, current_user).execute(merge_request)
end
end
params do
requires :merge_request_iid, type: Integer, desc: 'The IID of a merge request'
optional :render_html, type: Boolean, desc: 'Returns the description and title rendered HTML'
optional :include_diverged_commits_count, type: Boolean, desc: 'Returns the commits count behind the target branch'
optional :include_rebase_in_progress, type: Boolean, desc: 'Returns whether a rebase operation is ongoing '
end
desc 'Get a single merge request' do
success Entities::MergeRequest
end
get ':id/merge_requests/:merge_request_iid', feature_category: :code_review do
not_found!("Merge Request") unless can?(current_user, :read_merge_request, user_project)
merge_request = find_merge_request_with_access(params[:merge_request_iid])
present merge_request,
with: Entities::MergeRequest,
current_user: current_user,
project: user_project,
render_html: params[:render_html],
include_first_contribution: true,
include_diverged_commits_count: params[:include_diverged_commits_count],
include_rebase_in_progress: params[:include_rebase_in_progress]
end
desc 'Get the participants of a merge request' do
success Entities::UserBasic
end
get ':id/merge_requests/:merge_request_iid/participants', feature_category: :code_review do
not_found!("Merge Request") unless can?(current_user, :read_merge_request, user_project)
merge_request = find_merge_request_with_access(params[:merge_request_iid])
participants = ::Kaminari.paginate_array(merge_request.participants)
present paginate(participants), with: Entities::UserBasic
end
desc 'Get the commits of a merge request' do
success Entities::Commit
end
get ':id/merge_requests/:merge_request_iid/commits', feature_category: :code_review do
not_found!("Merge Request") unless can?(current_user, :read_merge_request, user_project)
merge_request = find_merge_request_with_access(params[:merge_request_iid])
commits =
paginate(merge_request.merge_request_diff.merge_request_diff_commits)
.map { |commit| Commit.from_hash(commit.to_hash, merge_request.project) }
present commits, with: Entities::Commit
end
desc 'Get the context commits of a merge request' do
success Entities::Commit
end
get ':id/merge_requests/:merge_request_iid/context_commits', feature_category: :code_review do
merge_request = find_merge_request_with_access(params[:merge_request_iid])
project = merge_request.project
not_found! unless project.context_commits_enabled?
context_commits =
paginate(merge_request.merge_request_context_commits).map(&:to_commit)
present context_commits, with: Entities::CommitWithLink, type: :full, request: merge_request
end
params do
requires :commits, type: Array[String], coerce_with: ::API::Validations::Types::CommaSeparatedToArray.coerce, allow_blank: false, desc: 'List of context commits sha'
end
desc 'create context commits of merge request' do
success Entities::Commit
end
post ':id/merge_requests/:merge_request_iid/context_commits', feature_category: :code_review do
commit_ids = params[:commits]
if commit_ids.size > CONTEXT_COMMITS_POST_LIMIT
render_api_error!("Context commits array size should not be more than #{CONTEXT_COMMITS_POST_LIMIT}", 400)
end
merge_request = find_merge_request_with_access(params[:merge_request_iid])
project = merge_request.project
not_found! unless project.context_commits_enabled?
authorize!(:update_merge_request, merge_request)
project = merge_request.target_project
result = ::MergeRequests::AddContextService.new(project, current_user, merge_request: merge_request, commits: commit_ids).execute
if result.instance_of?(Array)
present result, with: Entities::Commit
else
render_api_error!(result[:message], result[:http_status])
end
end
params do
requires :commits, type: Array[String], coerce_with: ::API::Validations::Types::CommaSeparatedToArray.coerce, allow_blank: false, desc: 'List of context commits sha'
end
desc 'remove context commits of merge request'
delete ':id/merge_requests/:merge_request_iid/context_commits', feature_category: :code_review do
commit_ids = params[:commits]
merge_request = find_merge_request_with_access(params[:merge_request_iid])
project = merge_request.project
not_found! unless project.context_commits_enabled?
authorize!(:destroy_merge_request, merge_request)
project = merge_request.target_project
commits = project.repository.commits_by(oids: commit_ids)
if commits.size != commit_ids.size
render_api_error!("One or more context commits' sha is not valid.", 400)
end
MergeRequestContextCommit.delete_bulk(merge_request, commits)
status 204
end
desc 'Show the merge request changes' do
success Entities::MergeRequestChanges
end
get ':id/merge_requests/:merge_request_iid/changes', feature_category: :code_review do
not_found!("Merge Request") unless can?(current_user, :read_merge_request, user_project)
merge_request = find_merge_request_with_access(params[:merge_request_iid])
present merge_request,
with: Entities::MergeRequestChanges,
current_user: current_user,
project: user_project,
access_raw_diffs: to_boolean(params.fetch(:access_raw_diffs, false))
end
desc 'Get the merge request pipelines' do
success Entities::Ci::PipelineBasic
end
get ':id/merge_requests/:merge_request_iid/pipelines', feature_category: :continuous_integration do
pipelines = merge_request_pipelines_with_access
not_found!("Merge Request") unless can?(current_user, :read_merge_request, user_project)
present paginate(pipelines), with: Entities::Ci::PipelineBasic
end
desc 'Create a pipeline for merge request' do
success ::API::Entities::Ci::Pipeline
end
post ':id/merge_requests/:merge_request_iid/pipelines', feature_category: :continuous_integration do
pipeline = ::MergeRequests::CreatePipelineService
.new(user_project, current_user, allow_duplicate: true)
.execute(find_merge_request_with_access(params[:merge_request_iid]))
if pipeline.nil?
not_allowed!
elsif pipeline.persisted?
status :ok
present pipeline, with: ::API::Entities::Ci::Pipeline
else
render_validation_error!(pipeline)
end
end
desc 'Update a merge request' do
success Entities::MergeRequest
end
params do
optional :title, type: String, allow_blank: false, desc: 'The title of the merge request'
optional :target_branch, type: String, allow_blank: false, desc: 'The target branch'
optional :state_event, type: String, values: %w[close reopen],
desc: 'Status of the merge request'
optional :discussion_locked, type: Boolean, desc: 'Whether the MR discussion is locked'
use :optional_params
at_least_one_of(*::API::MergeRequests.update_params_at_least_one_of)
end
put ':id/merge_requests/:merge_request_iid', feature_category: :code_review do
Gitlab::QueryLimiting.disable!('https://gitlab.com/gitlab-org/gitlab/-/issues/20772')
merge_request = find_merge_request_with_access(params.delete(:merge_request_iid), :update_merge_request)
mr_params = declared_params(include_missing: false)
mr_params[:force_remove_source_branch] = mr_params.delete(:remove_source_branch) if mr_params.has_key?(:remove_source_branch)
mr_params = convert_parameters_from_legacy_format(mr_params)
service = if mr_params.one? && (mr_params.keys & %i[assignee_id assignee_ids]).one?
::MergeRequests::UpdateAssigneesService
else
::MergeRequests::UpdateService
end
merge_request = service.new(user_project, current_user, mr_params).execute(merge_request)
handle_merge_request_errors!(merge_request)
present merge_request, with: Entities::MergeRequest, current_user: current_user, project: user_project
end
desc 'Merge a merge request' do
success Entities::MergeRequest
end
params do
optional :merge_commit_message, type: String, desc: 'Custom merge commit message'
optional :squash_commit_message, type: String, desc: 'Custom squash commit message'
optional :should_remove_source_branch, type: Boolean,
desc: 'When true, the source branch will be deleted if possible'
optional :merge_when_pipeline_succeeds, type: Boolean,
desc: 'When true, this merge request will be merged when the pipeline succeeds'
optional :sha, type: String, desc: 'When present, must have the HEAD SHA of the source branch'
optional :squash, type: Grape::API::Boolean, desc: 'When true, the commits will be squashed into a single commit on merge'
end
put ':id/merge_requests/:merge_request_iid/merge', feature_category: :code_review do
Gitlab::QueryLimiting.disable!('https://gitlab.com/gitlab-org/gitlab/-/issues/4796')
merge_request = find_project_merge_request(params[:merge_request_iid])
# Merge request can not be merged
# because user dont have permissions to push into target branch
unauthorized! unless merge_request.can_be_merged_by?(current_user)
merge_when_pipeline_succeeds = to_boolean(params[:merge_when_pipeline_succeeds])
automatically_mergeable = automatically_mergeable?(merge_when_pipeline_succeeds, merge_request)
immediately_mergeable = immediately_mergeable?(merge_when_pipeline_succeeds, merge_request)
not_allowed! if !immediately_mergeable && !automatically_mergeable
render_api_error!('Branch cannot be merged', 406) unless merge_request.mergeable?(skip_ci_check: automatically_mergeable)
check_sha_param!(params, merge_request)
merge_request.update(squash: params[:squash]) if params[:squash]
merge_params = HashWithIndifferentAccess.new(
commit_message: params[:merge_commit_message],
squash_commit_message: params[:squash_commit_message],
should_remove_source_branch: params[:should_remove_source_branch],
sha: params[:sha] || merge_request.diff_head_sha
).compact
if immediately_mergeable
::MergeRequests::MergeService
.new(merge_request.target_project, current_user, merge_params)
.execute(merge_request)
elsif automatically_mergeable
AutoMergeService.new(merge_request.target_project, current_user, merge_params)
.execute(merge_request, AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS)
end
present merge_request, with: Entities::MergeRequest, current_user: current_user, project: user_project
end
desc 'Returns the up to date merge-ref HEAD commit'
get ':id/merge_requests/:merge_request_iid/merge_ref', feature_category: :code_review do
merge_request = find_project_merge_request(params[:merge_request_iid])
result = ::MergeRequests::MergeabilityCheckService.new(merge_request).execute(recheck: true)
if result.success?
present :commit_id, result.payload.dig(:merge_ref_head, :commit_id)
else
render_api_error!(result.message, 400)
end
end
desc 'Cancel merge if "Merge When Pipeline Succeeds" is enabled' do
success Entities::MergeRequest
end
post ':id/merge_requests/:merge_request_iid/cancel_merge_when_pipeline_succeeds', feature_category: :code_review do
merge_request = find_project_merge_request(params[:merge_request_iid])
unauthorized! unless merge_request.can_cancel_auto_merge?(current_user)
AutoMergeService.new(merge_request.target_project, current_user).cancel(merge_request)
end
desc 'Rebase the merge request against its target branch' do
detail 'This feature was added in GitLab 11.6'
end
params do
optional :skip_ci, type: Boolean, desc: 'Do not create CI pipeline'
end
put ':id/merge_requests/:merge_request_iid/rebase', feature_category: :code_review do
merge_request = find_project_merge_request(params[:merge_request_iid])
authorize_push_to_merge_request!(merge_request)
merge_request.rebase_async(current_user.id, skip_ci: params[:skip_ci])
status :accepted
present rebase_in_progress: merge_request.rebase_in_progress?
rescue ::MergeRequest::RebaseLockTimeout => e
render_api_error!(e.message, 409)
end
desc 'List issues that will be closed on merge' do
success Entities::MRNote
end
params do
use :pagination
end
get ':id/merge_requests/:merge_request_iid/closes_issues', feature_category: :code_review do
merge_request = find_merge_request_with_access(params[:merge_request_iid])
issues = ::Kaminari.paginate_array(merge_request.visible_closing_issues_for(current_user))
issues = paginate(issues)
external_issues, internal_issues = issues.partition { |issue| issue.is_a?(ExternalIssue) }
data = Entities::IssueBasic.represent(internal_issues, current_user: current_user)
data += Entities::ExternalIssue.represent(external_issues, current_user: current_user)
data.as_json
end
end
end
end
| 42.65371 | 177 | 0.703049 |
bb4c042ad77a5ef18df537cdd7715f329fb86514 | 7,985 | # frozen_string_literal: true
module Id3Taginator
class Id3v2Tag
include Frames::UfidFrames
include Frames::TextFrames
include Frames::UrlFrames
include Frames::IplFrames
include Frames::McdiFrames
include Frames::LyricsFrames
include Frames::CommentFrames
include Frames::PictureFrames
include Frames::GeoFrames
include Frames::CountFrames
include Frames::BufferFrames
include Frames::ToSFrames
include Frames::EncryptionFrames
include Frames::GroupingFrames
include Frames::PrivateFrames
include Frames::CustomFrames
IDENTIFIER = 'ID3'
attr_writer :options
# checks if the given stream contains a id3v2 tag
#
# @param file [StringIO, IO, File] the file stream to check
#
# @return [Boolean] true if contains an id3v2 tag, else false
def self.id3v2_tag?(file)
tag = file.read(3)
file.seek(0)
tag == IDENTIFIER
end
# builds an id3tag from the given file stream and the passed options
#
# @param file [StringIO, IO, File] the file stream
# @param options [Options::Options] options that should be used
#
# @return [Id3v2Tag] the id3v2tag object,the specific object is determined by the tag version
def self.build_from_file(file, options)
file.seek(0)
tag = file.read(3)
raise Errors::Id3TagError, "#{tag} is no valid ID3v2 tag. Tag seems corrupted." unless tag == IDENTIFIER
major_version = file.readbyte
minor_version = file.readbyte
flags = Header::Id3v2Flags.new(file.readbyte)
tag_size = Util::MathUtil.to_32_synchsafe_integer(file.read(4)&.bytes)
tag_data = file.read(tag_size)
raise Errors::Id3TagError, 'There is no Tag data to read. ID3v2 tag seems to be invalid.' if tag_data.nil?
tag_data = Util::SyncUtil.undo_synchronization(StringIO.new(tag_data)) if flags.unsynchronized?
id3v2_tag = id3v2_tag_for_version(major_version)
id3v2_tag.new(minor_version, flags, tag_size, StringIO.new(tag_data), options)
end
# builds an empty id3tag for the given version
#
# @param version [Integer] the id3tag major version 2,3 or 4
# @param options [Options::Options] the options to use
#
# @return [Id3v22Tag, Id3v23Tag, Id3v24Tag] the Id3v2 tag object for the requested version
def self.build_for_version(version, options)
case version
when 2
Id3v22Tag.build_empty(options)
when 3
Id3v23Tag.build_empty(options)
when 4
Id3v24Tag.build_empty(options)
else
raise Errors::Id3TagError, "Id3v2.#{version} is not supported."
end
end
# Constructor
#
# @param header_size [Integer] number of bytes for the Header, usually 6 for v2 and 10 for v3 and v4
# @param major_version [Integer] the major version, in v2.[major].[minor]
# @param minor_version [Integer] the minor version, in v2.[major].[minor]
# @param flags [Header::Id3v2Flags] the 2 Byte header flags wrapped in the entity
# @param tag_size [Integer] number of bytes the excluding header/footer of the tag
# @param frames [Array<Frames::Id3TagFrame>] array of frames of the id3tag
# @param extended_header [Header::Id3v23ExtendedHeader, Header::Id3v24ExtendedHeader, nil] the extended header of
# present or nil otherwise
def initialize(header_size, major_version, minor_version, flags, tag_size, frames, extended_header)
@header_size = header_size
@major_version = major_version
@minor_version = minor_version
@flags = flags
@tag_size = tag_size
@extended_header = extended_header
@frames = frames
end
# gets the version of this id3tag entity
#
# @return [String] returns the version in the form 2.x.y
def version
"2.#{@major_version}.#{@minor_version}"
end
# returns the number of bytes of the total tag, including header and footer
#
# @return [Integer] the total tag size in bytes
def total_tag_size
@header_size + @tag_size + (@flags&.footer? ? 10 : 0)
end
# selects all frames with the given frame id
#
# @return [Array<Frames::Id3v2Frame>] an array of Id3v2Frames such as CustomFrame, AlbumFrame etc.
def frames(frame_id)
@frames.select { |f| f.frame_id == frame_id }
end
# adds a new frame. There will be no validity checks, even invalid frames can be added, essentially rendering
# the Id3 tag broken
#
# @param frame [Frames::Id3v2Frame] the frame to add
def add_frame(frame)
raise Errors::Id3TagError, 'The given frame is no Id3v2Frame.' unless frame.is_a?(Frames::Id3v2Frame)
@frames << frame
end
# returns the number of frames for this tag
#
# @return [Integer] number of frames
def number_of_frames
@frames.length
end
# determined if the tag is unsynchronized
#
# @return [Boolean] true if unsynchronized, else false
def unsynchronized?
@flags.unsynchronized?
end
# sets the tag synchronized or unsynchronized. Should be false, only required for very old player
#
# @param enabled [Boolean] sets unsynchronized enabled or disabled
def unsynchronized=(enabled = true)
@flags.unsynchronized = enabled
end
# adds the size tag if not present. If v2.4, the option ignore_v24_frame_error must be true
#
# @param audio_size [Integer] the audio size bytes
def add_size_tag_if_not_present(audio_size)
return nil unless @options.add_size_frame
return nil if @major_version == 4 && [email protected]_v24_frame_error
size_frame = size
return nil unless size_frame.nil?
self.size = audio_size
end
# dumps the tag to a byte string. This dump already takes unsynchronization, padding and all other options
# into effect
#
# @return [String] tag dump as a String. tag.bytes represents the byte array
def to_bytes
# add up frame size and unsyc if necessary
frames_payload = ''
@frames.each do |frame|
frames_payload += frame.to_bytes
end
frames_payload += "\x00" * @options.padding_bytes if @options.padding_bytes.positive?
frames_payload = Util::SyncUtil.add_synchronization(frames_payload) if unsynchronized?
frame_size = frames_payload.size
res = 'ID3'
res += @major_version.chr
res += @minor_version.chr
res += @flags.to_bytes
res += Util::MathUtil.from_32_synchsafe_integer(frame_size)
res += frames_payload
if @flags&.footer?
res = '3DI'
res += @major_version.chr
res += @minor_version.chr
res += @flags.to_bytes
res += Util::MathUtil.from_32_synchsafe_integer(frame_size)
end
res
end
# creates an id3v2 tag for the specific version
#
# @param major_version [Integer] the major version, 2,3 or 4
#
# @return [Class<Id3v22Tag>, Class<Id3v23Tag>, Class<Id3v24Tag>] the correct id3v2 tag object
def self.id3v2_tag_for_version(major_version)
case major_version
when 2
Id3v22Tag
when 3
Id3v23Tag
when 4
Id3v24Tag
else
raise Errors::Id3TagError, "Unsupported version: 2.#{major_version}"
end
end
# parses the frames for the given id3v2 tag version
#
# @param file [StringIO, IO, File] the file or StringIO stream the bytes can be fetched from
# @param version [Integer]
#
# @return [Array<Frames::Id3v2Frame>] list of all parsed frames
def parse_frames(file, version = 3)
generator = Frames::Id3v2FrameFactory.new(file, version, @options)
result = []
frame = generator.next_frame
until frame.nil?
result << frame
frame = generator.next_frame
end
result
end
private_class_method :id3v2_tag_for_version
end
end
| 32.995868 | 117 | 0.670006 |
2808170f7164a861a152db3656f0589e0fde6e86 | 779 | require 'java'
import org.foa.ThreadKilledException
require 'thread'
class JRunnable
include Java::java.lang.Runnable
def initialize(proc)
@proc = proc
end
def run
begin
@proc.call
rescue java.lang.InterruptedException => e
# do nothing
rescue ThreadKilledException => e
# do nothing.
rescue Exception => e
puts "Exception in runnable:"
puts e.to_s
puts e.backtrace.join("\n")
end
end
end
class ControllableThread < org.foa.ControllableThread
def initialize(name="empty", &block)
runnable = JRunnable.new(block)
super(name, runnable)
end
end
# Don't use the kernel sleep. Redispatch to ControllableThread instead.
module Kernel
def sleep(sec)
ControllableThread.sleepSec(sec)
end
end
| 19.974359 | 72 | 0.693196 |
abb437a23f5ff92fc5855fa5e1f8368791ec8b2c | 4,378 | require 'cases/sqlserver_helper'
require 'models/job'
require 'models/person'
require 'models/reference'
require 'models/book'
require 'models/author'
require 'models/subscription'
require 'models/post'
require 'models/comment'
require 'models/categorization'
require 'models_sqlserver/sql_server_order_row_number'
class OffsetAndLimitTestSqlserver < ActiveRecord::TestCase
fixtures :jobs, :people, :references, :subscriptions,
:authors, :posts, :comments, :categorizations
setup :create_10_books
teardown :destroy_all_books
context 'When selecting with limit' do
should 'alter sql to limit number of records returned' do
assert_sql(/SELECT TOP \(10\)/) { Book.limit(10).load }
end
end
context 'When selecting with offset' do
should 'have limit (top) of 9223372036854775807 if only offset is passed' do
assert_sql(/SELECT TOP \(9223372036854775807\) \[__rnt\]\.\* FROM.*WHERE \[__rnt\]\.\[__rn\] > \(1\)/) { Book.offset(1).load }
end
should 'support calling exists?' do
assert Book.offset(3).exists?
end
end
context 'When selecting with limit and offset' do
should 'work with fully qualified table and columns in select' do
books = Book.select('books.id, books.name').limit(3).offset(5)
assert_equal Book.all[5,3].map(&:id), books.map(&:id)
end
should 'alter SQL to limit number of records returned offset by specified amount' do
sql = %|EXEC sp_executesql N'SELECT TOP (3) [__rnt].* FROM ( SELECT ROW_NUMBER() OVER (ORDER BY [books].[id] ASC) AS [__rn], [books].* FROM [books] ) AS [__rnt] WHERE [__rnt].[__rn] > (5) ORDER BY [__rnt].[__rn] ASC'|
assert_sql(sql) { Book.limit(3).offset(5).load }
end
should 'add locks to deepest sub select' do
pattern = /FROM \[books\]\s+WITH \(NOLOCK\)/
assert_sql(pattern) { Book.limit(3).lock('WITH (NOLOCK)').offset(5).count }
assert_sql(pattern) { Book.limit(3).lock('WITH (NOLOCK)').offset(5).load }
end
should 'have valid sort order' do
order_row_numbers = SqlServerOrderRowNumber.offset(7).order("c DESC").select("c, ROW_NUMBER() OVER (ORDER BY c ASC) AS [dummy]").map(&:c)
assert_equal [2, 1, 0], order_row_numbers
end
should 'work with through associations' do
assert_equal people(:david), jobs(:unicyclist).people.limit(1).offset(1).first
end
should 'work with through uniq associations' do
david = authors(:david)
mary = authors(:mary)
thinking = posts(:thinking)
# Mary has duplicate categorizations to the thinking post.
assert_equal [thinking, thinking], mary.categorized_posts.load
assert_equal [thinking], mary.unique_categorized_posts.limit(2).offset(0).load
# Paging thru David's uniq ordered comments, with count too.
assert_equal [1, 2, 3, 5, 6, 7, 8, 9, 10, 12], david.ordered_uniq_comments.map(&:id)
assert_equal [3, 5], david.ordered_uniq_comments.limit(2).offset(2).map(&:id)
assert_equal 2, david.ordered_uniq_comments.limit(2).offset(2).count
assert_equal [8, 9, 10, 12], david.ordered_uniq_comments.limit(5).offset(6).map(&:id)
assert_equal 4, david.ordered_uniq_comments.limit(5).offset(6).count
end
should 'remove [__rnt] table names from relation reflection and hence do not eager loading' do
create_10_books
create_10_books
assert_queries(1) { Book.includes(:subscriptions).limit(10).offset(10).references(:subscriptions).load }
end
context 'with count' do
should 'pass a gauntlet of window tests' do
Book.first.destroy
Book.first.destroy
Book.first.destroy
assert_equal 7, Book.count
assert_equal 1, Book.limit(1).offset(1).size
assert_equal 1, Book.limit(1).offset(5).size
assert_equal 1, Book.limit(1).offset(6).size
assert_equal 0, Book.limit(1).offset(7).size
assert_equal 3, Book.limit(3).offset(4).size
assert_equal 2, Book.limit(3).offset(5).size
assert_equal 1, Book.limit(3).offset(6).size
assert_equal 0, Book.limit(3).offset(7).size
assert_equal 0, Book.limit(3).offset(8).size
end
end
end
protected
def create_10_books
Book.delete_all
@books = (1..10).map {|i| Book.create!}
end
def destroy_all_books
@books.each { |b| b.destroy }
end
end
| 34.203125 | 223 | 0.677478 |
f73fc5f55dab27f27b9d74d75b3d0f3ddb7d3534 | 691 | require "language/node"
class Twiliorc < Formula
desc "unleash the power of Twilio from your command prompt"
homepage "https://github.com/twilio/twilio-cli"
url "https://twilio-cli-prod.s3.amazonaws.com/channels/rc/twilio-v2.36.0-rc.2/twilio-v2.36.0-rc.2.tar.gz"
version "2.36.0-rc.2"
sha256 "bb8252cca1cce30051da332fc46141938c6339b14d9e1d3164669a68854e72d3"
depends_on "node"
def install
inreplace "bin/twilio", /^CLIENT_HOME=/, "export TWILIO_OCLIF_CLIENT_HOME=#{lib/"client"}\nCLIENT_HOME="
libexec.install Dir["*"]
bin.install_symlink libexec/"bin/twilio"
end
def post_install
pid = spawn("node #{libexec}/welcome.js")
Process.wait pid
end
end
| 31.409091 | 108 | 0.733719 |
e2fc51825e31e7f3a5cb3aa130a019e43cb7aa33 | 757 | class AddSharedToRiskAssessments < ActiveRecord::Migration[5.2]
def change
change_table :risk_assessments do |t|
t.boolean :shared, index: true, null: false, default: false
t.references :group, index: true, foreign_key: FOREIGN_KEY_OPTIONS.dup
end
put_group_id_on_risk_assessments
change_column_null :risk_assessments, :group_id, false
end
private
def put_group_id_on_risk_assessments
RiskAssessment.reset_column_information
risk_assessments.find_each do |risk_assessment|
group_id = risk_assessment.organization.group_id
risk_assessment.update_column :group_id, group_id
end
end
def risk_assessments
RiskAssessment.unscoped.all.includes :organization
end
end
| 26.103448 | 76 | 0.747688 |
0391cd5b2fddccfb788d5ef249906fcdaf2b9486 | 412 | # frozen_string_literal: true
module Sanitizable
extend ActiveSupport::Concern
included do
before_validation :sanitize_web
end
protected
def sanitize_web
if self.attributes.key?('web_url')
unless self.web_url.blank? || self.web_url.start_with?('http://') || self.web_url.start_with?('https://')
self.web_url = "http://#{self.web_url}"
end
end
end
end
| 21.684211 | 113 | 0.657767 |
08f128f23fa7e550f7d5e9cab5b210fe28d00886 | 3,466 | #
# = uri/ftp.rb
#
# Author:: Akira Yamada <[email protected]>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
# Revision:: $Id: ftp.rb,v 1.3.2.1 2004/03/24 12:20:32 gsinclair Exp $
#
require 'uri/generic'
module URI
#
# RFC1738 section 3.2.
#
class FTP < Generic
DEFAULT_PORT = 21
COMPONENT = [
:scheme,
:userinfo, :host, :port,
:path, :typecode
].freeze
#
# Typecode is, "a", "i" or "d".
# As for "a" the text, as for "i" binary,
# as for "d" the directory is displayed.
# "A" with the text, as for "i" being binary,
# is because the respective data type was called ASCII and
# IMAGE with the protocol of FTP.
#
TYPECODE = ['a', 'i', 'd'].freeze
TYPECODE_PREFIX = ';type='.freeze
def self.new2(user, password, host, port, path,
typecode = nil, arg_check = true)
typecode = nil if typecode.size == 0
if typecode && !TYPECODE.include?(typecode)
raise ArgumentError,
"bad typecode is specified: #{typecode}"
end
# do escape
self.new('ftp',
[user, password],
host, port, nil,
typecode ? path + TYPECODE_PREFIX + typecode : path,
nil, nil, nil, arg_check)
end
#
# == Description
#
# Creates a new URI::FTP object from components of URI::FTP with
# check. It is scheme, userinfo, host, port, path and typecode. It
# provided by an Array or a Hash. typecode is "a", "i" or "d".
#
def self.build(args)
tmp = Util::make_components_hash(self, args)
if tmp[:typecode]
if tmp[:typecode].size == 1
tmp[:typecode] = TYPECODE_PREFIX + tmp[:typecode]
end
tmp[:path] << tmp[:typecode]
end
return super(tmp)
end
#
# == Description
#
# Create a new URI::FTP object from ``generic'' components with no
# check.
#
# == Usage
#
# require 'uri'
# p ftp = URI.parse("ftp://ftp.ruby-lang.org/pub/ruby/;type=d")
# # => #<URI::FTP:0x201fad08 URL:ftp://ftp.ruby-lang.org/pub/ruby/;type=d>
# p ftp.typecode
# # => "d"
#
def initialize(*arg)
super(*arg)
@typecode = nil
tmp = @path.index(TYPECODE_PREFIX)
if tmp
typecode = @path[tmp + TYPECODE_PREFIX.size..-1]
self.set_path(@path[0..tmp - 1])
if arg[-1]
self.typecode = typecode
else
self.set_typecode(typecode)
end
end
end
attr_reader :typecode
def check_typecode(v)
if TYPECODE.include?(v)
return true
else
raise InvalidComponentError,
"bad typecode(expected #{TYPECODE.join(', ')}): #{v}"
end
end
private :check_typecode
def set_typecode(v)
@typecode = v
end
protected :set_typecode
def typecode=(typecode)
check_typecode(typecode)
set_typecode(typecode)
typecode
end
def merge(oth) # :nodoc:
tmp = super(oth)
if self != tmp
tmp.set_typecode(oth.typecode)
end
return tmp
end
def to_s
save_path = nil
if @typecode
save_path = @path
@path = @path + TYPECODE_PREFIX + @typecode
end
str = super
if @typecode
@path = save_path
end
return str
end
end
@@schemes['FTP'] = FTP
end
| 23.261745 | 81 | 0.553664 |
1ac69ffa5cf8002ac9e64486e54511896f53a77a | 61 | module DreamSeeDoApi
class GoogleDocument < Base
end
end
| 12.2 | 29 | 0.786885 |
e8d4d8efa8d08c5a7d54c847ddbdf54eaa60926a | 2,449 | # frozen_string_literal: true
require "test_helper"
# Test to make sure admins can manage team members.
class Admin::TeamMembersControllerTest < ActionDispatch::IntegrationTest
setup do
@admin = users(:admin)
@admin_team_member = admin_team_members(:one)
end
def admin_team_member_params
{
bio: @admin_team_member.bio,
designations: @admin_team_member.designations,
name: @admin_team_member.name,
photo: @admin_team_member.photo,
position: @admin_team_member.position,
role: @admin_team_member.role
}
end
test "should get order as admin" do
login(@admin)
get order_admin_team_members_url
assert_response :success
end
test "should update order as admin" do
login(@admin)
post order_admin_team_members_url, params: {
team_member_ids: [admin_team_members(:two).id, admin_team_members(:one).id]
}
admin_team_members(:one).reload
admin_team_members(:two).reload
assert_equal 0, admin_team_members(:two).position
assert_equal 1, admin_team_members(:one).position
assert_response :success
end
test "should get index" do
login(@admin)
get admin_team_members_url
assert_response :success
end
test "should get new" do
login(@admin)
get new_admin_team_member_url
assert_response :success
end
test "should create admin_team_member" do
login(@admin)
assert_difference("Admin::TeamMember.count") do
post admin_team_members_url, params: {
admin_team_member: admin_team_member_params
}
end
assert_redirected_to admin_team_member_url(Admin::TeamMember.last)
end
test "should show admin_team_member" do
login(@admin)
get admin_team_member_url(@admin_team_member)
assert_redirected_to admin_team_members_url
end
test "should get edit" do
login(@admin)
get edit_admin_team_member_url(@admin_team_member)
assert_response :success
end
test "should update admin_team_member" do
login(@admin)
patch admin_team_member_url(@admin_team_member), params: {
admin_team_member: admin_team_member_params
}
assert_redirected_to admin_team_member_url(@admin_team_member)
end
test "should destroy admin_team_member" do
login(@admin)
assert_difference("Admin::TeamMember.current.count", -1) do
delete admin_team_member_url(@admin_team_member)
end
assert_redirected_to admin_team_members_url
end
end
| 26.912088 | 81 | 0.737444 |
117d7d5d0f46350f9fc51898bd5144aa6e5373c2 | 3,535 | require 'spec_helper'
require 'rack/test'
module Bosh::Director
module Api
describe Controllers::StemcellsController do
include Rack::Test::Methods
let!(:temp_dir) { Dir.mktmpdir}
before do
blobstore_dir = File.join(temp_dir, 'blobstore')
FileUtils.mkdir_p(blobstore_dir)
test_config = Psych.load(spec_asset('test-director-config.yml'))
test_config['dir'] = temp_dir
test_config['blobstore'] = {
'provider' => 'local',
'options' => {'blobstore_path' => blobstore_dir}
}
test_config['snapshots']['enabled'] = true
Config.configure(test_config)
@director_app = App.new(Config.load_hash(test_config))
end
after do
FileUtils.rm_rf(temp_dir)
end
def app
@rack_app ||= Controller.new
end
def login_as_admin
basic_authorize 'admin', 'admin'
end
def login_as(username, password)
basic_authorize username, password
end
it 'requires auth' do
get '/'
last_response.status.should == 401
end
it 'sets the date header' do
get '/'
last_response.headers['Date'].should_not be_nil
end
it 'allows Basic HTTP Auth with admin/admin credentials for ' +
"test purposes (even though user doesn't exist)" do
basic_authorize 'admin', 'admin'
get '/'
last_response.status.should == 404
end
describe 'API calls' do
before(:each) { login_as_admin }
describe 'creating a stemcell' do
it 'expects compressed stemcell file' do
post '/stemcells', spec_asset('tarball.tgz'), { 'CONTENT_TYPE' => 'application/x-compressed' }
expect_redirect_to_queued_task(last_response)
end
it 'expects remote stemcell location' do
post '/stemcells', Yajl::Encoder.encode('location' => 'http://stemcell_url'), { 'CONTENT_TYPE' => 'application/json' }
expect_redirect_to_queued_task(last_response)
end
it 'only consumes application/x-compressed and application/json' do
post '/stemcells', spec_asset('tarball.tgz'), { 'CONTENT_TYPE' => 'application/octet-stream' }
last_response.status.should == 404
end
end
describe 'listing stemcells' do
it 'has API call that returns a list of stemcells in JSON' do
stemcells = (1..10).map do |i|
Models::Stemcell.
create(:name => "stemcell-#{i}", :version => i,
:cid => rand(25000 * i))
end
get '/stemcells', {}, {}
last_response.status.should == 200
body = Yajl::Parser.parse(last_response.body)
body.kind_of?(Array).should be_true
body.size.should == 10
response_collection = body.map do |e|
[e['name'], e['version'], e['cid']]
end
expected_collection = stemcells.sort_by { |e| e.name }.map do |e|
[e.name.to_s, e.version.to_s, e.cid.to_s]
end
response_collection.should == expected_collection
end
it 'returns empty collection if there are no stemcells' do
get '/stemcells', {}, {}
last_response.status.should == 200
body = Yajl::Parser.parse(last_response.body)
body.should == []
end
end
end
end
end
end
| 29.957627 | 130 | 0.571994 |
bbcb390fbee2fe3cc9616d5d1ca4ef74237180d3 | 442 | class Chef::Recipe
##
# Allow a recipe to find its cookbook's version
##
def cookbook_version
run_context.cookbook_collection[cookbook_name].version
end
end
##
# Version and Download URI helpers
##
module Tokend
module Helpers
class << self
def github_download(owner, repo, version)
"https://github.com/#{owner}/#{repo}/releases/download/v#{version}/tokend_#{version}_amd64.deb"
end
end
end
end
| 20.090909 | 103 | 0.690045 |
792030967319080a3bd212359fbdfd86c4798241 | 156 | # Enables Addressable::URI support in Hurley
require "addressable/uri"
module Hurley
class Url
@@parser = Addressable::URI.method(:parse)
end
end
| 15.6 | 46 | 0.730769 |
615a9af72b262d4e3c9f344da90fc857fb8b3da0 | 1,526 | RSpec.shared_examples "a Gather Content Element" do |type|
it "has the correct type" do
expect(subject[:type]).to eq(type)
end
context "a valid section instance" do
it "has a name" do
expect(subject[:name]).to eq(name)
end
it "has a required flag" do
expect(subject[:required]).to eq(required)
end
it "has a label" do
expect(subject[:label]).to eq(label)
end
it "has microcopy" do
expect(subject[:microcopy]).to eq(microcopy)
end
end
context "with an empty name" do
let(:name) { "" }
it "raises a ArgumentError" do
expect {
subject
}.to raise_error(ArgumentError)
end
end
context "with an empty label" do
let(:label) { "" }
it "raises a ArgumentError" do
expect {
subject
}.to raise_error(ArgumentError)
end
end
context "required" do
context "is true" do
let(:required) { true }
it "compiles to true" do
expect(subject[:required]).to eq(true)
end
end
context "is false" do
let(:required) { false }
it "compiles to false" do
expect(subject[:required]).to eq(false)
end
end
context "is truthy" do
let(:required) { "I'm a string!" }
it "compiles to true" do
expect(subject[:required]).to eq(true)
end
end
context "is falsey" do
let(:required) { nil }
it "compiles to false" do
expect(subject[:required]).to eq(false)
end
end
end
end
| 19.564103 | 58 | 0.58519 |
28459214810fd434883cd281896965dfe74b0843 | 229 | # 列車種別の情報(他社)を扱うクラス
class TokyoMetro::Static::TrainType::Custom::OtherOperator < TokyoMetro::Static::Fundamental::TopLevel::UsingMultipleYamls
include ::TokyoMetro::ClassNameLibrary::Static::TrainType::Custom::OtherOperator
end | 57.25 | 122 | 0.816594 |
39847b1e2e09564dcf54ab853b491139a93a3b27 | 13,863 | # Generated from https://dartlang.org/sitemap.xml on July 6, 2016
$OLD_SITE_URLS = [
"https://www.dartlang.org/",
"https://www.dartlang.org/articles/",
"https://www.dartlang.org/articles/await-async/",
"https://www.dartlang.org/articles/benchmarking/",
"https://www.dartlang.org/articles/beyond-async/",
"https://www.dartlang.org/articles/broadcast-streams/",
"https://www.dartlang.org/articles/converters-and-codecs/",
"https://www.dartlang.org/articles/creating-streams/",
"https://www.dartlang.org/articles/embedding-in-html/",
"https://www.dartlang.org/articles/emulating-functions/",
"https://www.dartlang.org/articles/event-loop/",
"https://www.dartlang.org/articles/futures-and-error-handling/",
"https://www.dartlang.org/articles/improving-the-dom/",
"https://www.dartlang.org/articles/io/",
"https://www.dartlang.org/articles/js-dart-interop/",
"https://www.dartlang.org/articles/json-web-service/",
"https://www.dartlang.org/articles/mixins/",
"https://www.dartlang.org/articles/native-extensions-for-standalone-dart-vm/",
"https://www.dartlang.org/articles/numeric-computation/",
"https://www.dartlang.org/articles/optional-types/",
"https://www.dartlang.org/articles/reflection-with-mirrors/",
"https://www.dartlang.org/articles/serialization/",
"https://www.dartlang.org/articles/simd/",
"https://www.dartlang.org/articles/snapshots/",
"https://www.dartlang.org/articles/why-dart-types/",
"https://www.dartlang.org/articles/why-not-bytecode/",
"https://www.dartlang.org/articles/zones/",
"https://www.dartlang.org/authors/bob-nystrom.html",
"https://www.dartlang.org/authors/chris-buckett.html",
"https://www.dartlang.org/authors/david-chandler.html",
"https://www.dartlang.org/authors/eli-brandt.html",
"https://www.dartlang.org/authors/florian-loitsch.html",
"https://www.dartlang.org/authors/gilad-bracha.html",
"https://www.dartlang.org/authors/graham-wheeler.html",
"https://www.dartlang.org/authors/index.html",
"https://www.dartlang.org/authors/john-mccutchan.html",
"https://www.dartlang.org/authors/kathy-walrath.html",
"https://www.dartlang.org/authors/lasse-nielsen.html",
"https://www.dartlang.org/authors/mads-ager.html",
"https://www.dartlang.org/authors/mary-campione.html",
"https://www.dartlang.org/authors/nicolas-garnier.html",
"https://www.dartlang.org/authors/seth-ladd.html",
"https://www.dartlang.org/authors/shailen-tuli.html",
"https://www.dartlang.org/authors/sigmund-cherem.html",
"https://www.dartlang.org/authors/siva-annamalai.html",
"https://www.dartlang.org/authors/vijay-menon.html",
"https://www.dartlang.org/authors/william-hesse.html",
"https://www.dartlang.org/books/",
"https://www.dartlang.org/codelabs/",
"https://www.dartlang.org/codelabs/darrrt/",
"https://www.dartlang.org/codelabs/darrrt/examples/index.html",
"https://www.dartlang.org/community/who-uses-dart.html",
"https://www.dartlang.org/dart-by-example/",
"https://www.dartlang.org/dart-tips/",
"https://www.dartlang.org/dart-tips/dart-tips-ep-1.html",
"https://www.dartlang.org/dart-tips/dart-tips-ep-10.html",
"https://www.dartlang.org/dart-tips/dart-tips-ep-11.html",
"https://www.dartlang.org/dart-tips/dart-tips-ep-2.html",
"https://www.dartlang.org/dart-tips/dart-tips-ep-3.html",
"https://www.dartlang.org/dart-tips/dart-tips-ep-4.html",
"https://www.dartlang.org/dart-tips/dart-tips-ep-5.html",
"https://www.dartlang.org/dart-tips/dart-tips-ep-6.html",
"https://www.dartlang.org/dart-tips/dart-tips-ep-7.html",
"https://www.dartlang.org/dart-tips/dart-tips-ep-8.html",
"https://www.dartlang.org/dart-tips/dart-tips-ep-9.html",
"https://www.dartlang.org/devices/",
"https://www.dartlang.org/docs/",
"https://www.dartlang.org/docs/dart-up-and-running/",
"https://www.dartlang.org/docs/dart-up-and-running/ch01.html",
"https://www.dartlang.org/docs/dart-up-and-running/ch02.html",
"https://www.dartlang.org/docs/dart-up-and-running/ch03.html",
"https://www.dartlang.org/docs/dart-up-and-running/ch04.html",
"https://www.dartlang.org/docs/dart-up-and-running/foreword.html",
"https://www.dartlang.org/docs/dart-up-and-running/preface.html",
"https://www.dartlang.org/docs/spec/",
"https://www.dartlang.org/docs/spec/examples/lazyloader/index.html",
"https://www.dartlang.org/docs/synonyms/",
"https://www.dartlang.org/docs/tutorials/",
"https://www.dartlang.org/docs/tutorials/add-elements/",
"https://www.dartlang.org/docs/tutorials/cmdline/",
"https://www.dartlang.org/docs/tutorials/connect-dart-html/",
"https://www.dartlang.org/docs/tutorials/fetchdata/",
"https://www.dartlang.org/docs/tutorials/futures/",
"https://www.dartlang.org/docs/tutorials/get-started/",
"https://www.dartlang.org/docs/tutorials/httpserver/",
"https://www.dartlang.org/docs/tutorials/remove-elements/",
"https://www.dartlang.org/docs/tutorials/shared-pkgs/",
"https://www.dartlang.org/docs/tutorials/streams/",
"https://www.dartlang.org/downloads/",
"https://www.dartlang.org/downloads/archive/",
"https://www.dartlang.org/downloads/linux.html",
"https://www.dartlang.org/downloads/mac.html",
"https://www.dartlang.org/downloads/windows.html",
"https://www.dartlang.org/effective-dart/",
"https://www.dartlang.org/effective-dart/design/",
"https://www.dartlang.org/effective-dart/documentation/",
"https://www.dartlang.org/effective-dart/style/",
"https://www.dartlang.org/effective-dart/usage/",
"https://www.dartlang.org/events/2014/flight-school/img/icons/preview.html",
"https://www.dartlang.org/events/2014/flight-school/index.html",
"https://www.dartlang.org/events/2015/summit/about-dart-summit/index.html",
"https://www.dartlang.org/events/2015/summit/attendee-information/index.html",
"https://www.dartlang.org/events/2015/summit/get-involved/index.html",
"https://www.dartlang.org/events/2015/summit/index.html",
"https://www.dartlang.org/events/2015/summit/schedule/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/async-in-dart/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/building-an-awesome-ecosystem/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/building-production-dart-apps-with-a-pure-open-source-workflow/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/dart-at-60fps/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/dart-for-internet-of-things/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/dart-for-mobile/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/dart-for-the-web-state-of-the-union/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/debugging-and-profiling-dart-programs-with-observatory/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/getting-the-most-out-of-dart2js/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/google-fiber-and-dart/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/how-we-built-instill-io-with-dart-and-polymer/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/keynote-ads-and-dart/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/keynote/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/lightning-talks/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/migrating-trustwaves-large-customer-portal-to-dart/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/moving-from-node-js-to-dart/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/panel/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/sky/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/space-frugal-reflection/index.html",
"https://www.dartlang.org/events/2015/summit/sessions/switching-to-dart/index.html",
"https://www.dartlang.org/events/2015/summit/src/index.html",
"https://www.dartlang.org/events/2016/summit/index.html",
"https://www.dartlang.org/hackathons/2012/happy-hour/index.html",
"https://www.dartlang.org/logos/",
"https://www.dartlang.org/performance/",
"https://www.dartlang.org/polymer-old/",
"https://www.dartlang.org/polymer-old/app-directories.html",
"https://www.dartlang.org/polymer-old/creating-elements/",
"https://www.dartlang.org/polymer-old/faq.html",
"https://www.dartlang.org/polymer-old/reference/",
"https://www.dartlang.org/polymer-old/reference/error-messages/",
"https://www.dartlang.org/polymer-old/reference/release-notes/",
"https://www.dartlang.org/polymer-old/spa/",
"https://www.dartlang.org/polymer-old/upgrading-to-polymer-from-web-ui.html",
"https://www.dartlang.org/polymer-old/using-elements/",
"https://www.dartlang.org/polymer-old/using-polymer/",
"https://www.dartlang.org/polymer-old/using-polymer/examples/using_paper_elements/web/index.html",
"https://www.dartlang.org/samples/",
"https://www.dartlang.org/samples/appcache/",
"https://www.dartlang.org/samples/appcache/example/index.html",
"https://www.dartlang.org/samples/appcache/example/offline.html",
"https://www.dartlang.org/samples/dnd/",
"https://www.dartlang.org/samples/dnd/example/index.html",
"https://www.dartlang.org/samples/dndfiles/",
"https://www.dartlang.org/samples/dndfiles/example/dndfiles.html",
"https://www.dartlang.org/samples/dndfiles/example/index.html",
"https://www.dartlang.org/samples/dndfiles/example/monitoring.html",
"https://www.dartlang.org/samples/dndfiles/example/slicing.html",
"https://www.dartlang.org/samples/filesystem/",
"https://www.dartlang.org/samples/filesystem/example/index.html",
"https://www.dartlang.org/samples/geolocation/",
"https://www.dartlang.org/samples/geolocation/example/index.html",
"https://www.dartlang.org/samples/imagefilters/",
"https://www.dartlang.org/samples/imagefilters/example/index.html",
"https://www.dartlang.org/samples/indexeddb_todo/",
"https://www.dartlang.org/samples/indexeddb_todo/example/index.html",
"https://www.dartlang.org/samples/localstorage/",
"https://www.dartlang.org/samples/localstorage/example/index.html",
"https://www.dartlang.org/samples/raf/",
"https://www.dartlang.org/samples/raf/example/index.html",
"https://www.dartlang.org/samples/solar3d/",
"https://www.dartlang.org/samples/solar3d/example/web/solar.html",
"https://www.dartlang.org/samples/terminal/",
"https://www.dartlang.org/samples/terminal/example/index.html",
"https://www.dartlang.org/samples/webaudio/",
"https://www.dartlang.org/samples/webaudio/example/index.html",
"https://www.dartlang.org/samples/websockets/",
"https://www.dartlang.org/samples/websockets/example/index.html",
"https://www.dartlang.org/search.html",
"https://www.dartlang.org/slides/",
"https://www.dartlang.org/slides/2011/12/gtug/",
"https://www.dartlang.org/slides/2012/06/io12/dart-a-modern-web-language.html",
"https://www.dartlang.org/slides/2012/06/io12/putting-the-app-back-into-web-apps.html",
"https://www.dartlang.org/support/",
"https://www.dartlang.org/support/faq.html",
"https://www.dartlang.org/tools/",
"https://www.dartlang.org/tools/dart-vm/",
"https://www.dartlang.org/tools/dart2js/",
"https://www.dartlang.org/tools/dartium/",
"https://www.dartlang.org/tools/faq.html",
"https://www.dartlang.org/tools/jetbrains-plugin/",
"https://www.dartlang.org/tools/private-files.html",
"https://www.dartlang.org/tools/pub/",
"https://www.dartlang.org/tools/pub/assets-and-transformers.html",
"https://www.dartlang.org/tools/pub/cmd/",
"https://www.dartlang.org/tools/pub/cmd/pub-build.html",
"https://www.dartlang.org/tools/pub/cmd/pub-cache.html",
"https://www.dartlang.org/tools/pub/cmd/pub-deps.html",
"https://www.dartlang.org/tools/pub/cmd/pub-downgrade.html",
"https://www.dartlang.org/tools/pub/cmd/pub-get.html",
"https://www.dartlang.org/tools/pub/cmd/pub-global.html",
"https://www.dartlang.org/tools/pub/cmd/pub-lish.html",
"https://www.dartlang.org/tools/pub/cmd/pub-run.html",
"https://www.dartlang.org/tools/pub/cmd/pub-serve.html",
"https://www.dartlang.org/tools/pub/cmd/pub-upgrade.html",
"https://www.dartlang.org/tools/pub/cmd/pub-uploader.html",
"https://www.dartlang.org/tools/pub/create-library-packages.html",
"https://www.dartlang.org/tools/pub/dart2js-transformer.html",
"https://www.dartlang.org/tools/pub/dependencies.html",
"https://www.dartlang.org/tools/pub/faq.html",
"https://www.dartlang.org/tools/pub/get-started.html",
"https://www.dartlang.org/tools/pub/glossary.html",
"https://www.dartlang.org/tools/pub/installing.html",
"https://www.dartlang.org/tools/pub/package-layout.html",
"https://www.dartlang.org/tools/pub/publishing.html",
"https://www.dartlang.org/tools/pub/pubspec.html",
"https://www.dartlang.org/tools/pub/transformers/",
"https://www.dartlang.org/tools/pub/transformers/aggregate.html",
"https://www.dartlang.org/tools/pub/transformers/examples/",
"https://www.dartlang.org/tools/pub/transformers/lazy-transformer.html",
"https://www.dartlang.org/tools/pub/troubleshoot.html",
"https://www.dartlang.org/tools/pub/versioning.html",
"https://www.dartlang.org/tools/sdk/",
"https://www.dartlang.org/tools/webstorm/",
"https://www.dartlang.org/tos.html"
] | 61.888393 | 133 | 0.709587 |
08e43d378c83bc734256d174d591aa3f7697fe84 | 827 | require 'facets/proc/bind'
class Proc
# Convert Proc to method.
#
# plusproc = lambda { |x| x + 1 }
# plusproc.to_method(self, 'foo')
# X.new.foo(1) #=> 2
def to_method(object, name=nil)
#object = object || eval("self", self)
block, time = self, Time.now
method_name = name || "__bind_#{time.to_i}_#{time.usec}"
begin
(class << object; self; end).class_eval do
define_method(method_name, &block)
method = instance_method(method_name)
remove_method(method_name) unless name
method
end.bind(object)
rescue TypeError
object.class.class_eval do
define_method(method_name, &block)
method = instance_method(method_name)
remove_method(method_name) unless name
method
end.bind(object)
end
end
end
| 24.323529 | 60 | 0.625151 |
6a510b33c751c2c4c73c1bcf7d1fd681f8b61b80 | 1,191 | class Jansson < Formula
desc "C library for encoding, decoding, and manipulating JSON"
homepage "http://www.digip.org/jansson/"
url "http://www.digip.org/jansson/releases/jansson-2.10.tar.gz"
sha256 "78215ad1e277b42681404c1d66870097a50eb084be9d771b1d15576575cf6447"
bottle do
cellar :any
sha256 "701c9253fb60487c94b4840a57621d5faf6ad1a8d0659ae6a419e57b5bd94ced" => :sierra
sha256 "a51789b3b30f9e70232f9e872b08b5367caa5d027f7a8a72ed92c2ef68c432b7" => :el_capitan
sha256 "4fabfb2143c27b4460560af12a459180221f097ad69ed95e86cf082b436d4950" => :yosemite
end
def install
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
test do
(testpath/"test.c").write <<-EOS.undent
#include <jansson.h>
#include <assert.h>
int main()
{
json_t *json;
json_error_t error;
json = json_loads("\\"foo\\"", JSON_DECODE_ANY, &error);
assert(json && json_is_string(json));
json_decref(json);
return 0;
}
EOS
system ENV.cc, "test.c", "-L#{lib}", "-ljansson", "-o", "test"
system "./test"
end
end
| 30.538462 | 92 | 0.661629 |
3385fd667c10347a12c83442cea08e33dd3338aa | 6,610 | # encoding: binary
#
# This file is taken from Unicorn. The following license applies to this file
# (and this file only, not to the rest of Phusion Passenger):
#
# 1. You may make and give away verbatim copies of the source form of the
# software without restriction, provided that you duplicate all of the
# original copyright notices and associated disclaimers.
#
# 2. You may modify your copy of the software in any way, provided that
# you do at least ONE of the following:
#
# a) place your modifications in the Public Domain or otherwise make them
# Freely Available, such as by posting said modifications to Usenet or an
# equivalent medium, or by allowing the author to include your
# modifications in the software.
#
# b) use the modified software only within your corporation or
# organization.
#
# c) rename any non-standard executables so the names do not conflict with
# standard executables, which must also be provided.
#
# d) make other distribution arrangements with the author.
#
# 3. You may distribute the software in object code or executable
# form, provided that you do at least ONE of the following:
#
# a) distribute the executables and library files of the software,
# together with instructions (in the manual page or equivalent) on where
# to get the original distribution.
#
# b) accompany the distribution with the machine-readable source of the
# software.
#
# c) give non-standard executables non-standard names, with
# instructions on where to get the original software distribution.
#
# d) make other distribution arrangements with the author.
#
# 4. You may modify and include the part of the software into any other
# software (possibly commercial). But some files in the distribution
# are not written by the author, so that they are not under this terms.
#
# 5. The scripts and library files supplied as input to or produced as
# output from the software do not automatically fall under the
# copyright of the software, but belong to whomever generated them,
# and may be sold commercially, and may be aggregated with this
# software.
#
# 6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE.
require 'stringio'
PhusionPassenger.require_passenger_lib 'utils/tmpio'
module PhusionPassenger
module Utils
# acts like tee(1) on an input input to provide a input-like stream
# while providing rewindable semantics through a File/StringIO backing
# store. On the first pass, the input is only read on demand so your
# Rack application can use input notification (upload progress and
# like). This should fully conform to the Rack::Lint::InputWrapper
# specification on the public API. This class is intended to be a
# strict interpretation of Rack::Lint::InputWrapper functionality and
# will not support any deviations from it.
#
# When processing uploads, Unicorn exposes a TeeInput object under
# "rack.input" of the Rack environment.
class TeeInput
CONTENT_LENGTH = "CONTENT_LENGTH".freeze
HTTP_TRANSFER_ENCODING = "HTTP_TRANSFER_ENCODING".freeze
CHUNKED = "chunked".freeze
# The maximum size (in +bytes+) to buffer in memory before
# resorting to a temporary file. Default is 112 kilobytes.
@@client_body_buffer_size = 112 * 1024
# sets the maximum size of request bodies to buffer in memory,
# amounts larger than this are buffered to the filesystem
def self.client_body_buffer_size=(bytes)
@@client_body_buffer_size = bytes
end
# returns the maximum size of request bodies to buffer in memory,
# amounts larger than this are buffered to the filesystem
def self.client_body_buffer_size
@@client_body_buffer_size
end
# Initializes a new TeeInput object. You normally do not have to call
# this unless you are writing an HTTP server.
def initialize(socket, env)
if @len = env[CONTENT_LENGTH]
@len = @len.to_i
elsif env[HTTP_TRANSFER_ENCODING] != CHUNKED
@len = 0
end
@socket = socket
@bytes_read = 0
if @len && @len <= @@client_body_buffer_size
@tmp = StringIO.new("")
else
@tmp = TmpIO.new("PassengerTeeInput")
end
@tmp.binmode
end
def close
@tmp.close
end
def size
if @len
@len
else
pos = @tmp.pos
consume!
@tmp.pos = pos
@len = @tmp.size
end
end
def read(len = nil, buf = "")
buf ||= ""
if len
if len < 0
raise ArgumentError, "negative length #{len} given"
elsif len == 0
buf.replace('')
buf
else
if socket_drained?
@tmp.read(len, buf)
else
tee(read_exact(len, buf))
end
end
else
if socket_drained?
@tmp.read(nil, buf)
else
tee(read_all(buf))
end
end
end
def gets
if socket_drained?
@tmp.gets
else
if @bytes_read == @len
nil
elsif line = @socket.gets
if @len
max_len = @len - @bytes_read
line.slice!(max_len, line.size - max_len)
end
@bytes_read += line.size
tee(line)
else
nil
end
end
end
def rewind
return 0 if 0 == @tmp.size
consume! if !socket_drained?
@tmp.rewind # Rack does not specify what the return value is here
end
def each
while line = gets
yield line
end
self # Rack does not specify what the return value is here
end
private
def socket_drained?
if @socket
if @socket.eof?
@socket = nil
true
else
false
end
else
true
end
end
# consumes the stream of the socket
def consume!
junk = ""
nil while read(16 * 1024, junk)
@socket = nil
end
def tee(buffer)
if buffer && buffer.size > 0
@tmp.write(buffer)
end
buffer
end
def read_exact(len, buf)
if @len
max_len = @len - @bytes_read
len = max_len if len > max_len
return nil if len == 0
end
ret = @socket.read(len, buf)
@bytes_read += ret.size if ret
ret
end
def read_all(buf)
if @len
ret = @socket.read(@len - @bytes_read, buf)
if ret
@bytes_read += ret.size
ret
else
buf.replace("")
buf
end
else
ret = @socket.read(nil, buf)
@bytes_read += ret.size
ret
end
end
end
end # module Utils
end # module PhusionPassenger
| 27.090164 | 79 | 0.663691 |
e91b1274cf5c57ce56d53c820c3541b27e2f50de | 55 | class InventoryItemDefinition < ActiveRecord::Base
end
| 18.333333 | 50 | 0.854545 |
4abc42e6afe6292fee7ae7f977863fad08b06a5b | 44 | module Certifi
VERSION = "2018.01.18"
end
| 11 | 24 | 0.704545 |
38e95fb871e4a1e946b25504ee45343db4912492 | 5,655 | require "cribbage/version"
require "cribbage/console"
require 'awesome_print'
module Cribbage
# Input:
# H = heart S = spade D = diamond C = club
# AH 5C 6D 7S 8C QD 9C
class Card
# Str format:
# "5h" = five of hearts
# "AD" = ace of diamonds
# "10c" = ten of clubs
attr_accessor :value
attr_accessor :face_value
attr_accessor :suit
attr_accessor :card_str
attr_accessor :index # index in a hand. Ie A = 0,
INDEX = %w(A 2 3 4 5 6 7 8 9 10 J Q K)
SUITS = {'H' => '♥', 'D' => '♦', 'C' => '♣', 'S' => '♠'}
def initialize(str)
raise "String cannot be blank!" if str.nil?
raise "Must be a string!" unless str.is_a?(String)
raise "Invalid length" if (str.size < 2 or str.size > 3)
@value = self.compute_value(str.chop)
@face_value = str.chop.upcase
raise "Invalid face value" unless INDEX.include?(@face_value)
@index = INDEX.index(@face_value)
@suit = str[-1].upcase
@card_str = str
end
def to_s
"[#{@face_value}#{SUITS[@suit]}]"
end
def compute_value(char)
return 1 if char.upcase=='A'
return 10 if %w(J Q K).include?(char.upcase)
if char.to_i > 0 and char.to_i <= 10
return char.to_i
end
raise "Could not compute value of #{char}"
end
end
class Hand
attr :points
# key: fifteens
# cards: [ [1,2], [3,4] ] MUST BE Nested array
# points: 4
attr :cards
# Input is an array of strings from the command line
# I.E. 4H JD QD KH 3H
def initialize(cards_array)
@cards = [ ]
@points = { }
cards_array.each { |c| @cards << Card.new(c) }
find_fifteens
find_runs
find_pairs
find_flush
find_nobs
end
def starter_card
@cards.first
end
def players_cards
@cards[[email protected]]
end
def total_score
score = 0
@points.each do |k,v|
score += v[:point_value]
end
score
end
def print_score
# Your Hand
# 5H | 6D 3D JH
#
# Total Points: +17
# Fifteens (+8): (5 5 5), (5 J), (5 J), (5 K)
# Runs:
#
$stdout.printf "\n\n"
$stdout.printf "%-3s %-21s %-10s\n\n", '', 'Hand:', starter_card.to_s + "" + players_cards.join('')
print_points :fifteens
print_points :runs
print_points :pairs
print_points :flush
print_points :nobs
$stdout.printf "\n%-3s %-10s %-10s\n", '', 'Total:', "+#{total_score}"
$stdout.printf "\n\n"
end
#
def print_points(key)
if @points[key].nil?
return false
end
cards = @points[key.to_sym][:cards] # should be array of array
str = cards.map { |c| "" + c.join('') + "" }.join ", "
title = key.to_s
$stdout.printf "%-3s %-10s %-10s %-10s\n", '', title, "+#{@points[key][:point_value]}", str
end
def print_cards(label, cards)
str = cards.map { |c| c.card_str }.join " "
ap "#{label}: #{str}"
end
def find_fifteens
found = nil
[2,3,4,5].each do |combo_size|
@cards.combination(combo_size).each do |card_combo|
# Check for 15s
card_count = 0
card_combo.each { |card| card_count += card.value }
if card_count == 15
found ||= [ ]
found << card_combo
end
end
end
if found!=nil
@points[:fifteens] = {cards: found, point_value: found.size*2}
end
end
def find_runs
found = { }
[5,4,3].each do |combo_size|
@cards.combination(combo_size).each do |combo|
combo = combo.sort { |x,y| x.index <=> y.index } # sort by index
next unless combo.map(&:face_value).uniq.size == combo.size # all cards must be unique
if (combo.last.index - combo.first.index) == (combo.size-1)
found[combo_size] ||= [ ]
found[combo_size] << combo
end
end
end
if found.has_key?(5)
@points[:runs] = {cards: found[5], point_value: 5}
return true
end
if found.has_key?(4)
cards = found[4]
@points[:runs] = {cards: cards, point_value: cards.first.size*cards.size}
return true
end
if found.has_key?(3)
cards = found[3]
@points[:runs] = {cards: cards, point_value: cards.first.size*cards.size}
return found[3]
end
return nil
end
def find_pairs
found = [ ]
@cards.combination(2).each do |pair|
if pair.first.face_value == pair.last.face_value
found << pair
end
end
if found.size==0
return nil
else
@points[:pairs] = {cards: found, point_value: found.size*2}
end
end
def find_flush
hand = @cards
if @cards.map(&:suit).uniq.size == 1
@points[:flush] = {cards: [@cards], point_value: 5}
return true
end
if players_cards.map(&:suit).uniq.size == 1
@points[:flush] = {cards: [ players_cards ], point_value: 4}
return true
end
return nil
end
def find_heels
# Awarded when the starter card is a Jack
if starter_card.face_value=='J'
@points[:heels] = {cards: [[starter_card]], point_value: 2}
end
end
def find_nobs
# One for nobs
jacks = players_cards.keep_if {|c| c.face_value=='J'}
if jacks.map(&:suit).include?(starter_card.suit)
@points[:nobs] = {cards: [ jacks.keep_if { |j| starter_card.suit==j.suit } ], point_value: 1}
end
return nil
end
end
end
| 25.133333 | 105 | 0.54695 |
26501e238d2c8ff74b3b9cc9b6497978db7abafd | 50 | module StaticCodeAnalyzer
VERSION = '0.1.3'
end
| 12.5 | 25 | 0.74 |
e219a001724c0d9a167d3e7c4f0ca492d45f6a75 | 3,118 | class Docbook < Formula
desc "Standard SGML representation system for technical documents"
homepage "https://docbook.org/"
url "https://docbook.org/xml/5.0/docbook-5.0.zip"
sha256 "3dcd65e1f5d9c0c891b3be204fa2bb418ce485d32310e1ca052e81d36623208e"
bottle do
cellar :any_skip_relocation
rebuild 3
sha256 "0f99e9e2e42f4a21bdb9066f02e247c919c21f586cea0bcd787c9112659df030" => :high_sierra
sha256 "40b2740609c1586d030d3b9a131761821425c211989bee297af29900981b3aba" => :sierra
sha256 "3fb7e4070eaa9250fa947d38e3d7803d37c159d9765e3f71397702d5ad6bb578" => :el_capitan
sha256 "dfdb315404c98dca2682f63260f2996de101cb6b41de69ac268dcded110e2a3f" => :yosemite
sha256 "65925fda670fdb020fe9d52cd5891f8e3a2a44619e9129b30031127c7c2e998c" => :mavericks
end
resource "xml412" do
url "https://docbook.org/xml/4.1.2/docbkx412.zip"
sha256 "30f0644064e0ea71751438251940b1431f46acada814a062870f486c772e7772"
version "4.1.2"
end
resource "xml42" do
url "https://docbook.org/xml/4.2/docbook-xml-4.2.zip"
sha256 "acc4601e4f97a196076b7e64b368d9248b07c7abf26b34a02cca40eeebe60fa2"
end
resource "xml43" do
url "https://docbook.org/xml/4.3/docbook-xml-4.3.zip"
sha256 "23068a94ea6fd484b004c5a73ec36a66aa47ea8f0d6b62cc1695931f5c143464"
end
resource "xml44" do
url "https://docbook.org/xml/4.4/docbook-xml-4.4.zip"
sha256 "02f159eb88c4254d95e831c51c144b1863b216d909b5ff45743a1ce6f5273090"
end
resource "xml45" do
url "https://docbook.org/xml/4.5/docbook-xml-4.5.zip"
sha256 "4e4e037a2b83c98c6c94818390d4bdd3f6e10f6ec62dd79188594e26190dc7b4"
end
resource "xml50" do
url "https://docbook.org/xml/5.0/docbook-5.0.zip"
sha256 "3dcd65e1f5d9c0c891b3be204fa2bb418ce485d32310e1ca052e81d36623208e"
end
def install
(etc/"xml").mkpath
%w[42 412 43 44 45 50].each do |version|
resource("xml#{version}").stage do |r|
if version == "412"
cp prefix/"docbook/xml/4.2/catalog.xml", "catalog.xml"
inreplace "catalog.xml" do |s|
s.gsub! "V4.2 ..", "V4.1.2 "
s.gsub! "4.2", "4.1.2"
end
end
rm_rf "docs"
(prefix/"docbook/xml"/r.version).install Dir["*"]
end
end
end
def post_install
ENV["XML_CATALOG_FILES"] = "#{etc}/xml/catalog"
# only create catalog file if it doesn't exist already to avoid content added
# by other formulae to be removed
unless File.file?("#{etc}/xml/catalog")
system "xmlcatalog", "--noout", "--create", "#{etc}/xml/catalog"
end
%w[4.2 4.1.2 4.3 4.4 4.5 5.0].each do |version|
catalog = prefix/"docbook/xml/#{version}/catalog.xml"
system "xmlcatalog", "--noout", "--del",
"file://#{catalog}", "#{etc}/xml/catalog"
system "xmlcatalog", "--noout", "--add", "nextCatalog",
"", "file://#{catalog}", "#{etc}/xml/catalog"
end
end
def caveats; <<~EOS
To use the DocBook package in your XML toolchain,
you need to add the following to your ~/.bashrc:
export XML_CATALOG_FILES="#{etc}/xml/catalog"
EOS
end
end
| 32.821053 | 93 | 0.690507 |
f835b0feb90107057df8ab3feb185b38740e6eca | 1,605 | control "ESXI-67-000040" do
title "The ESXi host must use multifactor authentication for local DCUI
access to privileged accounts."
desc "To assure accountability and prevent unauthenticated access,
privileged users must utilize multifactor authentication to prevent potential
misuse and compromise of the system.
Note: This feature requires an existing PKI and AD integration."
impact 0.3
tag severity: "CAT III"
tag gtitle: "SRG-OS-000107-VMM-000530"
tag rid: "ESXI-67-000040"
tag stig_id: "ESXI-67-000040"
tag cci: "CCI-000767"
tag nist: ["IA-2 (3)", "Rev_4"]
desc 'check', "From the vSphere Client select the ESXi Host and go to Configure
>> System >> Authentication Services and view the Smart Card Authentication
status.
If \"Smart Card Mode\" is \"Disabled\", this is a finding.
For environments that do have PKI or AD available, this is not applicable."
desc 'fix', "The following are pre-requisites to configuration smart card
authentication for the ESXi DCUI:
-Active Directory domain that supports smart card authentication, smart card
readers, and smart cards.
-ESXi joined to an Active Directory domain.
-Trusted certificates for root and intermediary certificate authorities.
From the vSphere Client select the ESXi Host and go to Configure >> System >>
Authentication Services and click Edit and check \"Enable Smart Card
Authentication\" checkbox, at the Certificates tab, click the green plus sign
to import trusted certificate authority certificates and click OK."
describe "" do
skip 'Manual verification is required for this control'
end
end
| 38.214286 | 81 | 0.770093 |
62841223d6ad694c9add3301d5691043db7bc2e9 | 57 | class Route < ApplicationRecord
belongs_to :area
end
| 14.25 | 31 | 0.77193 |
33814fce3cc8cd11fd843f4388233252a0bf57b0 | 1,624 | require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
end
test "login with valid email/invalid password" do
get login_path
assert_template 'sessions/new'
post login_path, params: { session: { email: @user.email,password: "invalid" } }
assert_not is_logged_in?
assert_template 'sessions/new'
assert_not flash.empty?
get root_path
assert flash.empty?
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
# cookieを保存してログイン
log_in_as(@user, remember_me: '1')
delete logout_path
# cookieを削除してログイン
log_in_as(@user, remember_me: '0')
assert_empty cookies[:remember_token]
end
end
| 29 | 87 | 0.684729 |
d5bf981ee33ec5a45b059441c866e1d2aeef6385 | 611 | # encoding: UTF-8
require_relative 'api/api'
require_relative './config'
require_relative './area'
require_relative './context'
require_relative './coordinate'
require_relative './ellipsoid'
require_relative './error'
require_relative './point'
require_relative './prime_meridian'
require_relative './unit'
require_relative './pj_object'
require_relative './operation'
require_relative './crs'
require_relative './projection'
require_relative './transformation'
module Proj
def self.info
Api.proj_info
end
def self.version
self.info[:version]
end
end
Proj::Config.instance.set_search_paths | 19.709677 | 38 | 0.772504 |
4a98a02bb1b8d9efb817c51ff8fcf8f4820c8c89 | 1,529 | # frozen_string_literal: true
require 'spec_helper'
describe RecordNotUnique, use_connection: true do
it "rescues ActiveRecord::RecordNotUnique exceptions as activerecord errors" do
company = Company.create(name: 'test')
dupe = Company.create(name: 'test')
expect(dupe.save).to eql false
expect(dupe.errors.messages.keys).to contain_exactly(:name)
expect(dupe.errors[:name].first).to match /has already been taken/
end
it "raises when used with ! methods like save!" do
expect {
Company.create!(name: 'test')
}.to raise_exception(ActiveRecord::RecordNotUnique)
end
it "When unique contraint is voilated by a composite index" do
company = Company.first
user = User.create(name: 'foo', username: 'foo', company_id: company.id)
dupe = User.create(name: 'bar', username: 'foo', company_id: company.id)
expect(dupe.save).to eql(false)
expect(dupe.errors.messages.keys).to contain_exactly(:username)
expect(dupe.errors.full_messages.to_sentence).to match /#{company.name}/
end
it "Works for multiple indexes" do
company1 = Company.first
company2 = Company.create(name: 'test2')
user = User.create(name: 'foo', username: 'foo', company_id: company2.id)
dupe = User.create(name: 'foo', username: 'bar', company_id: company2.id)
expect(dupe.save).to eql(false)
expect(dupe.errors.messages.keys).to contain_exactly(:name)
expect(dupe.errors.full_messages.to_sentence).to match /has already been taken/
end
end | 35.55814 | 83 | 0.706344 |
d564c8df038883f882fb84af87ed00be53d413ed | 6,606 | require 'rails_helper'
RSpec.describe StatusController, type: :request do
describe '#healthcheck' do
before do
allow(Sidekiq::ProcessSet).to receive(:new).and_return(instance_double(Sidekiq::ProcessSet, size: 1))
allow(Sidekiq::RetrySet).to receive(:new).and_return(instance_double(Sidekiq::RetrySet, size: 0))
allow(Sidekiq::DeadSet).to receive(:new).and_return(instance_double(Sidekiq::DeadSet, size: 0))
connection = double('connection')
allow(connection).to receive(:info).and_return(redis_version: '5.0.0')
allow(Sidekiq).to receive(:redis).and_yield(connection)
end
context 'when failed Sidekiq jobs exist' do
let(:failed_job_healthcheck) do
{
checks: {
database: true,
redis: true,
sidekiq: true,
sidekiq_queue: false,
malware_scanner: {
positive: true,
negative: true
}
}
}.to_json
end
context 'dead set exists' do
before do
allow(Sidekiq::DeadSet).to receive(:new).and_return(instance_double(Sidekiq::DeadSet, size: 1))
get '/healthcheck'
end
it 'returns ok http status' do
expect(response).to have_http_status :ok
end
it 'returns the expected response report' do
expect(response.body).to eq(failed_job_healthcheck)
end
end
context 'retry set exists' do
before do
allow(Sidekiq::RetrySet).to receive(:new).and_return(instance_double(Sidekiq::RetrySet, size: 1))
get '/healthcheck'
end
it 'returns ok http status' do
expect(response).to have_http_status :ok
end
it 'returns the expected response report' do
expect(response.body).to eq(failed_job_healthcheck)
end
end
end
context 'when an infrastructure problem exists' do
before do
allow(ActiveRecord::Base.connection).to receive(:active?).and_raise(PG::ConnectionBad)
allow(Sidekiq::ProcessSet).to receive(:new).and_return(instance_double(Sidekiq::ProcessSet, size: 0))
connection = double('connection')
allow(connection).to receive(:info).and_raise(Redis::CannotConnectError)
allow(Sidekiq).to receive(:redis).and_yield(connection)
get '/healthcheck'
end
let(:failed_healthcheck) do
{
checks: {
database: false,
redis: false,
sidekiq: false,
sidekiq_queue: true,
malware_scanner: {
positive: true,
negative: true
}
}
}.to_json
end
it 'returns status bad gateway' do
expect(response).to have_http_status :bad_gateway
end
it 'returns the expected response report' do
expect(response.body).to eq(failed_healthcheck)
end
end
context 'when Sidekiq::ProcessSet encounters an error' do
before do
allow(Sidekiq::ProcessSet).to receive(:new).and_raise(StandardError)
get '/healthcheck'
end
let(:failed_healthcheck) do
{
checks: {
database: true,
redis: true,
sidekiq: false,
sidekiq_queue: true,
malware_scanner: {
positive: true,
negative: true
}
}
}.to_json
end
it 'returns status bad gateway' do
expect(response).to have_http_status :bad_gateway
end
it 'returns the expected response report' do
expect(response.body).to eq(failed_healthcheck)
end
end
context 'when sidekiq_queue_healthy encounters an error' do
before do
allow(Sidekiq::DeadSet).to receive(:new).and_raise(StandardError)
get '/healthcheck'
end
let(:failed_healthcheck) do
{
checks: {
database: true,
redis: true,
sidekiq: true,
sidekiq_queue: false,
malware_scanner: {
positive: true,
negative: true
}
}
}.to_json
end
it 'returns ok http status' do
# queue health should not impact the status
expect(response).to have_http_status :ok
end
it 'returns the expected response report' do
expect(response.body).to eq(failed_healthcheck)
end
end
context 'when everything is ok' do
before do
allow(ActiveRecord::Base.connection).to receive(:active?).and_return(true)
connection = double('connection', info: {})
allow(Sidekiq).to receive(:redis).and_yield(connection)
get '/healthcheck'
end
let(:expected_response) do
{
checks: {
database: true,
redis: true,
sidekiq: true,
sidekiq_queue: true,
malware_scanner: {
positive: true,
negative: true
}
}
}.to_json
end
it 'returns HTTP success' do
get '/healthcheck'
expect(response.status).to eq(200)
end
it 'returns the expected response report' do
get '/healthcheck'
expect(response.body).to eq(expected_response)
end
end
end
describe '#ping' do
context 'when environment variables set' do
let(:expected_json) do
{
'build_date' => '20150721',
'build_tag' => 'test',
'app_branch' => 'test_branch'
}
end
before do
allow(Rails.configuration.x.status).to receive(:build_date).and_return('20150721')
allow(Rails.configuration.x.status).to receive(:build_tag).and_return('test')
allow(Rails.configuration.x.status).to receive(:app_branch).and_return('test_branch')
get('/ping')
end
it 'returns JSON with app information' do
expect(JSON.parse(response.body)).to eq(expected_json)
end
end
context 'when environment variables not set' do
before do
allow(Rails.configuration.x.status).to receive(:build_date).and_return('Not Available')
allow(Rails.configuration.x.status).to receive(:build_tag).and_return('Not Available')
allow(Rails.configuration.x.status).to receive(:app_branch).and_return('Not Available')
get '/ping'
end
it 'returns "Not Available"' do
expect(JSON.parse(response.body).values).to be_all('Not Available')
end
end
end
end
| 28.230769 | 109 | 0.589767 |
bffa57504f7b8be7dc093bcef6a226bad3fa58b9 | 17,661 | # encoding: UTF-8
class AddMissingBallotsInds < ActiveRecord::Migration
def up
total_ind_id = 15
event_names = ['2012 Parliamentary - Party List', '2012 Parliamentary - Majoritarian']
events = Event.includes(:event_translations).where(:event_translations => {:name => event_names, :locale => 'en'})
old_core_names = ['Precincts with Validation Errors (%)', 'Precincts with Validation Errors (#)', 'Average Number of Validation Errors', 'Number of Validation Errors']
cores = []
old_core_names.each do |old_name|
x = CoreIndicator.includes(:core_indicator_translations).where(:core_indicator_translations => {:name => old_name, :locale => 'en'})
cores << x.first if x.present?
end
if events.present? && events.length == event_names.length
CoreIndicator.transaction do
##########################
# add core inds
# precincts with More Ballots Than Votes (%)
exists = CoreIndicatorTranslation.where(:locale => 'en', :name => 'Precincts with More Ballots Than Votes (%)')
if exists.present?
prec_missing_perc = CoreIndicator.find_by_id(exists.first.core_indicator_id)
else
prec_missing_perc = CoreIndicator.create(:indicator_type_id => 1, :number_format => '%')
prec_missing_perc.core_indicator_translations.create(:locale => 'en', :name => 'Precincts with More Ballots Than Votes (%)',
:name_abbrv => 'More Ballots Than Votes (%)', :description => 'Precincts with More Ballots Than Votes (%)')
prec_missing_perc.core_indicator_translations.create(:locale => 'ka', :name => 'საარჩევნო უბნები ხმებზე მეტი ბიულეტენებით (%)',
:name_abbrv => 'ხმებზე მეტი ბიულეტენები (%)', :description => 'საარჩევნო უბნები ხმებზე მეტი ბიულეტენებით (%)')
end
# precincts with More Ballots Than Votes (#)
exists = CoreIndicatorTranslation.where(:locale => 'en', :name => 'Precincts with More Ballots Than Votes (#)')
if exists.present?
prec_missing_num = CoreIndicator.find_by_id(exists.first.core_indicator_id)
else
prec_missing_num = CoreIndicator.create(:indicator_type_id => 1)
prec_missing_num.core_indicator_translations.create(:locale => 'en', :name => 'Precincts with More Ballots Than Votes (#)',
:name_abbrv => 'More Ballots Than Votes (#)', :description => 'Precincts with More Ballots Than Votes (#)')
prec_missing_num.core_indicator_translations.create(:locale => 'ka', :name => 'საარჩევნო უბნები ხმებზე მეტი ბიულეტენებით (#)',
:name_abbrv => 'ხმებზე მეტი ბიულეტენები (#)', :description => 'საარჩევნო უბნები ხმებზე მეტი ბიულეტენებით (#)')
end
# avg # of More Ballots Than Votes
exists = CoreIndicatorTranslation.where(:locale => 'en', :name => 'More Ballots Than Votes (Average)')
if exists.present?
avg = CoreIndicator.find_by_id(exists.first.core_indicator_id)
else
avg = CoreIndicator.create(:indicator_type_id => 1)
avg.core_indicator_translations.create(:locale => 'en', :name => 'More Ballots Than Votes (Average)',
:name_abbrv => 'More Ballots Than Votes (Avg)', :description => 'More Ballots Than Votes (Average)')
avg.core_indicator_translations.create(:locale => 'ka', :name => 'ხმებზე მეტი ბიულეტენები (საშუალო)',
:name_abbrv => 'ხმებზე მეტი ბიულეტენები (საშუალო)', :description => 'ხმებზე მეტი ბიულეტენები (საშუალო)')
end
# More Ballots Than Votes (#)
exists = CoreIndicatorTranslation.where(:locale => 'en', :name => 'More Ballots Than Votes (#)')
if exists.present?
missing = CoreIndicator.find_by_id(exists.first.core_indicator_id)
else
missing = CoreIndicator.create(:indicator_type_id => 1)
missing.core_indicator_translations.create(:locale => 'en', :name => 'More Ballots Than Votes (#)',
:name_abbrv => 'More Ballots Than Votes (#)', :description => 'More Ballots Than Votes (#)')
missing.core_indicator_translations.create(:locale => 'ka', :name => 'ხმებზე მეტი ბიულეტენები (#)',
:name_abbrv => 'ხმებზე მეტი ბიულეტენები (#)', :description => 'ხმებზე მეტი ბიულეტენები (#)')
end
events.each do |event|
# add if not exists
if EventIndicatorRelationship.where(:event_id => event.id, :core_indicator_id => prec_missing_perc.id).blank? &&
EventIndicatorRelationship.where(:event_id => event.id, :core_indicator_id => missing.id).blank?
##########################
# create relationships
# - non-precinct relationship
EventIndicatorRelationship.create(:event_id => event.id, :core_indicator_id => prec_missing_perc.id, :related_core_indicator_id => prec_missing_num.id,
:sort_order => 1, :visible => true, :has_openlayers_rule_value => false)
EventIndicatorRelationship.create(:event_id => event.id, :core_indicator_id => prec_missing_perc.id, :related_core_indicator_id => prec_missing_perc.id,
:sort_order => 2, :visible => true, :has_openlayers_rule_value => true)
EventIndicatorRelationship.create(:event_id => event.id, :core_indicator_id => prec_missing_perc.id, :related_core_indicator_id => avg.id,
:sort_order => 3, :visible => true, :has_openlayers_rule_value => false)
EventIndicatorRelationship.create(:event_id => event.id, :core_indicator_id => prec_missing_perc.id, :related_core_indicator_id => total_ind_id,
:sort_order => 4, :visible => true, :has_openlayers_rule_value => false)
# - precinct relationship
EventIndicatorRelationship.create(:event_id => event.id, :core_indicator_id => missing.id, :related_core_indicator_id => missing.id,
:sort_order => 1, :visible => true, :has_openlayers_rule_value => true)
EventIndicatorRelationship.create(:event_id => event.id, :core_indicator_id => missing.id, :related_core_indicator_id => total_ind_id,
:sort_order => 4, :visible => true, :has_openlayers_rule_value => false)
end
# for each event, clone indicators/scales for new indicators
puts "=================="
if cores.present? && cores.length == old_core_names.length
puts "cloning indicators for event #{event.id}"
cores.each_with_index do |core, i|
puts "- cloning core #{core.id}"
new_core_id = nil
case i
when 0
new_core_id = prec_missing_perc.id
when 1
new_core_id = prec_missing_num.id
when 2
new_core_id = avg.id
when 3
new_core_id = missing.id
end
puts "- new core id = #{new_core_id}; cloning"
Indicator.clone_from_core_indicator(event.id, core.id, event.id, new_core_id) if new_core_id.present?
if i == 3
puts "-- this is the last core ind, fixing stuff"
# clone process does not work when ind has parent id that is not itself
# - manual fix for precincts (%) -> number
fix_inds = Indicator.where(:event_id => event.id, :core_indicator_id => prec_missing_perc.id, :shape_type_id => 3)
if fix_inds.present?
puts "-- found ind for prec missing % at district"
Indicator.where(:event_id => event.id, :core_indicator_id => new_core_id).each do |fix_ind|
puts "--- fixing parent id from #{fix_ind.parent_id} to #{fix_inds.first.id}"
fix_ind.parent_id = fix_inds.first.id
fix_ind.save
# the old validation errors scale for number of validation errors (at precinct level)
# had scale of < 0
# this was cloned for the new indicators, but is no longer needed
fix_scale_ids = fix_ind.indicator_scales.map{|x| x.id}
if fix_scale_ids.present?
puts "--- removing '<0' scale"
matches = IndicatorScaleTranslation.select('indicator_scale_id').where(:indicator_scale_id => fix_scale_ids, :name => '<0')
IndicatorScale.where(:id => matches.map{|x| x.indicator_scale_id}.uniq).destroy_all if matches.present?
end
end
end
end
puts "- finished cloning"
end
end
end
##########################
##########################
##########################
##########################
# add core inds
# precincts with More Votes Than Ballots (%)
exists = CoreIndicatorTranslation.where(:locale => 'en', :name => 'Precincts with More Votes Than Ballots (%)')
if exists.present?
prec_missing_perc = CoreIndicator.find_by_id(exists.first.core_indicator_id)
else
prec_missing_perc = CoreIndicator.create(:indicator_type_id => 1, :number_format => '%')
prec_missing_perc.core_indicator_translations.create(:locale => 'en', :name => 'Precincts with More Votes Than Ballots (%)',
:name_abbrv => 'More Votes Than Ballots (%)', :description => 'Precincts with More Votes Than Ballots (%)')
prec_missing_perc.core_indicator_translations.create(:locale => 'ka', :name => 'საარჩევნო უბნები ბიულეტენებზე მეტი ხმების რაოდენობით (%)',
:name_abbrv => 'ბიულეტენებზე მეტი ხმები (%)', :description => 'საარჩევნო უბნები ბიულეტენებზე მეტი ხმების რაოდენობით (%)')
end
# precincts with More Votes Than Ballots (#)
exists = CoreIndicatorTranslation.where(:locale => 'en', :name => 'Precincts with More Votes Than Ballots (#)')
if exists.present?
prec_missing_num = CoreIndicator.find_by_id(exists.first.core_indicator_id)
else
prec_missing_num = CoreIndicator.create(:indicator_type_id => 1)
prec_missing_num.core_indicator_translations.create(:locale => 'en', :name => 'Precincts with More Votes Than Ballots (#)',
:name_abbrv => 'More Votes Than Ballots (#)', :description => 'Precincts with More Votes Than Ballots (#)')
prec_missing_num.core_indicator_translations.create(:locale => 'ka', :name => 'საარჩევნო უბნები ბიულეტენებზე მეტი ხმების რაოდენობით (#)',
:name_abbrv => 'ბიულეტენებზე მეტი ხმები (#)', :description => 'საარჩევნო უბნები ბიულეტენებზე მეტი ხმების რაოდენობით (#)')
end
# avg # of More Votes Than Ballots
exists = CoreIndicatorTranslation.where(:locale => 'en', :name => 'More Votes Than Ballots (Average)')
if exists.present?
avg = CoreIndicator.find_by_id(exists.first.core_indicator_id)
else
avg = CoreIndicator.create(:indicator_type_id => 1)
avg.core_indicator_translations.create(:locale => 'en', :name => 'More Votes Than Ballots (Average)',
:name_abbrv => 'More Votes Than Ballots (Avg)', :description => 'More Votes Than Ballots (Average)')
avg.core_indicator_translations.create(:locale => 'ka', :name => 'ბიულეტენებზე მეტი ხმები (საშუალო)',
:name_abbrv => 'ბიულეტენებზე მეტი ხმები (საშუალო)', :description => 'ბიულეტენებზე მეტი ხმები (საშუალო)')
end
# More Votes Than Ballots (#)
exists = CoreIndicatorTranslation.where(:locale => 'en', :name => 'More Votes Than Ballots (#)')
if exists.present?
missing = CoreIndicator.find_by_id(exists.first.core_indicator_id)
else
missing = CoreIndicator.create(:indicator_type_id => 1)
missing.core_indicator_translations.create(:locale => 'en', :name => 'More Votes Than Ballots (#)',
:name_abbrv => 'More Votes Than Ballots (#)', :description => 'More Votes Than Ballots (#)')
missing.core_indicator_translations.create(:locale => 'ka', :name => 'ბიულეტენებზე მეტი ხმები (#)',
:name_abbrv => 'ბიულეტენებზე მეტი ხმები (#)', :description => 'ბიულეტენებზე მეტი ხმები (#)')
end
events.each do |event|
# add if not exists
if EventIndicatorRelationship.where(:event_id => event.id, :core_indicator_id => prec_missing_perc.id).blank? &&
EventIndicatorRelationship.where(:event_id => event.id, :core_indicator_id => missing.id).blank?
##########################
# create relationships
# - non-precinct relationship
EventIndicatorRelationship.create(:event_id => event.id, :core_indicator_id => prec_missing_perc.id, :related_core_indicator_id => prec_missing_num.id,
:sort_order => 1, :visible => true, :has_openlayers_rule_value => false)
EventIndicatorRelationship.create(:event_id => event.id, :core_indicator_id => prec_missing_perc.id, :related_core_indicator_id => prec_missing_perc.id,
:sort_order => 2, :visible => true, :has_openlayers_rule_value => true)
EventIndicatorRelationship.create(:event_id => event.id, :core_indicator_id => prec_missing_perc.id, :related_core_indicator_id => avg.id,
:sort_order => 3, :visible => true, :has_openlayers_rule_value => false)
EventIndicatorRelationship.create(:event_id => event.id, :core_indicator_id => prec_missing_perc.id, :related_core_indicator_id => total_ind_id,
:sort_order => 4, :visible => true, :has_openlayers_rule_value => false)
# - precinct relationship
EventIndicatorRelationship.create(:event_id => event.id, :core_indicator_id => missing.id, :related_core_indicator_id => missing.id,
:sort_order => 1, :visible => true, :has_openlayers_rule_value => true)
EventIndicatorRelationship.create(:event_id => event.id, :core_indicator_id => missing.id, :related_core_indicator_id => total_ind_id,
:sort_order => 4, :visible => true, :has_openlayers_rule_value => false)
end
# for each event, clone indicators/scales for new indicators
puts "=================="
if cores.present? && cores.length == old_core_names.length
puts "cloning indicators2 for event #{event.id}"
cores.each_with_index do |core, i|
puts "- cloning core #{core.id}"
new_core_id = nil
case i
when 0
new_core_id = prec_missing_perc.id
when 1
new_core_id = prec_missing_num.id
when 2
new_core_id = avg.id
when 3
new_core_id = missing.id
end
puts "- new core id = #{new_core_id}; cloning"
Indicator.clone_from_core_indicator(event.id, core.id, event.id, new_core_id) if new_core_id.present?
if i == 3
puts "-- this is the last core ind, fixing stuff"
# clone process does not work when ind has parent id that is not itself
# - manual fix for precincts (%) -> number
fix_inds = Indicator.where(:event_id => event.id, :core_indicator_id => prec_missing_perc.id, :shape_type_id => 3)
if fix_inds.present?
puts "-- found ind for prec missing % at district"
Indicator.where(:event_id => event.id, :core_indicator_id => new_core_id).each do |fix_ind|
puts "--- fixing parent id from #{fix_ind.parent_id} to #{fix_inds.first.id}"
fix_ind.parent_id = fix_inds.first.id
fix_ind.save
# the old validation errors scale for number of validation errors (at precinct level)
# had scale of '<0'
# this was cloned for the new indicators, but is no longer needed
fix_scale_ids = fix_ind.indicator_scales.map{|x| x.id}
if fix_scale_ids.present?
puts "--- removing '<0' scale"
matches = IndicatorScaleTranslation.select('indicator_scale_id').where(:indicator_scale_id => fix_scale_ids, :name => '<0')
IndicatorScale.where(:id => matches.map{|x| x.indicator_scale_id}.uniq).destroy_all if matches.present?
end
end
end
end
puts "- finished cloning"
end
end
end
end
end
end
def down
ind_names = ['Precincts with More Ballots Than Votes (%)', 'Precincts with More Ballots Than Votes (#)', 'More Ballots Than Votes (Average)', 'More Ballots Than Votes (#)', 'Average Number of More Ballots Than Votes', 'Number of More Ballots Than Votes', 'Precincts with More Votes Than Ballots (%)', 'Precincts with More Votes Than Ballots (#)', 'More Votes Than Ballots (Average)', 'More Votes Than Ballots (#)', 'Average Number of More Votes Than Ballots', 'Number of More Votes Than Ballots']
inds = CoreIndicatorTranslation.where(:name => ind_names, :locale => 'en')
if inds.present?
CoreIndicator.transaction do
CoreIndicator.where(:id => inds.map{|x| x.core_indicator_id}).destroy_all
end
end
end
end
| 59.867797 | 500 | 0.608686 |
f76d5318d203fc42cc7307094f6f4ef79658498f | 1,105 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'milia/version'
Gem::Specification.new do |spec|
spec.name = "milia"
spec.version = Milia::VERSION
spec.authors = ["daudi amani"]
spec.email = ["[email protected]"]
spec.description = %q{Multi-tenanting gem for hosted Rails/Ruby/devise applications}
spec.summary = %q{Transparent multi-tenanting for hosted rails/ruby/devise web applications}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency 'rails', '~> 4.2'
spec.add_dependency 'devise', '~> 3.4'
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake"
spec.add_development_dependency "sqlite3"
spec.add_development_dependency "shoulda"
spec.add_development_dependency "turn"
end
| 36.833333 | 100 | 0.677828 |
5d251472a145b5e6d70e42d41aa0c301290145aa | 119 | class AddUserIdColumn < ActiveRecord::Migration[5.0]
def change
add_column :images, :user_id, :integer
end
end
| 19.833333 | 52 | 0.739496 |
f739c0e258b42c11ded1dc823422e7ad40d0f2f0 | 6,801 | require File.expand_path(File.dirname(__FILE__) + "/../spec_helper")
describe "waiting tasks" do
before(:each) do
WorkerQueue::WorkerQueueItem.destroy_all
@item = WorkerQueue::WorkerQueueItem.new
@worker_queue = []
1.upto(10) do |number|
@item2 = @item.clone
@item2.task_name = number.to_s
@item2.task_group = 'some_group'
@item2.status = WorkerQueue::WorkerQueueItem::STATUS_WAITING
@item2.class_name = 'WorkerTester'
@item2.method_name = 'process'
@item2.argument_hash = {:aap => :noot}
@item2.data = '123456789'
@item2.save
@worker_queue << @item2
end
end
it "should not crash on an empty set" do
WorkerQueue::WorkerQueueItem.destroy_all
WorkerQueue.available_tasks([]).should eql([])
end
it "should find all waiting tasks" do
WorkerQueue.available_tasks.length.should eql(10)
end
it "should filter out all running tasks of the same type" do
@worker_queue[0].task_group = 'other_group'
@worker_queue[1].task_group = 'other_group'
@worker_queue[1].status = WorkerQueue::WorkerQueueItem::STATUS_RUNNING
@worker_queue[0].save
@worker_queue[1].save
WorkerQueue.available_tasks.length.should eql(8)
end
it "should filter out all running tasks is they are all the same type" do
@worker_queue[0].status = WorkerQueue::WorkerQueueItem::STATUS_RUNNING
@worker_queue[0].save
WorkerQueue.available_tasks.length.should eql(0)
end
it "should order all waiting tasks in the correct order" do
@worker_queue[0].task_group = 'other_group'
@worker_queue[1].task_group = 'other_group'
@worker_queue[1].status = WorkerQueue::WorkerQueueItem::STATUS_WAITING
queue = WorkerQueue.available_tasks
1.upto(6) do |number|
queue[number].id.should > queue[number-1].id
end
end
it "for all without specified type, should always be available" do
@worker_queue.each { |item| item.update_attribute( :task_group, '' ) }
@worker_queue[0].status = WorkerQueue::WorkerQueueItem::STATUS_RUNNING
@worker_queue[0].save
WorkerQueue.available_tasks.length.should eql(9)
end
end
describe "work" do
before(:each) do
WorkerQueue::WorkerQueueItem.destroy_all
@item = WorkerQueue::WorkerQueueItem.new
@worker_queue = []
1.upto(10) do |number|
@item2 = @item.clone
@item2.task_name = number.to_s
@item2.task_group = 'some_group'
@item2.status = WorkerQueue::WorkerQueueItem::STATUS_WAITING
@item2.class_name = 'WorkerQueue::WorkerTester'
@item2.method_name = 'test'
@item2.argument_hash = {:aap => :noot}
@item2.data = '123456789'
@item2.save
@worker_queue << @item2
end
end
it "should perform all tasks" do
WorkerQueue::WorkerTester.should_receive(:test).with({:aap => :noot, :data => '123456789'}).exactly(10).times.and_return(true)
WorkerQueue.work
end
it "should flag all tasks as completed" do
WorkerQueue.work
tasks = WorkerQueue::WorkerQueueItem.find(:all)
tasks.length.should eql(10)
tasks.each do |task|
task.should be_completed
task.should_not be_running
end
end
it "should handle no method errors" do
@worker_queue[0].method_name = 'does_not_exist'
@worker_queue[0].save
WorkerQueue.work
tasks = WorkerQueue::WorkerQueueItem.errors
tasks.length.should eql(1)
tasks[0].error_message.should_not be_nil
end
it "should handle no class errors" do
@worker_queue[0].class_name = 'does_not_exist'
@worker_queue[0].save
WorkerQueue.work
tasks = WorkerQueue::WorkerQueueItem.errors
tasks.length.should eql(1)
tasks[0].error_message.should_not be_nil
end
it "should handle return false from method call and stop the group execution" do
WorkerQueue::WorkerTester.stub!(:test).and_return(false)
WorkerQueue.work
tasks = WorkerQueue::WorkerQueueItem.errors
tasks.length.should eql(1)
tasks[0].error_message.should_not be_nil
tasks = WorkerQueue::WorkerQueueItem.waiting
tasks.length.should eql(9)
# No remainder of the group should be executable.
WorkerQueue.available_tasks.length.should eql(0)
end
end
describe "work?" do
before(:each) do
WorkerQueue::WorkerQueueItem.destroy_all
@item = WorkerQueue::WorkerQueueItem.new
@item.task_name = '1234567890'
@item.task_group = 'some_group'
@item.status = WorkerQueue::WorkerQueueItem::STATUS_WAITING
@item.class_name = 'WorkerQueue::WorkerTester'
@item.method_name = 'test'
@item.argument_hash = {:aap => :noot}
@item.data = '1234567890'
@item.save!
end
it "should see work" do
WorkerQueue.should be_work
end
it "should not see work if an item has an error status" do
@item.status = WorkerQueue::WorkerQueueItem::STATUS_ERROR
@item.save
WorkerQueue.should_not be_work
end
it "should not see work if item is running" do
@item.status = WorkerQueue::WorkerQueueItem::STATUS_RUNNING
@item.save
WorkerQueue.should_not be_work
end
it "should not see work if item is running and item of the same group is waiting" do
@item2 = @item.clone
@item2.save
@item.status = WorkerQueue::WorkerQueueItem::STATUS_RUNNING
@item.save
WorkerQueue.should_not be_work
end
end
describe "When handling racing conditions" do
before(:each) do
WorkerQueue::WorkerQueueItem.destroy_all
@item = WorkerQueue::WorkerQueueItem.new
@item.task_name = '1234567890'
@item.task_group = 'some_group'
@item.status = WorkerQueue::WorkerQueueItem::STATUS_RUNNING
@item.class_name = 'WorkerQueue::WorkerTester'
@item.method_name = 'test'
@item.argument_hash = {:aap => :noot}
@item.data = '1234567890'
@item.lock_version = 1
@item.save!
end
it "should not execute an executing object" do
WorkerQueue::WorkerTester.should_receive(:test).exactly(0).times
@item.lock_version = 0
@item.status = WorkerQueue::WorkerQueueItem::STATUS_WAITING
WorkerQueue.work([@item])
@item.reload
@item.status.should eql(WorkerQueue::WorkerQueueItem::STATUS_RUNNING)
end
it "should not execute when the object when it is stale" do
WorkerQueue::WorkerTester.should_receive(:test).exactly(0).times
@item.lock_version = 0
@item.status = WorkerQueue::WorkerQueueItem::STATUS_WAITING
@item.stub!(:executable?).and_return(true)
WorkerQueue.work([@item])
@item.reload
@item.status.should eql(WorkerQueue::WorkerQueueItem::STATUS_RUNNING)
end
end
| 28.57563 | 130 | 0.679312 |
f8474a659b204571bfa6e064fe3b71d756e85301 | 1,267 | =begin
#Datadog API V2 Collection
#Collection of all Datadog Public endpoints.
The version of the OpenAPI document: 1.0
Contact: [email protected]
Generated by: https://openapi-generator.tech
Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
This product includes software developed at Datadog (https://www.datadoghq.com/).
Copyright 2020-Present Datadog, Inc.
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for DatadogAPIClient::V2::DashboardListAddItemsResponse
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe DatadogAPIClient::V2::DashboardListAddItemsResponse do
let(:instance) { DatadogAPIClient::V2::DashboardListAddItemsResponse.new }
describe 'test an instance of DashboardListAddItemsResponse' do
it 'should create an instance of DashboardListAddItemsResponse' do
expect(instance).to be_instance_of(DatadogAPIClient::V2::DashboardListAddItemsResponse)
end
end
describe 'test attribute "added_dashboards_to_list"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 33.342105 | 107 | 0.789266 |
1daea18d9fd70d645c80c7b053e2bc4da1ef5e51 | 3,423 | require_relative 'parameter'
module RSpec
module ApiDoc
module DSL
def metadata_macro(name)
define_method(name) do |value = nil|
if value
let(name) { value.dup }
metadata[name.to_sym] = value
end
metadata[name.to_sym]
end
end
module_function :metadata_macro
# Use the metadata to store these so they are available in nested groups
# and examples
metadata_macro :resource
def endpoint_macro(name)
define_method(name) do |value = nil|
set_endpoint(name, value)
metadata[name.to_sym]
end
end
module_function :endpoint_macro
endpoint_macro :resource_endpoint
endpoint_macro :collection_endpoint
def use_host(host)
uri = URI.parse(host)
host = uri.host
protocol = uri.scheme || "https"
around do |ex|
org_host = default_url_options[:host]
org_protocol = default_url_options[:protocol]
default_url_options[:host] = host
default_url_options[:protocol] = protocol
ex.run
# Rails dislikes an explicit `nil` as the host, so check first
if org_host
default_url_options[:host] = org_host
else
default_url_options.delete(:host)
end
if org_protocol
default_url_options[:protocol] = org_protocol
else
default_url_options.delete(:protocol)
end
end
end
def example_explanation(text = nil)
@_example_explanation = text.strip_heredoc if text
@_example_explanation
end
def explanation(text)
explanation_parts << text.strip_heredoc.chomp
end
def paragraph(text)
explanation_parts << text.squish.chomp
end
def include_section(name)
# Easiest if for this to simply be an include shared_context alias
# which we would need to create a custom macro alias for
# `shared_context`. However, this would require the writer to
# understand our "section" nesting formatting :-/
include_context(name)
end
def header(name, static_value = nil)
metadata['include_headers'] ||= {
'Accept' => nil,
'Content-Type' => nil,
}
metadata['include_headers'][name] = static_value
end
# This sets a class variable which is distict per group; it is not
# inherited by nested groups
def explanation_parts
@explanation_parts ||= []
end
def parameter(name, description, type: :string, required: false)
parameters << Parameter.new(name, description, type, required)
end
def parameters
@parameters ||= []
end
def parameters_info(value)
@custom_parameters_info = value
end
def custom_parameters_info
@custom_parameters_info
end
attr_accessor :response, :request, :include_headers
private
def set_endpoint(key, value)
return if value.nil?
# Set the full URL when customized so the controller has it
let(key) {
if default_url_options[:host]
"#{default_url_options[:host]}#{value}"
else
value.dup
end
}
metadata[key.to_sym] = value
end
end
end
end
| 27.166667 | 78 | 0.600058 |
39190077638021b4870afeb08e6474adf11d5739 | 5,166 | #
# Be sure to run `pod spec lint BLAPIManagers.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "SignModule"
s.version = "0.0.1"
s.summary = "SignModule."
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
this is SignModule
DESC
s.homepage = "https://github.com/ModulizationSwift/SignModule"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
# s.license = "MIT (example)"
s.license = { :type => "MIT", :file => "FILE_LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "CasaTaloyum" => "[email protected]" }
# Or just: s.author = "CasaTaloyum"
# s.authors = { "CasaTaloyum" => "[email protected]" }
# s.social_media_url = "http://twitter.com/CasaTaloyum"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
# s.platform = :ios
s.platform = :ios, "8.0"
# When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# s.watchos.deployment_target = "2.0"
# s.tvos.deployment_target = "9.0"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
#
s.source = { :git => "https://github.com/ModulizationSwift/SignModule.git", :tag => s.version.to_s }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any swift, h, m, mm, c & cpp files.
# For header files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
s.source_files = "SignModule/SignModule/**/*.{h,m,swift}"
# s.exclude_files = "Classes/Exclude"
# s.public_header_files = "Classes/**/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
# s.framework = "SomeFramework"
# s.frameworks = "SomeFramework", "AnotherFramework"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "BLNetworking"
# s.dependency "BLAPIManagers"
# s.dependency "UIKit"
end
| 36.638298 | 108 | 0.595045 |
62ff7fcafea634101b2364c9c0e3e2bae3f06ad0 | 5,787 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::Ci::PipelineObjectHierarchy do
include Ci::SourcePipelineHelpers
let_it_be(:project) { create(:project, :repository) }
let_it_be(:ancestor) { create(:ci_pipeline, project: project) }
let_it_be(:parent) { create(:ci_pipeline, project: project) }
let_it_be(:child) { create(:ci_pipeline, project: project) }
let_it_be(:cousin_parent) { create(:ci_pipeline, project: project) }
let_it_be(:cousin) { create(:ci_pipeline, project: project) }
let_it_be(:triggered_pipeline) { create(:ci_pipeline) }
let_it_be(:triggered_child_pipeline) { create(:ci_pipeline) }
before_all do
create_source_pipeline(ancestor, parent)
create_source_pipeline(ancestor, cousin_parent)
create_source_pipeline(parent, child)
create_source_pipeline(cousin_parent, cousin)
create_source_pipeline(child, triggered_pipeline)
create_source_pipeline(triggered_pipeline, triggered_child_pipeline)
end
describe '#base_and_ancestors' do
it 'includes the base and its ancestors' do
relation = described_class.new(::Ci::Pipeline.where(id: parent.id),
options: { project_condition: :same }).base_and_ancestors
expect(relation).to contain_exactly(ancestor, parent)
end
it 'can find ancestors upto a certain level' do
relation = described_class.new(::Ci::Pipeline.where(id: child.id),
options: { project_condition: :same }).base_and_ancestors(upto: ancestor.id)
expect(relation).to contain_exactly(parent, child)
end
describe 'hierarchy_order option' do
let(:relation) do
described_class.new(::Ci::Pipeline.where(id: child.id),
options: { project_condition: :same }).base_and_ancestors(hierarchy_order: hierarchy_order)
end
context ':asc' do
let(:hierarchy_order) { :asc }
it 'orders by child to ancestor' do
expect(relation).to eq([child, parent, ancestor])
end
end
context ':desc' do
let(:hierarchy_order) { :desc }
it 'orders by ancestor to child' do
expect(relation).to eq([ancestor, parent, child])
end
end
end
end
describe '#base_and_descendants' do
it 'includes the base and its descendants' do
relation = described_class.new(::Ci::Pipeline.where(id: parent.id),
options: { project_condition: :same }).base_and_descendants
expect(relation).to contain_exactly(parent, child)
end
context 'when project_condition: :different' do
it "includes the base and other project pipelines" do
relation = described_class.new(::Ci::Pipeline.where(id: child.id),
options: { project_condition: :different }).base_and_descendants
expect(relation).to contain_exactly(child, triggered_pipeline, triggered_child_pipeline)
end
end
context 'when project_condition: nil' do
it "includes the base and its descendants with other project pipeline" do
relation = described_class.new(::Ci::Pipeline.where(id: parent.id)).base_and_descendants
expect(relation).to contain_exactly(parent, child, triggered_pipeline, triggered_child_pipeline)
end
end
context 'when with_depth is true' do
let(:relation) do
described_class.new(::Ci::Pipeline.where(id: ancestor.id),
options: { project_condition: :same }).base_and_descendants(with_depth: true)
end
it 'includes depth in the results' do
object_depths = {
ancestor.id => 1,
parent.id => 2,
cousin_parent.id => 2,
child.id => 3,
cousin.id => 3
}
relation.each do |object|
expect(object.depth).to eq(object_depths[object.id])
end
end
end
end
describe '#all_objects' do
context 'when passing ancestors_base' do
let(:options) { { project_condition: project_condition } }
let(:ancestors_base) { ::Ci::Pipeline.where(id: child.id) }
subject(:relation) { described_class.new(ancestors_base, options: options).all_objects }
context 'when project_condition: :same' do
let(:project_condition) { :same }
it "includes its ancestors and descendants" do
expect(relation).to contain_exactly(ancestor, parent, child)
end
end
context 'when project_condition: :different' do
let(:project_condition) { :different }
it "includes the base and other project pipelines" do
expect(relation).to contain_exactly(child, triggered_pipeline, triggered_child_pipeline)
end
end
end
context 'when passing ancestors_base and descendants_base' do
let(:options) { { project_condition: project_condition } }
let(:ancestors_base) { ::Ci::Pipeline.where(id: child.id) }
let(:descendants_base) { described_class.new(::Ci::Pipeline.where(id: child.id), options: options).base_and_ancestors }
subject(:relation) { described_class.new(ancestors_base, descendants_base, options: options).all_objects }
context 'when project_condition: :same' do
let(:project_condition) { :same }
it 'returns all family tree' do
expect(relation).to contain_exactly(ancestor, parent, cousin_parent, child, cousin)
end
end
context 'when project_condition: :different' do
let(:project_condition) { :different }
it "includes the base and other project pipelines" do
expect(relation).to contain_exactly(child, triggered_pipeline, triggered_child_pipeline)
end
end
end
end
end
| 35.944099 | 125 | 0.663729 |
21efd7066a212c1033419ec8cf986e33e4313275 | 240 | require 'test_helper'
class PagesControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
end
test "should get show" do
get :show
assert_response :success
end
end
| 16 | 54 | 0.720833 |
61cbbd137c568c5dd7dd5a6159143bffec4f1617 | 260 | module Humble
class IdentityMap
def initialize(items = {})
@items = items
end
def fetch(key, &block)
if @items.key?(key)
@items[key]
else
@items[key] = block.call
@items[key]
end
end
end
end
| 15.294118 | 32 | 0.526923 |
b9f297d781205dc0ccdb6291267fbb0a3927f135 | 3,438 | class Libgweather < Formula
desc "GNOME library for weather, locations and timezones"
homepage "https://wiki.gnome.org/Projects/LibGWeather"
url "https://download.gnome.org/sources/libgweather/3.36/libgweather-3.36.1.tar.xz"
sha256 "de2709f0ee233b20116d5fa9861d406071798c4aa37830ca25f5ef2c0083e450"
revision 2
bottle do
sha256 arm64_big_sur: "ea89b381f0cb180a44a1ab0d106693a8874fb785221cc6840092da07ed4960ec"
sha256 big_sur: "fbed23f116de31b6c729671e719bb88246ed66007f779fef5289be3519de3223"
sha256 catalina: "46c6e704f4d42d0032888a87cd2d0ce2fd2ce0a9b8027123976857d242c1b0f3"
sha256 mojave: "b8db1057908c9723c708b919330b9a58cdbdb9e6a6c7b053242fb8c965171eff"
sha256 high_sierra: "267bff5a8951012a4df193baed3816552028de9c44ae26d977e932a75a655d88"
end
depends_on "gobject-introspection" => :build
depends_on "meson" => :build
depends_on "ninja" => :build
depends_on "pkg-config" => :build
depends_on "geocode-glib"
depends_on "gtk+3"
depends_on "libsoup"
depends_on "glibc" unless OS.mac?
def install
# Needed by intltool (xml::parser)
ENV.prepend_path "PERL5LIB", "#{Formula["intltool"].libexec}/lib/perl5" unless OS.mac?
ENV["DESTDIR"] = "/"
mkdir "build" do
system "meson", *std_meson_args, ".."
system "ninja", "-v"
system "ninja", "install", "-v"
end
end
def post_install
system "#{Formula["glib"].opt_bin}/glib-compile-schemas", "#{HOMEBREW_PREFIX}/share/glib-2.0/schemas"
end
test do
(testpath/"test.c").write <<~EOS
#include <libgweather/gweather.h>
int main(int argc, char *argv[]) {
GType type = gweather_info_get_type();
return 0;
}
EOS
ENV.libxml2
atk = Formula["atk"]
cairo = Formula["cairo"]
fontconfig = Formula["fontconfig"]
freetype = Formula["freetype"]
gdk_pixbuf = Formula["gdk-pixbuf"]
gettext = Formula["gettext"]
glib = Formula["glib"]
gtkx3 = Formula["gtk+3"]
harfbuzz = Formula["harfbuzz"]
libepoxy = Formula["libepoxy"]
libpng = Formula["libpng"]
libsoup = Formula["libsoup"]
pango = Formula["pango"]
pixman = Formula["pixman"]
flags = %W[
-I#{atk.opt_include}/atk-1.0
-I#{cairo.opt_include}/cairo
-I#{fontconfig.opt_include}
-I#{freetype.opt_include}/freetype2
-I#{gdk_pixbuf.opt_include}/gdk-pixbuf-2.0
-I#{gettext.opt_include}
-I#{glib.opt_include}/gio-unix-2.0/
-I#{glib.opt_include}/glib-2.0
-I#{glib.opt_lib}/glib-2.0/include
-I#{gtkx3.opt_include}/gtk-3.0
-I#{harfbuzz.opt_include}/harfbuzz
-I#{include}/libgweather-3.0
-I#{libepoxy.opt_include}
-I#{libpng.opt_include}/libpng16
-I#{libsoup.opt_include}/libsoup-2.4
-I#{pango.opt_include}/pango-1.0
-I#{pixman.opt_include}/pixman-1
-D_REENTRANT
-L#{atk.opt_lib}
-L#{cairo.opt_lib}
-L#{gdk_pixbuf.opt_lib}
-L#{gettext.opt_lib}
-L#{glib.opt_lib}
-L#{gtkx3.opt_lib}
-L#{lib}
-L#{pango.opt_lib}
-latk-1.0
-lcairo
-lcairo-gobject
-lgdk-3
-lgdk_pixbuf-2.0
-lgio-2.0
-lglib-2.0
-lgobject-2.0
-lgtk-3
-lgweather-3
-lpango-1.0
-lpangocairo-1.0
]
flags << "-lintl" if OS.mac?
system ENV.cc, "-DGWEATHER_I_KNOW_THIS_IS_UNSTABLE=1", "test.c", "-o", "test", *flags
system "./test"
end
end
| 30.972973 | 105 | 0.653287 |
87cc9e00605947f57efe1cc835db4f208d2dc9c6 | 1,046 | require File.expand_path("../../Abstract/abstract-php-extension", __FILE__)
class Php53Timezonedb < AbstractPhp53Extension
init
homepage "https://pecl.php.net/package/timezonedb"
url "https://pecl.php.net/get/timezonedb-2014.7.tgz"
sha256 "76e1fba9ea263621810a220ffe280c8ca227a12fd497c9ce430537fbd13357a7"
head "https://svn.php.net/repository/pecl/timezonedb/trunk/"
bottle do
cellar :any_skip_relocation
sha256 "bfef1a882dcb239af54f732ed222b03bde93b604e18c66bf2ab65511225c6175" => :el_capitan
sha256 "940a91a621c42be5c3a4eab1d56a7a54a6c27d1f5a18762c51413457bcea9423" => :yosemite
sha256 "f3f317b41bd608998a48f6d5875ff33fc023643e11587300374503ad425dd66b" => :mavericks
end
def install
Dir.chdir "timezonedb-#{version}" unless build.head?
ENV.universal_binary if build.universal?
safe_phpize
system "./configure", "--prefix=#{prefix}",
phpconfig
system "make"
prefix.install "modules/timezonedb.so"
write_config_file if build.with? "config-file"
end
end
| 34.866667 | 92 | 0.756214 |
260daa5346a59484eed8781324460748d58814a1 | 604 | # Given a nonnegative integer, return a hash whose keys are all the odd nonnegative integers up to it
# and each key's value is an array containing all the even non negative integers up to it.
#
# Examples:
# staircase 1 # => {1 => []}
# staircase 2 # => {1 => []}
# staircase 3 # => {1 => [], 3 => [2]}
# staircase 4 # => {1 => [], 3 => [2]}
# staircase 5 # => {1 => [], 3 => [2], 5 =>[2, 4]}
def staircase n
odd = [*1..n].select(&:odd?)
even = [*1..n].select(&:even?)
arr = []
((n/2.0).ceil).times do |i|
arr << odd[i]
arr << even.select{|x| x < odd[i]}
end
Hash[*arr]
end
| 25.166667 | 101 | 0.534768 |
0173d0da047b72efc9fc4bd19b7fdc8ae349b13c | 4,194 | # You can have Apartment route to the appropriate Tenant by adding some Rack middleware.
# Apartment can support many different "Elevators" that can take care of this routing to your data.
# Require whichever Elevator you're using below or none if you have a custom one.
#
# require 'apartment/elevators/generic'
# require 'apartment/elevators/domain'
require 'apartment/elevators/subdomain'
# require 'apartment/elevators/first_subdomain'
# require 'apartment/elevators/host'
#
# Apartment Configuration
#
Apartment.configure do |config|
# Add any models that you do not want to be multi-tenanted, but remain in the global (public) namespace.
# A typical example would be a Customer or Tenant model that stores each Tenant's information.
#
config.excluded_models = %w{ Tenant }
# In order to migrate all of your Tenants you need to provide a list of Tenant names to Apartment.
# You can make this dynamic by providing a Proc object to be called on migrations.
# This object should yield either:
# - an array of strings representing each Tenant name.
# - a hash which keys are tenant names, and values custom db config (must contain all key/values required in database.yml)
#
# config.tenant_names = lambda{ Customer.pluck(:tenant_name) }
# config.tenant_names = ['tenant1', 'tenant2']
# config.tenant_names = {
# 'tenant1' => {
# adapter: 'postgresql',
# host: 'some_server',
# port: 5555,
# database: 'postgres' # this is not the name of the tenant's db
# # but the name of the database to connect to before creating the tenant's db
# # mandatory in postgresql
# },
# 'tenant2' => {
# adapter: 'postgresql',
# database: 'postgres' # this is not the name of the tenant's db
# # but the name of the database to connect to before creating the tenant's db
# # mandatory in postgresql
# }
# }
# config.tenant_names = lambda do
# Tenant.all.each_with_object({}) do |tenant, hash|
# hash[tenant.name] = tenant.db_configuration
# end
# end
#
config.tenant_names = lambda { Tenant.pluck :name }
# PostgreSQL:
# Specifies whether to use PostgreSQL schemas or create a new database per Tenant.
#
# MySQL:
# Specifies whether to switch databases by using `use` statement or re-establish connection.
#
# The default behaviour is true.
#
# config.use_schemas = true
#
# ==> PostgreSQL only options
# Apartment can be forced to use raw SQL dumps instead of schema.rb for creating new schemas.
# Use this when you are using some extra features in PostgreSQL that can't be represented in
# schema.rb, like materialized views etc. (only applies with use_schemas set to true).
# (Note: this option doesn't use db/structure.sql, it creates SQL dump by executing pg_dump)
#
# config.use_sql = false
# There are cases where you might want some schemas to always be in your search_path
# e.g when using a PostgreSQL extension like hstore.
# Any schemas added here will be available along with your selected Tenant.
#
# config.persistent_schemas = %w{ hstore }
# <== PostgreSQL only options
#
# By default, and only when not using PostgreSQL schemas, Apartment will prepend the environment
# to the tenant name to ensure there is no conflict between your environments.
# This is mainly for the benefit of your development and test environments.
# Uncomment the line below if you want to disable this behaviour in production.
#
# config.prepend_environment = !Rails.env.production?
end
# Setup a custom Tenant switching middleware. The Proc should return the name of the Tenant that
# you want to switch to.
# Rails.application.config.middleware.use Apartment::Elevators::Generic, lambda { |request|
# request.host.split('.').first
# }
# Rails.application.config.middleware.use Apartment::Elevators::Domain
# Rails.application.config.middleware.use Apartment::Elevators::Subdomain
# Rails.application.config.middleware.use Apartment::Elevators::FirstSubdomain
# Rails.application.config.middleware.use Apartment::Elevators::Host
| 41.94 | 124 | 0.711254 |
1af71a0a09627f28b2c3f73a8b5de6366d8e9fca | 2,089 | ##########################################################################
# Copyright 2016 ThoughtWorks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##########################################################################
module ApiV3
module Shared
module Stages
class PluginConfigurationPropertyRepresenter < BaseRepresenter
alias_method :configuration_property, :represented
error_representer(
{
'encryptedValue' => 'encrypted_value',
'configurationValue' => 'configuration_value',
'configurationKey' => 'configuration_key'
}
)
property :key, exec_context: :decorator
property :value, skip_nil: true, exec_context: :decorator
property :encrypted_value, skip_nil: true, exec_context: :decorator
def value
configuration_property.getValue unless configuration_property.isSecure
end
def encrypted_value
configuration_property.getEncryptedValue if configuration_property.isSecure
end
def value=(val)
configuration_property.setConfigurationValue(ConfigurationValue.new(val))
end
def encrypted_value=(encrypted_val)
configuration_property.setEncryptedConfigurationValue(EncryptedConfigurationValue.new(encrypted_val))
end
def key
configuration_property.getConfigurationKey.getName
end
def key=(value)
configuration_property.setConfigurationKey(ConfigurationKey.new(value))
end
end
end
end
end | 34.816667 | 111 | 0.650551 |
edaf61be8ad0dbadc41b1dfc0cebea14652188c7 | 66 | # frozen_string_literal: true
module Que
Version = "1.0.0"
end
| 11 | 29 | 0.712121 |
2144468d9a63aba54c58c2838ec0ba7f203ca985 | 13,070 | require 'spec_helper'
describe 'PayPal', type: :feature, js: true do
let!(:country) { create(:country, name: 'United States', states_required: true) }
let!(:state) { create(:state, country: country) }
let!(:shipping_method) { create(:shipping_method) }
let!(:stock_location) { create(:stock_location) }
let!(:product) { create(:product, name: 'RoR Mug') }
let!(:zone) { create(:zone) }
let!(:store) { create(:store) }
before do
@gateway = Spree::Gateway::PayPalExpress.create!({
preferred_login: 'pp_api1.ryanbigg.com',
preferred_password: '1383066713',
preferred_signature: 'An5ns1Kso7MWUdW4ErQKJJJ4qi4-Ar-LpzhMJL0cu8TjM8Z2e1ykVg5B',
name: 'PayPal',
active: true
})
end
def switch_to_paypal_login
unless page.has_selector?('#login #email')
if page.has_css?('.changeLanguage')
wait_for { !page.has_css?('div#preloaderSpinner') }
find('.changeLanguage').click
find_all('a', text: 'English')[0].click
end
wait_for { page.has_link?(text: 'Log In') }
wait_for { !page.has_css?('div.spinWrap') }
click_link 'Log In'
end
end
def login_to_paypal
wait_for { page.has_text?('Pay with PayPal') }
fill_in 'email', with: '[email protected]'
fill_in 'password', with: 'thequickbrownfox'
click_button 'btnLogin'
end
def within_transaction_cart(container_class, expected_texts, unexpected_texts)
wait_for { page.has_css?('span#transactionCart') }
wait_for { !page.has_css?('div#preloaderSpinner') }
wait_for { !page.has_css?('div#spinner') }
find('span#transactionCart').click
within(container_class) do
expected_texts.each do |expected_text|
expect(page).to have_content(expected_text)
end
unexpected_texts.each do |unexpected_text|
expect(page).not_to have_content(unexpected_text)
end
end
find('#closeCart').click
end
def fill_in_billing
fill_in :order_bill_address_attributes_firstname, with: 'Test'
fill_in :order_bill_address_attributes_lastname, with: 'User'
fill_in :order_bill_address_attributes_address1, with: '1 User Lane'
fill_in :order_bill_address_attributes_city, with: 'Adamsville'
select 'United States', from: :order_bill_address_attributes_country_id
find('#order_bill_address_attributes_state_id').find(:xpath, 'option[2]').select_option
fill_in :order_bill_address_attributes_zipcode, with: '35005'
fill_in :order_bill_address_attributes_phone, with: '555-123-4567'
end
def fill_in_guest
fill_in :order_email, with: '[email protected]'
end
def click_pay_now_button
wait_for { page.has_button?('Pay Now') }
wait_for { page.has_css?('div#button') }
click_button 'Pay Now'
end
def click_paypal_button
wait_for { page.has_link?(id: 'paypal_button') }
find('#paypal_button').click
end
def stay_logged_in_for_faster_checkout
if page.has_text?('Stay logged in for faster checkout')
click_link 'Not now'
end
end
def expect_successfully_processed_order
wait_for { page.has_css?('div.alert-notice') }
order_number = Spree::Order.last.number
expect(page).to have_current_path("/orders/#{order_number}")
expect(page).to have_content('Your order has been processed successfully')
end
def proceed_through_address_stage
if Spree.version.to_f < 4.1
visit spree.root_path
click_link product.name
click_button 'Add To Cart'
sleep(1)
visit spree.cart_path
click_button 'Checkout'
fill_in_guest
fill_in_billing
else
add_to_cart(product)
visit spree.checkout_path
fill_in_guest
fill_in_address
end
end
it 'pays for an order successfully', js: true do
proceed_through_address_stage
click_button 'Save and Continue'
click_button 'Save and Continue'
click_paypal_button
switch_to_paypal_login
login_to_paypal
stay_logged_in_for_faster_checkout
click_pay_now_button
expect_successfully_processed_order
expect(Spree::Payment.last.source.transaction_id).not_to be_empty
end
context "with 'Sole' solution type" do
before do
@gateway.preferred_solution = 'Sole'
end
it 'passes user details to PayPal' do
proceed_through_address_stage
click_button 'Save and Continue'
click_button 'Save and Continue'
click_paypal_button
switch_to_paypal_login
login_to_paypal
stay_logged_in_for_faster_checkout
click_pay_now_button
if Spree.version.to_f < 4.1
wait_for { page.has_text?('555-123-4567') }
within('#order_summary') do
expect(page).to have_selector '[data-hook=order-bill-address] .fn', text: 'Test User'
expect(page).to have_selector '[data-hook=order-bill-address] .adr', text: '1 User Lane'
expect(page).to have_selector '[data-hook=order-bill-address] .adr .local .locality', text: 'Adamsville'
expect(page).to have_selector '[data-hook=order-bill-address] .adr .local .postal-code', text: '35005'
expect(page).to have_selector '[data-hook=order-bill-address] .tel', text: '555-123-4567'
end
else
wait_for { page.has_text?('Order Summary') }
expect(page).to have_content('Order placed successfully')
end
end
end
xit 'includes adjustments in PayPal summary' do
visit spree.root_path
click_link product.name
click_button 'Add To Cart'
order = Spree::Order.last
Spree::Adjustment.create!(label: '$5 off', adjustable: order, order: order, amount: -5)
Spree::Adjustment.create!(label: '$10 on', adjustable: order, order: order, amount: 10)
visit '/cart'
within('#cart_adjustments') do
expect(page).to have_content('$5 off')
expect(page).to have_content('$10 on')
end
click_button 'Checkout'
fill_in_guest
fill_in_billing
click_button 'Save and Continue'
click_button 'Save and Continue'
click_paypal_button
within_transaction_cart('.cartContainer', ['$5 off', '$10 on'], [])
switch_to_paypal_login
login_to_paypal
stay_logged_in_for_faster_checkout
within_transaction_cart('.cartContainer', ['$5 off', '$10 on'], [])
click_pay_now_button
wait_for { page.has_css?('[data-hook=order_details_adjustments]') }
within('[data-hook=order_details_adjustments]') do
expect(page).to have_content('$5 off')
expect(page).to have_content('$10 on')
end
end
context 'line item adjustments' do
let(:promotion) { Spree::Promotion.create(name: '10% off') }
before do
calculator = Spree::Calculator::FlatPercentItemTotal.new(preferred_flat_percent: 10)
action = Spree::Promotion::Actions::CreateItemAdjustments.create(calculator: calculator)
promotion.actions << action
end
it 'includes line item adjustments in PayPal summary' do
proceed_through_address_stage
click_button 'Save and Continue'
click_button 'Save and Continue'
click_paypal_button
within_transaction_cart('.cartContainer', ['10% off'], [])
switch_to_paypal_login
login_to_paypal
stay_logged_in_for_faster_checkout
click_pay_now_button
if Spree.version.to_f < 4.1
wait_for { page.has_css?('strong', text: '10% off') }
within('#price-adjustments') do
expect(page).to have_content('10% off')
end
else
wait_for { page.has_text?('Order Summary') }
expect(page).to have_content('PROMOTION')
end
end
end
# Regression test for #10
context 'will skip $0 items' do
let!(:product2) { create(:product, name: 'iPod') }
xit do
add_to_cart(product)
add_to_cart(product2)
# TODO: Is there a better way to find this current order?
script_content = page.all('body script', visible: false).last['innerHTML']
order_id = script_content.strip.split('\"')[1]
order = Spree::Order.find_by(number: order_id)
order.line_items.last.update_attribute(:price, 0)
proceed_through_address_stage
click_button 'Save and Continue'
click_button 'Save and Continue'
click_paypal_button
within_transaction_cart('.cartContainer', ['iPad'], ['iPod'])
wait_for { page.has_css?('.transactionDetails') }
switch_to_paypal_login
login_to_paypal
stay_logged_in_for_faster_checkout
within_transaction_cart('.transctionCartDetails', ['iPad'], ['iPod'])
click_pay_now_button
wait_for { page.has_text?('Order Summary') }
expect(page).to have_content('iPad')
expect(page).to have_content('iPod')
end
end
context 'can process an order with $0 item total' do
before do
# If we didn't do this then the order would be free and skip payment altogether
calculator = Spree::ShippingMethod.first.calculator
calculator.preferred_amount = 10
calculator.save
end
xit do
add_to_cart(product)
# TODO: Is there a better way to find this current order?
order = Spree::Order.last
Spree::Adjustment.create!(label: 'FREE iPad ZOMG!', adjustable: order, order: order, amount: -order.line_items.last.price)
click_button 'Checkout'
fill_in_guest
fill_in_billing
click_button 'Save and Continue'
click_button 'Save and Continue'
click_paypal_button
switch_to_paypal_login
login_to_paypal
stay_logged_in_for_faster_checkout
click_pay_now_button
wait_for { page.has_text?('FREE iPad ZOMG!') }
within('[data-hook=order_details_adjustments]') do
expect(page).to have_content('FREE iPad ZOMG!')
end
end
end
context 'cannot process a payment with invalid gateway details' do
before do
@gateway.preferred_login = nil
@gateway.save
end
specify do
proceed_through_address_stage
click_button 'Save and Continue'
click_button 'Save and Continue'
click_paypal_button
expect(page).to have_content('PayPal failed. Security header is not valid')
end
end
context 'can process an order with Tax included prices' do
let(:tax_rate) { create(:tax_rate, name: 'VAT Tax', amount: 0.1,
zone: Spree::Zone.first, included_in_price: true) }
let(:tax_category) { create(:tax_category, tax_rates: [tax_rate]) }
let(:product3) { create(:product, name: 'EU Charger', tax_category: tax_category) }
let(:tax_string) { 'VAT Tax 10.0%' }
# Regression test for #129
context 'on countries where the Tax is applied' do
before { Spree::Zone.first.update_attribute(:default_tax, true) }
end
end
context 'as an admin' do
context 'refunding payments' do
before do
stub_authorization!
visit spree.root_path
click_link 'iPad'
click_button 'Add To Cart'
click_button 'Checkout'
within('#guest_checkout') do
fill_in 'Email', with: '[email protected]'
click_button 'Continue'
end
fill_in_billing
click_button 'Save and Continue'
click_button 'Save and Continue'
click_paypal_button
switch_to_paypal_login
login_to_paypal
stay_logged_in_for_faster_checkout
click_pay_now_button
expect_successfully_processed_order
visit '/admin'
click_link Spree::Order.last.number
click_link 'Payments'
find('#content').find('table').first('a').click # this clicks the first payment
click_link 'Refund'
end
xit 'can refund payments fully' do
click_button 'Refund'
expect(page).to have_content('PayPal refund successful')
payment = Spree::Payment.last
paypal_checkout = payment.source.source
expect(paypal_checkout.refund_transaction_id).to_not be_blank
expect(paypal_checkout.refunded_at).to_not be_blank
expect(paypal_checkout.state).to eql('refunded')
expect(paypal_checkout.refund_type).to eql('Full')
# regression test for #82
within('table') do
expect(page).to have_content(payment.display_amount.to_html)
end
end
xit 'can refund payments partially' do
payment = Spree::Payment.last
# Take a dollar off, which should cause refund type to be...
fill_in 'Amount', with: payment.amount - 1
click_button 'Refund'
expect(page).to have_content('PayPal refund successful')
source = payment.source
expect(source.refund_transaction_id).to_not be_blank
expect(source.refunded_at).to_not be_blank
expect(source.state).to eql('refunded')
# ... a partial refund
expect(source.refund_type).to eql('Partial')
end
xit 'errors when given an invalid refund amount' do
fill_in 'Amount', with: 'lol'
click_button 'Refund'
expect(page).to have_content('PayPal refund unsuccessful (The partial refund amount is not valid)')
end
end
end
end
| 32.921914 | 128 | 0.679036 |
18156a85595570a7a0a7c8143d9f197bc27adfc3 | 180 | json.array!(@comments) do |comment|
json.extract! comment, :id, :text, :user_id, :comment_id, :comment_creation_date, :post_id
json.url comment_url(comment, format: :json)
end
| 36 | 92 | 0.738889 |
286c827b796feaca4fb4cd8fcde8d226d9df29dd | 1,744 | # frozen_string_literal: true
require 'ant/storage'
require_relative 'metatypes'
module Ant
module Nanoservice
# Takes a configuration and creates the metaclasess, repositories and
# factory from them.
# this can be attached to Grape API as helpers and provide a connection
# to the data layer.
class Schema
attr_reader :schema, :repositories
def initialize(schema)
build_schemas(schema['models'])
build_repositories(schema['models'], schema['repositories'])
end
private
def build_schemas(models)
@schema_configs = {}
@schema = models.each_with_object({}) do |(name, configs), obj|
columns = configs['fields']
@schema_configs[name] = configs
configs['configs']['schema_name'] = name
obj[name] = MetaTypes.build(name, columns, configs)
end
end
def build_repositories(models, repository_conf)
@repositories = models.each_with_object({}) do |(name, _), obj|
obj[name] = Ant::Storage::Repository
.from_config(@schema[name],
@schema_configs[name]['configs'],
repository_conf['default'])
end
end
public
def mount_grape_helpers(api, schema_name)
model = schema[schema_name]
repo = repositories[schema_name]
api.helpers do
define_method('factory') do
@factory ||= begin
factory = Ant::Storage::Factory.new(model)
factory.register(:default, :primary)
factory.register(:primary, repo)
factory
end
end
end
end
end
end
end
| 28.590164 | 75 | 0.583142 |
acf666549fad8206bf505d9e4497a82eaf4c2660 | 104 | module Bootstrap4DatetimePickerRails
module Rails
class Railtie < ::Rails::Railtie; end
end
end
| 17.333333 | 41 | 0.759615 |
5dcb311cb4af086494b6d66f2dfa6f18560526b6 | 5,861 | # encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
require 'spec_helper'
describe TwitterCldr::Parsers::NumberParser do
let(:separators) { ["\\.", ","] }
before(:each) do
@parser = described_class.new(:es)
end
describe "#group_separator" do
it "returns the correct group separator" do
expect(@parser.send(:group_separator)).to match_normalized("\\.")
end
end
describe "#decimal_separator" do
it "returns the correct decimal separator" do
expect(@parser.send(:decimal_separator)).to eq(",")
end
end
describe "#identify" do
it "properly identifies a numeric value" do
expect(@parser.send(:identify, "7841", *separators)).to eq({ value: "7841", type: :numeric })
end
it "properly identifies a decimal separator" do
expect(@parser.send(:identify, ",", *separators)).to eq({ value: ",", type: :decimal })
end
it "properly identifies a group separator" do
expect(@parser.send(:identify, ".", *separators)).to eq({ value: ".", type: :group })
end
it "returns nil if the text doesn't match a number or either separators" do
expect(@parser.send(:identify, "abc", *separators)).to eq({ value: "abc", type: nil })
end
end
describe "#tokenize" do
it "splits text by numericality and group/decimal separators" do
expect(@parser.send(:tokenize, "1,33.00", *separators)).to eq([
{ value: "1", type: :numeric },
{ value: ",", type: :decimal },
{ value: "33", type: :numeric },
{ value: ".", type: :group },
{ value: "00", type: :numeric }
])
end
it "returns an empty array for a non-numeric string" do
expect(@parser.send(:tokenize, "abc", *separators)).to be_empty
end
end
describe "#separators" do
it "returns all separators when strict mode is off" do
group, decimal = @parser.send(:separators, false)
expect(group).to eq('\.,\s')
expect(decimal).to eq('\.,\s')
end
it "returns only locale-specific separators when strict mode is on" do
group, decimal = @parser.send(:separators, true)
expect(group).to match_normalized("\\.")
expect(decimal).to eq(',')
end
end
describe "#punct_valid" do
it "correctly validates a number with no decimal" do
tokens = @parser.send(:tokenize, "1.337", *separators).reject { |t| t[:type] == :numeric }
expect(@parser.send(:punct_valid?, tokens)).to eq(true)
end
it "correctly validates a number with a decimal" do
tokens = @parser.send(:tokenize, "1.337,00", *separators).reject { |t| t[:type] == :numeric }
expect(@parser.send(:punct_valid?, tokens)).to eq(true)
end
it "reports on an invalid number when it has more than one decimal" do
tokens = @parser.send(:tokenize, "1,337,00", *separators).reject { |t| t[:type] == :numeric }
expect(@parser.send(:punct_valid?, tokens)).to eq(false)
end
end
describe "#is_numeric?" do
it "returns true if the text is numeric" do
expect(described_class.is_numeric?("4839", "")).to eq(true)
expect(described_class.is_numeric?("1", "")).to eq(true)
end
it "returns false if the text is not purely numeric" do
expect(described_class.is_numeric?("abc", "")).to eq(false)
expect(described_class.is_numeric?("123abc", "")).to eq(false)
end
it "returns false if the text is blank" do
expect(described_class.is_numeric?("", "")).to eq(false)
end
it "accepts the given characters as valid numerics" do
expect(described_class.is_numeric?("a123a", "a")).to eq(true)
expect(described_class.is_numeric?("1.234,56")).to eq(true) # default separator chars used here
end
end
describe "#valid?" do
it "correctly identifies a series of valid cases" do
["5", "5,0", "1.337", "1.337,0", "0,05", ",5", "1.337.000,00"].each do |num|
expect(@parser.valid?(num)).to eq(true)
end
end
it "correctly identifies a series of invalid cases" do
["12,0,0", "5,", "5."].each do |num|
expect(@parser.valid?(num)).to eq(false)
end
end
end
describe "#parse" do
it "correctly parses a series of valid numbers" do
cases = {
"5" => 5,
"5,0" => 5.0,
"1.337" => 1337,
"1.337,0" => 1337.0,
"0,05" => 0.05,
",5" => 0.5,
"1.337.000,00" => 1337000.0
}
cases.each do |text, expected|
expect(@parser.parse(text)).to eq(expected)
end
end
it "correctly raises an error when asked to parse invalid numbers" do
cases = ["12,0,0", "5,", "5."]
cases.each do |text|
expect { @parser.parse(text) }.to raise_error(TwitterCldr::Parsers::InvalidNumberError)
end
end
context "non-strict" do
it "succeeds in parsing even if inexact punctuation is used" do
expect(@parser.parse("5 100", strict: false)).to eq(5100)
end
end
end
describe "#try_parse" do
it "parses correctly with a valid number" do
expect(@parser.try_parse("1.234")).to eq(1234)
end
it "parses correctly with a valid number and yields to the given block" do
pre_result = nil
expect(@parser.try_parse("1.234") do |result|
pre_result = result
9
end).to eq(9)
expect(pre_result).to eq(1234)
end
it "falls back on the default value if the number is invalid" do
expect(@parser.try_parse("5,")).to be_nil
expect(@parser.try_parse("5,", 0)).to eq(0)
end
it "falls back on the block if the number is invalid" do
expect(@parser.try_parse("5,") { |result| 9 }).to eq(9)
end
it "doesn't catch anything but an InvalidNumberError" do
expect { @parser.try_parse(Object.new) }.to raise_error(NoMethodError)
end
end
end
| 31.510753 | 102 | 0.616618 |
18f0d171dc19f74425ea693eb952138ee2218a69 | 5,501 | # Copyright (c) 2018-2019 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: MIT
# DO NOT MODIFY. THIS CODE IS GENERATED. CHANGES WILL BE OVERWRITTEN.
# vcenter - VMware vCenter Server provides a centralized platform for managing your VMware vSphere environments
require 'date'
module VSphereAutomation
module VCenter
class VapiStdErrorsErrorError
attr_accessor :type
attr_accessor :value
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'type' => :'type',
:'value' => :'value'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'type' => :'String',
:'value' => :'VapiStdErrorsError'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.has_key?(:'type')
self.type = attributes[:'type']
end
if attributes.has_key?(:'value')
self.value = attributes[:'value']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
type == o.type &&
value == o.value
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[type, value].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN, :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = VSphereAutomation::VCenter.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
end
| 28.651042 | 111 | 0.614434 |
f8f20c1483878598bc66ac3d33171fd73c5536fe | 333 | module CloakPolicy
class Engine < ::Rails::Engine
isolate_namespace CloakPolicy
config.generators do |g|
g.template_engine :haml
end
initializer "cloak_policy.assets.precompile" do |app|
app.config.assets.precompile += %w( cloak_policy/application.js cloak_policy/application.css )
end
end
end
| 22.2 | 100 | 0.717718 |
180e46e9e6bdcddd4d2fd700edee3774fa9a31b7 | 424 | require "rails_helper"
describe Comment do
it { should belong_to(:user) }
it { should belong_to(:post) }
it "the factory can create a correct instance of the object" do
expect(FactoryGirl.build(:comment)).to be_valid
end
describe "validation" do
describe "it is invalid when" do
it { should validate_presence_of(:title) }
it { should validate_presence_of(:content) }
end
end
end | 24.941176 | 65 | 0.688679 |
bbe0b79b36fd7d973f1205c6c680ad0a994a293f | 885 | Pod::Spec.new do |s|
s.name = "RKCalendarLink"
s.version = "1.0"
s.summary = "CADisplayLink for calendar"
s.description = <<-DESC
Simple component for updating time labels at right time.
Notifies you whenever given calendar unit will change.
DESC
s.homepage = "https://github.com/samnung/RKCalendarLink"
s.license = 'MIT'
s.author = { "Roman Kříž" => "[email protected]" }
s.source = { :git => "https://github.com/samnung/RKCalendarLink.git", :tag => "v#{s.version}" }
s.social_media_url = 'https://twitter.com/roman__kriz'
s.ios.deployment_target = "6.0"
s.osx.deployment_target = "10.9"
s.requires_arc = true
s.source_files = 'Pod/Classes'
s.public_header_files = 'Pod/Classes/**/*.h'
s.frameworks = 'Foundation'
end
| 36.875 | 107 | 0.585311 |
87650afae961113706669c77d67255bccf13ef03 | 2,049 | require 'spec_helper'
describe Zonar do
describe '.bus_location' do
it 'parses xml response' do
sample_bus_location = bus_location_response(
bus_id: 'BUS1',
latitude: 1,
longitude: 2
)
stub_zonar_api [200, {}, sample_bus_location]
location = Zonar.bus_location('BUSID')
location.bus_id.should eq 'BUS1'
location.latitude.should eq '1'
location.longitude.should eq '2'
end
it 'returns nil if failed' do
stub_zonar_api [400, {}, "{}"]
Zonar.bus_location('BUSID').should be_nil
# Ensure cache miss
Rails.cache.fetch('zonar.locations.BUSID').should be_nil
end
it 'caches bus locations for 60 seconds' do
location = bus_location_response(
bus_id: 'cacheme',
latitude: 42,
longitude: -71
)
stub_zonar_api [200, {}, location]
Zonar.connection.should_receive(:get).twice.and_call_original
Zonar.bus_location('cacheme')
Zonar.bus_location('cacheme')
Timecop.travel(60.seconds.from_now)
Zonar.bus_location('cacheme')
end
it 'returns nil when an empty <currentlocations> object is returned' do
location = "<currentlocations>\n</currentlocations>"
stub_zonar_api [200, {}, location]
Zonar.bus_location('BUSID').should be_nil
end
end
describe '.bus_history' do
it 'parses json response' do
time = Time.zone.local(2010, 10, 30, 10, 30)
sample_bus_history = bus_history_response(
lat: 1,
lng: 2,
time: time
)
stub_zonar_history_api [200, {}, [sample_bus_history]]
history = Zonar.bus_history('BUS')
point = history.first
point.latitude.should eq 1
point.longitude.should eq 2
point.last_updated_at.should eq time
end
it 'returns [] if failed' do
stub_zonar_api [400, {}, "{}"]
Zonar.bus_history('BUSID').should == []
# Ensure cache miss
Rails.cache.fetch('zonar.history.BUSID').should be_nil
end
end
end
| 23.825581 | 75 | 0.632016 |
f846fb6df13b7ab9889a78477609af09a5e812ca | 85 | Rails.application.routes.draw do
mount GiRaycaster::Engine => "/gi_raycaster"
end
| 17 | 46 | 0.764706 |
619cd610f180989d6a61fc5bfe051a048d126893 | 461 | require_relative 'thor_test'
module Zsh
module PlainSubcommands
class Subcommand < ThorTest
desc 'noopts', 'subcommand that takes no options'
def noopts
puts 'noopts'
end
desc 'withopts', 'subcommand that takes options'
option :an_option
def withopts
puts 'with options'
end
end
class Main < ThorTest
desc 'sub', 'a subcommand'
subcommand 'sub', Subcommand
end
end
end | 20.043478 | 55 | 0.631236 |
6127e6ecf745744bb72bd6de5ab21346f9bbe5db | 28,104 | # encoding: utf-8
#
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
module Selenium
module Client
# Provide a more idiomatic API than the generated Ruby driver.
#
# Work in progress...
module Idiomatic
# Return the text content of an HTML element (rendered text shown to
# the user). Works for any HTML element that contains text.
#
#
# This command uses either the textContent (Mozilla-like browsers)
# or the innerText (IE-like browsers) of the element, which is the
# rendered text shown to the user.
#
# * 'locator' is an Selenium element locator
#
def text(locator)
string_command "getText", [locator,]
end
alias :text_content :text
# Return the title of the current HTML page.
def title
string_command "getTitle"
end
# Returns the absolute URL of the current page.
def location
string_command "getLocation"
end
# Waits for a new page to load.
#
# Selenium constantly keeps track of new pages loading, and sets a
# "newPageLoaded" flag when it first notices a page load. Running
# any other Selenium command after turns the flag to false. Hence,
# if you want to wait for a page to load, you must wait immediately
# after a Selenium command that caused a page-load.
#
# * 'timeout_in_seconds' is a timeout in seconds, after which this
# command will return with an error
def wait_for_page(timeout_in_seconds=nil)
remote_control_command "waitForPageToLoad",
[actual_timeout_in_milliseconds(timeout_in_seconds),]
end
alias_method :wait_for_page_to_load, :wait_for_page
# Waits for a popup window to appear and load up.
#
# window_id is the JavaScript window "name" of the window that will appear (not the text of the title bar)
# timeout_in_seconds is a timeout in seconds, after which the action will return with an error
def wait_for_popup(window_id, timeout_in_seconds=nil)
remote_control_command "waitForPopUp",
[window_id, actual_timeout_in_milliseconds(timeout_in_seconds) ,]
end
# Flexible wait semantics. ait is happening browser side. Useful for testing AJAX application.
#
# * wait :wait_for => :page # will wait for a new page to load
# * wait :wait_for => :popup, :window => 'a window id' # will wait for a new popup window to appear. Also selects the popup window for you provide `:select => true`
# * wait :wait_for => :ajax # will wait for all ajax requests to be completed using semantics of default javascript framework
# * wait :wait_for => :ajax, :javascript_framework => :jquery # will wait for all ajax requests to be completed overriding default javascript framework
# * wait :wait_for => :effects # will wait for all javascript effects to be rendered using semantics of default javascript framework
# * wait :wait_for => :effects, :javascript_framework => :prototype # will wait for all javascript effects to be rendered overriding default javascript framework
# * wait :wait_for => :element, :element => 'new_element_id' # will wait for an element to be present/appear
# * wait :wait_for => :no_element, :element => 'new_element_id' # will wait for an element to be not be present/disappear
# * wait :wait_for => :text, :text => 'some text' # will wait for some text to be present/appear
# * wait :wait_for => :text, :text => /A Regexp/ # will wait for some text to be present/appear
# * wait :wait_for => :text, :element => 'a_locator', :text => 'some text' # will wait for the content of 'a_locator' to be 'some text'
# * wait :wait_for => :no_text, :text => 'some text' # will wait for the text to be not be present/disappear
# * wait :wait_for => :no_text, :text => /A Regexp/ # will wait for the text to be not be present/disappear
# * wait :wait_for => :no_text, :element => 'a_locator', :text => 'some text' # will wait for the content of 'a_locator' to not be 'some text'
# * wait :wait_for => :value, :element => 'a_locator', :value => 'some value' # will wait for the field value of 'a_locator' to be 'some value'
# * wait :wait_for => :no_value, :element => 'a_locator', :value => 'some value' # will wait for the field value of 'a_locator' to not be 'some value'
# * wait :wait_for => :visible, :element => 'a_locator' # will wait for element to be visible
# * wait :wait_for => :not_visible, :element => 'a_locator' # will wait for element to not be visible
# * wait :wait_for => :condition, :javascript => 'some expression' # will wait for the javascript expression to be true
#
# Using options you can also define an explicit timeout (:timeout_in_seconds key). Otherwise the default driver timeout
# is used.
def wait_for(options)
if options[:wait_for] == :page
wait_for_page options[:timeout_in_seconds]
elsif options[:wait_for] == :ajax
wait_for_ajax options
elsif options[:wait_for] == :element
wait_for_element options[:element], options
elsif options[:wait_for] == :no_element
wait_for_no_element options[:element], options
elsif options[:wait_for] == :text
wait_for_text options[:text], options
elsif options[:wait_for] == :no_text
wait_for_no_text options[:text], options
elsif options[:wait_for] == :effects
wait_for_effects options
elsif options[:wait_for] == :popup
wait_for_popup options[:window], options[:timeout_in_seconds]
select_window options[:window] if options[:select]
elsif options[:wait_for] == :value
wait_for_field_value options[:element], options[:value], options
elsif options[:wait_for] == :no_value
wait_for_no_field_value options[:element], options[:value], options
elsif options[:wait_for] == :visible
wait_for_visible options[:element], options
elsif options[:wait_for] == :not_visible
wait_for_not_visible options[:element], options
elsif options[:wait_for] == :condition
wait_for_condition options[:javascript], options[:timeout_in_seconds]
end
end
# Gets the entire text of the page.
def body_text
string_command "getBodyText"
end
# Clicks on a link, button, checkbox or radio button.
#
# 'locator' is an element locator
#
# Using 'options' you can automatically wait for an event to happen after the
# click. e.g.
#
# * click "a_locator", :wait_for => :page # will wait for a new page to load
# * click "a_locator", :wait_for => :popup, :window => 'a window id' # will wait for a new popup window to appear. Also selects the popup window for you provide `:select => true`
# * click "a_locator", :wait_for => :ajax # will wait for all ajax requests to be completed using semantics of default javascript framework
# * click "a_locator", :wait_for => :ajax, :javascript_framework => :jquery # will wait for all ajax requests to be completed overriding default javascript framework
# * click "a_locator", :wait_for => :effects # will wait for all javascript effects to be rendered using semantics of default javascript framework
# * click "a_locator", :wait_for => :effects, :javascript_framework => :prototype # will wait for all javascript effects to be rendered overriding default javascript framework
# * click "a_locator", :wait_for => :element, :element => 'new_element_id' # will wait for an element to be present/appear
# * click "a_locator", :wait_for => :no_element, :element => 'new_element_id' # will wait for an element to be not be present/disappear
# * click "a_locator", :wait_for => :text, :text => 'some text' # will wait for some text to be present/appear
# * click "a_locator", :wait_for => :text, :text => /A Regexp/ # will wait for some text to be present/appear
# * click "a_locator", :wait_for => :text, :element => 'a_locator', :text => 'some text' # will wait for the content of 'a_locator' to be 'some text'
# * click "a_locator", :wait_for => :no_text, :text => 'some text' # will wait for the text to be not be present/disappear
# * click "a_locator", :wait_for => :no_text, :text => /A Regexp/ # will wait for the text to be not be present/disappear
# * click "a_locator", :wait_for => :no_text, :element => 'a_locator', :text => 'some text' # will wait for the content of 'a_locator' to not be 'some text'
# * click "a_locator", :wait_for => :value, :element => 'a_locator', :value => 'some value' # will wait for the field value of 'a_locator' to be 'some value'
# * click "a_locator", :wait_for => :no_value, :element => 'a_locator', :value => 'some value' # will wait for the field value of 'a_locator' to not be 'some value'
# * click "a_locator", :wait_for => :visible, :element => 'a_locator' # will wait for element to be visible
# * click "a_locator", :wait_for => :not_visible, :element => 'a_locator' # will wait for element to not be visible
# * click "a_locator", :wait_for => :condition, :javascript => 'some expression' # will wait for the javascript expression to be true
#
# Using options you can also define an explicit timeout (:timeout_in_seconds key). Otherwise the default driver timeout
# is used.
def click(locator, options={})
remote_control_command "click", [locator,]
wait_for options
end
# Verifies that the specified text pattern appears somewhere on the rendered page shown to the user.
#
# * 'pattern' is a pattern to match with the text of the page
def text?(pattern)
boolean_command "isTextPresent", [pattern,]
end
# Verifies that the specified element is somewhere on the page.
#
# * 'locator' is an element locator
def element?(locator)
boolean_command "isElementPresent", [locator,]
end
# Determines if the specified element is visible. An
# element can be rendered invisible by setting the CSS "visibility"
# property to "hidden", or the "display" property to "none", either for the
# element itself or one if its ancestors. This method will fail if
# the element is not present.
#
# 'locator' is an element locator
def visible?(locator)
boolean_command "isVisible", [locator,]
end
# Gets the (whitespace-trimmed) value of an input field
# (or anything else with a value parameter).
# For checkbox/radio elements, the value will be "on" or "off"
# depending on whether the element is checked or not.
#
# * 'locator' is an element locator
def field(locator)
string_command "getValue", [locator,]
end
# Alias for +field+
def value(locator)
field locator
end
# Returns whether a toggle-button (checkbox/radio) is checked.
# Fails if the specified element doesn't exist or isn't a toggle-button.
#
# * 'locator' is an element locator pointing to a checkbox or radio button
def checked?(locator)
boolean_command "isChecked", [locator,]
end
# Whether an alert occurred
def alert?
boolean_command "isAlertPresent"
end
# Retrieves the message of a JavaScript alert generated during the previous action,
# or fail if there were no alerts.
#
# Getting an alert has the same effect as manually clicking OK. If an
# alert is generated but you do not consume it with getAlert, the next Selenium action
# will fail.
#
# Under Selenium, JavaScript alerts will NOT pop up a visible alert
# dialog.
#
# Selenium does NOT support JavaScript alerts that are generated in a
# page's onload() event handler. In this case a visible dialog WILL be
# generated and Selenium will hang until someone manually clicks OK.
#
def alert
string_command "getAlert"
end
# Whether a confirmation has been auto-acknoledged (i.e. confirm() been called)
def confirmation?
boolean_command "isConfirmationPresent"
end
# Retrieves the message of a JavaScript confirmation dialog generated during
# the previous action.
#
# By default, the confirm function will return true, having the same effect
# as manually clicking OK. This can be changed by prior execution of the
# chooseCancelOnNextConfirmation command.
#
# If an confirmation is generated but you do not consume it with getConfirmation,
# the next Selenium action will fail.
#
# NOTE: under Selenium, JavaScript confirmations will NOT pop up a visible
# dialog.
#
# NOTE: Selenium does NOT support JavaScript confirmations that are
# generated in a page's onload() event handler. In this case a visible
# dialog WILL be generated and Selenium will hang until you manually click
# OK.
def confirmation
string_command "getConfirmation"
end
# Whether a prompt occurred
def prompt?
boolean_command "isPromptPresent"
end
# Retrieves the message of a JavaScript question prompt dialog generated during
# the previous action.
#
# Successful handling of the prompt requires prior execution of the
# answerOnNextPrompt command. If a prompt is generated but you
# do not get/verify it, the next Selenium action will fail.
#
# NOTE: under Selenium, JavaScript prompts will NOT pop up a visible
# dialog.
#
# NOTE: Selenium does NOT support JavaScript prompts that are generated in a
# page's onload() event handler. In this case a visible dialog WILL be
# generated and Selenium will hang until someone manually clicks OK.
def prompt
string_command "getPrompt"
end
# Returns the result of evaluating the specified JavaScript snippet whithin the browser.
# The snippet may have multiple lines, but only the result of the last line will be returned.
#
# Note that, by default, the snippet will run in the context of the "selenium"
# object itself, so <tt>this</tt> will refer to the Selenium object. Use <tt>window</tt> to
# refer to the window of your application, e.g. <tt>window.document.getElementById('foo')</tt>
# If you need to use
# a locator to refer to a single element in your application page, you can
# use <tt>this.browserbot.findElement("id=foo")</tt> where "id=foo" is your locator.
#
# * 'script' is the JavaScript snippet to run
def js_eval(script)
string_command "getEval", [script,]
end
# Set the Remote Control timeout (as opposed to the client side driver timeout).
# This timout specifies the amount of time that Selenium Core will wait for actions to complete.
#
# The default timeout is 30 seconds.
# 'timeout' is a timeout in seconds, after which the action will return with an error
#
# Actions that require waiting include "open" and the "waitFor*" actions.
def remote_control_timeout_in_seconds=(timeout_in_seconds)
remote_control_command "setTimeout", [actual_timeout_in_milliseconds(timeout_in_seconds),]
end
# Returns the text from a cell of a table. The cellAddress syntax
# tableLocator.row.column, where row and column start at 0.
#
# * 'tableCellAddress' is a cell address, e.g. "foo.1.4"
def table_cell_text(tableCellAddress)
string_command "getTable", [tableCellAddress,]
end
# Runs the specified JavaScript snippet repeatedly until it evaluates to "true".
# The snippet may have multiple lines, but only the result of the last line
# will be considered.
#
# Note that, by default, the snippet will be run in the runner's test window, not in the window
# of your application. To get the window of your application, you can use
# the JavaScript snippet <tt>selenium.browserbot.getCurrentWindow()</tt>, and then
# run your JavaScript in there
#
#
# * 'script' is the JavaScript snippet to run
# * 'timeout_in_seconds' is a timeout in seconds, after which this command will return with an error
def wait_for_condition(script, timeout_in_seconds = nil)
remote_control_command "waitForCondition",
[script, actual_timeout_in_milliseconds(timeout_in_seconds),]
end
# Simulates the user clicking the "back" button on their browser.
# Using 'options' you can automatically wait for an event to happen after the
# click. e.g.
#
# * go_back :wait_for => :page # will wait for a new page to load
# * go_back :wait_for => :popup, :window => 'a window id' # will wait for a new popup window to appear. Also selects the popup window for you provide `:select => true`
# * go_back :wait_for => :ajax # will wait for all ajax requests to be completed using semantics of default javascript framework
# * go_back :wait_for => :ajax, :javascript_framework => :jquery # will wait for all ajax requests to be completed overriding default javascript framework
# * go_back :wait_for => :effects # will wait for all javascript effects to be rendered using semantics of default javascript framework
# * go_back :wait_for => :effects, :javascript_framework => :prototype # will wait for all javascript effects to be rendered overriding default javascript framework
# * go_back :wait_for => :element, :element => 'new_element_id' # will wait for an element to be present/appear
# * go_back :wait_for => :no_element, :element => 'new_element_id' # will wait for an element to be not be present/disappear
# * go_back :wait_for => :text, :text => 'some text' # will wait for some text to be present/appear
# * go_back "a_locator", :wait_for => :text, :text => /A Regexp/ # will wait for some text to be present/appear
# * go_back :wait_for => :text, :element => 'a_locator', :text => 'some text' # will wait for the content of 'a_locator' to be 'some text'
# * go_back :wait_for => :no_text, :text => 'some text' # will wait for the text to be not be present/disappear
# * go_back "a_locator", :wait_for => :no_text, :text => /A Regexp/ # will wait for the text to be not be present/disappear
# * go_back :wait_for => :no_text, :element => 'a_locator', :text => 'some text' # will wait for the content of 'a_locator' to not be 'some text'
# * go_back :wait_for => :condition, :javascript => 'some expression' # will wait for the javascript expression to be true
# * go_back :wait_for => :value, :element => 'a_locator', :value => 'some value' # will wait for the field value of 'a_locator' to be 'some value'
# * go_back :wait_for => :visible, :element => 'a_locator' # will wait for element to be visible
# * go_back :wait_for => :not_visible, :element => 'a_locator' # will wait for element to not be visible
# * go_back :wait_for => :no_value, :element => 'a_locator', :value => 'some value' # will wait for the field value of 'a_locator' to not be 'some value'
#
# Using options you can also define an explicit timeout (:timeout_in_seconds key). Otherwise the default driver timeout
# is used.
def go_back(options={})
remote_control_command "goBack"
wait_for options
end
# Return all cookies for the current page under test.
def cookies
string_command "getCookie"
end
# Returns the value of the cookie with the specified name, or throws an error if the cookie is not present.
#
# 'name' is the name of the cookie
def cookie(name)
string_command "getCookieByName", [name,]
end
# Returns true if a cookie with the specified name is present, or false otherwise.
#
# 'name' is the name of the cookie
def cookie?(name)
boolean_command "isCookiePresent", [name,]
end
# Create a new cookie whose path and domain are same with those of current page
# under test, unless you specified a path for this cookie explicitly.
#
# 'nameValuePair' is name and value of the cookie in a format "name=value"
# 'optionsString' is options for the cookie. Currently supported options include 'path', 'max_age' and 'domain'.
# the optionsString's format is "path=/path/, max_age=60, domain=.foo.com". The order of options are irrelevant, the unit of the value of 'max_age' is second. Note that specifying a domain that isn't a subset of the current domain will usually fail.
def create_cookie(name_value_pair, options="")
if options.kind_of? Hash
options = options.keys.collect {|key| "#{key}=#{options[key]}" }.sort.join(", ")
end
remote_control_command "createCookie", [name_value_pair,options,]
end
# Delete a named cookie with specified path and domain. Be careful; to delete a cookie, you
# need to delete it using the exact same path and domain that were used to create the cookie.
# If the path is wrong, or the domain is wrong, the cookie simply won't be deleted. Also
# note that specifying a domain that isn't a subset of the current domain will usually fail.
#
# Since there's no way to discover at runtime the original path and domain of a given cookie,
# we've added an option called 'recurse' to try all sub-domains of the current domain with
# all paths that are a subset of the current path. Beware; this option can be slow. In
# big-O notation, it operates in O(n*m) time, where n is the number of dots in the domain
# name and m is the number of slashes in the path.
#
# 'name' is the name of the cookie to be deleted
# 'optionsString' is options for the cookie. Currently supported options include 'path', 'domain' and 'recurse.' The optionsString's format is "path=/path/, domain=.foo.com, recurse=true". The order of options are irrelevant. Note that specifying a domain that isn't a subset of the current domain will usually fail.
def delete_cookie(name, options="")
if options.kind_of? Hash
ordered_keys = options.keys.sort {|a,b| a.to_s <=> b.to_s }
options = ordered_keys.collect {|key| "#{key}=#{options[key]}" }.join(", ")
end
remote_control_command "deleteCookie", [name,options,]
end
# Returns the IDs of all windows that the browser knows about.
def all_window_ids
string_array_command "getAllWindowIds"
end
# Returns the names of all windows that the browser knows about.
def all_window_names
string_array_command "getAllWindowNames"
end
# Returns the titles of all windows that the browser knows about.
def all_window_titles
string_array_command "getAllWindowTitles"
end
# Returns a string representation of the network traffic seen by the
# browser, including headers, AJAX requests, status codes, and timings.
# When this function is called, the traffic log is cleared, so the
# returned content is only the traffic seen since the last call.
#
# The network traffic is returned in the format it was requested. Valid
# values are: :json, :xml, or :plain.
#
# Warning: For browser_network_traffic to work you need to start your
# browser session with the option "captureNetworkTraffic=true", which
# will force ALL traffic to go to the Remote Control proxy even for
# more efficient browser modes like `*firefox` and `*safari`.
def browser_network_traffic(format = :plain)
raise "format must be :plain, :json, or :xml" \
unless [:plain, :json, :xml].include?(format)
remote_control_command "captureNetworkTraffic", [format.to_s]
end
# Allows choice of a specific XPath libraries for Xpath evualuation
# in the browser (e.g. to resolve XPath locators).
#
# `library_name' can be:
# * :ajaxslt : Google's library
# * :javascript-xpath : Cybozu Labs' faster library
# * :default : Selenium default library.
def browser_xpath_library=(library_name)
raise "library name must be :ajaxslt, :javascript-xpath, or :default" \
unless [:ajaxslt, :'javascript-xpath', :default].include?(library_name)
remote_control_command "useXpathLibrary", [library_name.to_s]
end
#
# Turn on/off the automatic hightlighting of the element driven or
# inspected by Selenium core. Useful when recording videos
#
def highlight_located_element=(enabled)
boolean = (true == enabled)
js_eval "selenium.browserbot.shouldHighlightLocatedElement = #{boolean}"
end
# Get execution delay in milliseconds, i.e. a pause delay following
# each selenium operation. By default, there is no such delay
# (value is 0).
def execution_delay
string_command "getSpeed"
end
# Set the execution delay in milliseconds, i.e. a pause delay following
# each selenium operation. By default, there is no such delay.
#
# Setting an execution can be useful to troubleshoot or capture videos
def execution_delay=(delay_in_milliseconds)
remote_control_command "setSpeed", [delay_in_milliseconds]
end
def actual_timeout_in_milliseconds(timeout_in_seconds)
actual_timeout = (timeout_in_seconds ||
default_timeout_in_seconds).to_i
actual_timeout * 1000
end
end
end
end
| 55.322835 | 337 | 0.639197 |
08859bf15e7cf3295f763cc64a660b8bd7d80cdb | 227 | %w(rubygems halcyon).each{|dep|require dep}
module <%= app %>
class Client < Halcyon::Client
def self.version
VERSION.join('.')
end
def time
get('/time')[:body]
end
end
end
| 12.611111 | 43 | 0.53304 |
384c8c2635efe5c3e573e4d82223f6f203c6f509 | 5,064 | # Runs a [lambda](https://docs.puppetlabs.com/puppet/latest/reference/lang_lambdas.html)
# repeatedly using each value in a data structure, then returns the values unchanged.
#
# This function takes two mandatory arguments, in this order:
#
# 1. An array, hash, or other iterable object that the function will iterate over.
# 2. A lambda, which the function calls for each element in the first argument. It can
# request one or two parameters.
#
# @example Using the `each` function
#
# `$data.each |$parameter| { <PUPPET CODE BLOCK> }`
#
# or
#
# `each($data) |$parameter| { <PUPPET CODE BLOCK> }`
#
# When the first argument (`$data` in the above example) is an array, Puppet passes each
# value in turn to the lambda, then returns the original values.
#
# @example Using the `each` function with an array and a one-parameter lambda
#
# ~~~ puppet
# # For the array $data, run a lambda that creates a resource for each item.
# $data = ["routers", "servers", "workstations"]
# $data.each |$item| {
# notify { $item:
# message => $item
# }
# }
# # Puppet creates one resource for each of the three items in $data. Each resource is
# # named after the item's value and uses the item's value in a parameter.
# ~~~
#
# When the first argument is a hash, Puppet passes each key and value pair to the lambda
# as an array in the form `[key, value]` and returns the original hash.
#
# @example Using the `each` function with a hash and a one-parameter lambda
#
# ~~~ puppet
# # For the hash $data, run a lambda using each item as a key-value array that creates a
# # resource for each item.
# $data = {"rtr" => "Router", "svr" => "Server", "wks" => "Workstation"}
# $data.each |$items| {
# notify { $items[0]:
# message => $items[1]
# }
# }
# # Puppet creates one resource for each of the three items in $data, each named after the
# # item's key and containing a parameter using the item's value.
# ~~~
#
# When the first argument is an array and the lambda has two parameters, Puppet passes the
# array's indexes (enumerated from 0) in the first parameter and its values in the second
# parameter.
#
# @example Using the `each` function with an array and a two-parameter lambda
#
# ~~~ puppet
# # For the array $data, run a lambda using each item's index and value that creates a
# # resource for each item.
# $data = ["routers", "servers", "workstations"]
# $data.each |$index, $value| {
# notify { $value:
# message => $index
# }
# }
# # Puppet creates one resource for each of the three items in $data, each named after the
# # item's value and containing a parameter using the item's index.
# ~~~
#
# When the first argument is a hash, Puppet passes its keys to the first parameter and its
# values to the second parameter.
#
# @example Using the `each` function with a hash and a two-parameter lambda
#
# ~~~ puppet
# # For the hash $data, run a lambda using each item's key and value to create a resource
# # for each item.
# $data = {"rtr" => "Router", "svr" => "Server", "wks" => "Workstation"}
# $data.each |$key, $value| {
# notify { $key:
# message => $value
# }
# }
# # Puppet creates one resource for each of the three items in $data, each named after the
# # item's key and containing a parameter using the item's value.
# ~~~
#
# For an example that demonstrates how to create multiple `file` resources using `each`,
# see the Puppet
# [iteration](https://docs.puppetlabs.com/puppet/latest/reference/lang_iteration.html)
# documentation.
#
# @since 4.0.0
#
Puppet::Functions.create_function(:each) do
dispatch :foreach_Hash_2 do
param 'Hash[Any, Any]', :hash
block_param 'Callable[2,2]', :block
end
dispatch :foreach_Hash_1 do
param 'Hash[Any, Any]', :hash
block_param 'Callable[1,1]', :block
end
dispatch :foreach_Enumerable_2 do
param 'Iterable', :enumerable
block_param 'Callable[2,2]', :block
end
dispatch :foreach_Enumerable_1 do
param 'Iterable', :enumerable
block_param 'Callable[1,1]', :block
end
def foreach_Hash_1(hash)
enumerator = hash.each_pair
begin
hash.size.times do
yield(enumerator.next)
end
rescue StopIteration
end
# produces the receiver
hash
end
def foreach_Hash_2(hash)
enumerator = hash.each_pair
begin
hash.size.times do
yield(*enumerator.next)
end
rescue StopIteration
end
# produces the receiver
hash
end
def foreach_Enumerable_1(enumerable)
enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable)
begin
loop { yield(enum.next) }
rescue StopIteration
end
# produces the receiver
enumerable
end
def foreach_Enumerable_2(enumerable)
enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable)
if enum.hash_style?
enum.each { |entry| yield(*entry) }
else
begin
index = 0
loop do
yield(index, enum.next)
index += 1
end
rescue StopIteration
end
end
# produces the receiver
enumerable
end
end
| 29.788235 | 90 | 0.67654 |
911e049011918e80d4cefbd7da9022b0821ce735 | 404 | cask 'hipsterchat' do
version '0.2.1'
sha256 'efe6135fba92a437e18c4227569174f9505f91398946c9e8b0860f85b0c7d487'
url "https://github.com/kvasir/hipsterchat/releases/download/v#{version}/HipsterChat-osx-#{version}.zip"
appcast 'https://github.com/kvasir/hipsterchat/releases.atom'
name 'HipsterChat'
homepage 'https://github.com/kvasir/hipsterchat'
license :mit
app 'HipsterChat.app'
end
| 31.076923 | 106 | 0.774752 |
6132e15b655bd1ba33133164797aede297c068ad | 744 | require 'sinatra/base'
require 'sinatra/reloader'
require 'sinatra/assetpack'
require 'sinatra/partial'
class App < Sinatra::Base
set :root, File.dirname(__FILE__)
set :haml, format: :html5
configure :development do
register Sinatra::Reloader
end
register Sinatra::Partial
enable :partial_underscores
register Sinatra::AssetPack
assets {
serve '/javascripts', from: 'app/javascripts'
serve '/stylesheets', from: 'app/stylesheets'
serve '/images', from: 'app/images'
js :application, [
'/javascripts/application.js'
]
css :screen, [
'/stylesheets/screen.css'
]
js_compression :uglify
css_compression :sass
prebuild true
}
get '/' do
haml :index
end
end
| 17.714286 | 49 | 0.673387 |
6a86f8c087a69b13656904f3fa76110bcc6c6cd3 | 1,803 | # -------------------------------------------------------------------------- #
# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems #
# #
# 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. #
#--------------------------------------------------------------------------- #
EXAMPLES_PATH = File.join(File.dirname(__FILE__),'../examples')
FIXTURES_PATH = File.join(File.dirname(__FILE__),'../fixtures')
ONEUI_LIB_LOCATION = File.join(File.dirname(__FILE__), '..', '..')
$: << ONEUI_LIB_LOCATION
# Load the testing libraries
require 'rubygems'
require 'rspec'
require 'rack/test'
require 'json'
# Load the Sinatra app
require 'sunstone-server'
# Make Rack::Test available to all spec contexts
Spec::Runner.configure do |conf|
conf.include Rack::Test::Methods
end
# Set the Sinatra environment
set :environment, :test
# Add an app method for RSpec
def app
Sinatra::Application
end
| 41.930233 | 78 | 0.511925 |
5dc6ff837577cb3fed16dccca521eddec338fad4 | 8,131 | module ActiveMerchant #:nodoc:
module Billing #:nodoc:
class CashnetGateway < Gateway
self.live_url = "https://commerce.cashnet.com/"
self.supported_countries = ["US"]
self.supported_cardtypes = [:visa, :master, :american_express, :discover, :diners_club, :jcb]
self.homepage_url = "http://www.higherone.com/"
self.display_name = "Cashnet"
self.money_format = :dollars
# Creates a new CashnetGateway
#
# ==== Options
#
# * <tt>:merchant</tt> -- Gateway Merchant (REQUIRED)
# * <tt>:operator</tt> -- Operator (REQUIRED)
# * <tt>:password</tt> -- Password (REQUIRED)
# * <tt>:merchant_gateway_name</tt> -- Site name (REQUIRED)
# * <tt>:station</tt> -- Station (defaults to "WEB")
# * <tt>:default_item_code</tt> -- Item code (defaults to "FEE")
def initialize(options = {})
requires!(
options,
:merchant,
:operator,
:password,
:merchant_gateway_name
)
options[:default_item_code] ||= "FEE"
super
end
def purchase(money, payment_object, fields = {})
post = {}
add_creditcard(post, payment_object)
add_invoice(post, fields)
add_address(post, fields)
add_customer_data(post, fields)
commit('SALE', money, post)
end
def refund(money, identification, fields = {})
fields[:origtx] = identification
commit('REFUND', money, fields)
end
private
def commit(action, money, fields)
fields[:amount] = amount(money)
url = live_url + @options[:merchant_gateway_name]
response = parse(ssl_post(url, post_data(action, fields)))
success = (response[:result] == '0')
Response.new(
success,
CASHNET_CODES[response[:result]],
response,
test: test?,
authorization: (success ? response[:tx] : '')
)
end
def post_data(action, parameters = {})
post = {}
post[:command] = action
post[:merchant] = @options[:merchant]
post[:operator] = @options[:operator]
post[:password] = @options[:password]
post[:station] = (@options[:station] || "WEB")
post[:itemcode] = (options[:item_code] || @options[:default_item_code])
post[:custcode] = "ActiveMerchant/#{ActiveMerchant::VERSION}"
post.merge(parameters).collect { |key, value| "#{key}=#{CGI.escape(value.to_s)}" }.join("&")
end
def add_creditcard(post, creditcard)
post[:cardno] = creditcard.number
post[:cid] = creditcard.verification_value
post[:expdate] = expdate(creditcard)
post[:card_name_g] = creditcard.name
post[:fname] = creditcard.first_name
post[:lname] = creditcard.last_name
end
def add_invoice(post, options)
post[:order_number] = options[:order_id] if options[:order_id].present?
end
def add_address(post, options)
if address = (options[:shipping_address] || options[:billing_address] || options[:address])
post[:addr_g] = String(address[:address1]) + ',' + String(address[:address2])
post[:city_g] = address[:city]
post[:state_g] = address[:state]
post[:zip_g] = address[:zip]
end
end
def add_customer_data(post, options)
post[:email_g] = options[:email]
end
def expdate(creditcard)
year = format(creditcard.year, :two_digits)
month = format(creditcard.month, :two_digits)
"#{month}#{year}"
end
def parse(body)
response_data = body.match(/<cngateway>(.*)<\/cngateway>/)[1]
Hash[CGI::parse(response_data).map{|k,v| [k.to_sym,v.first]}]
end
def handle_response(response)
if (200...300).include?(response.code.to_i)
return response.body
elsif 302 == response.code.to_i
return ssl_get(URI.parse(response['location']))
end
raise ResponseError.new(response)
end
CASHNET_CODES = {
'0' => 'Success',
'1' => 'Invalid customer code, no customer code specified',
'2' => 'Invalid operator code, no operator specified',
'3' => 'Invalid workstation code, no station specified',
'4' => 'Invalid item code, no code specified',
'5' => 'Negative amount is not allowed',
'6' => 'Invalid credit card number, no credit card number provided',
'7' => 'Invalid expiration date, no expiration date provided',
'8' => 'Please only provide either ACH or credit card information',
'9' => 'Invalid ACH account number, no account number provided',
'10' => 'Invalid routing/transit number, no routing/transit number provided',
'11' => 'Invalid account type, no account type provided',
'12' => 'Invalid check digit for routing/transit number',
'13' => 'No ACH merchant account set up for the location of the station being used',
'21' => 'Invalid merchant code, no merchant code provided',
'22' => 'Invalid client code, no client code provided',
'23' => 'Invalid password, no password provided',
'24' => 'Invalid transaction type, no transaction type provided',
'25' => 'Invalid amount, amount not provided',
'26' => 'Invalid payment code provided',
'27' => 'Invalid version number, version not found',
'31' => 'Application amount exceeds account balance',
'150' => 'Invalid payment information, no payment information provided',
'200' => 'Invalid command',
'201' => 'Customer not on file',
'205' => 'Invalid operator or password',
'206' => 'Operator is not authorized for this function',
'208' => 'Customer/PIN authentication unsuccessful',
'209' => 'Credit card error',
'211' => 'Credit card error',
'212' => 'Customer/PIN not on file',
'213' => 'Customer information not on file',
'215' => 'Old PIN does not validate ',
'221' => 'Invalid credit card processor type specified in location or payment code',
'222' => 'Credit card processor error',
'280' => 'SmartPay transaction not posted',
'301' => 'Original transaction not found for this customer',
'302' => 'Amount to refund exceeds original payment amount or is missing',
'304' => 'Original credit card payment not found or corrupted',
'305' => 'Refund amounts should be expressed as positive amounts',
'306' => 'Original ACH payment not found',
'307' => 'Original electronic payment not found',
'308' => 'Invalid original transaction number, original transaction number not found',
'310' => 'Refund amount exceeds amount still available for a refund',
'321' => 'Store has not been implemented',
'501' => 'Unable to roll over batch',
'502' => 'Batch not found',
'503' => 'Batch information not available',
'650' => 'Invalid quick code',
'651' => 'Transaction amount does not match amount specified in quick code',
'652' => 'Invalid item code in the detail of the quick code',
'701' => 'This website has been disabled. Please contact the system administrator.',
'702' => 'Improper merchant code. Please contact the system administrator.',
'703' => 'This site is temporarily down for maintenance. We regret the inconvenience. Please try again later.',
'704' => 'Duplicate item violation. Please contact the system administrator.',
'705' => 'An invalid reference type has been passed into the system. Please contact the system administrator',
'706' => 'Items violating unique selection have been passed in. Please contact the system administrator.',
'999' => 'An unexpected error has occurred. Please consult the event log.'
}
end
end
end
| 43.481283 | 119 | 0.594761 |
28ebb508b63b8304a2194162e1014f27be5fcfb0 | 4,936 | # frozen_string_literal: true
require 'ci/queue/static'
require 'set'
module CI
module Queue
module Redis
ReservationError = Class.new(StandardError)
class << self
attr_accessor :requeue_offset
end
self.requeue_offset = 42
class Worker < Base
attr_reader :total
def initialize(redis, config)
@reserved_test = nil
@shutdown_required = false
super(redis, config)
end
def populate(tests, random: Random.new)
@index = tests.map { |t| [t.id, t] }.to_h
tests = Queue.shuffle(tests, random)
push(tests.map(&:id))
self
end
def populated?
!!defined?(@index)
end
def shutdown!
@shutdown_required = true
end
def shutdown_required?
@shutdown_required
end
def master?
@master
end
def poll
wait_for_master
until shutdown_required? || config.circuit_breakers.any?(&:open?) || exhausted? || max_test_failed?
if test = reserve
yield index.fetch(test)
else
sleep 0.05
end
end
rescue *CONNECTION_ERRORS
end
if ::Redis.method_defined?(:exists?)
def retrying?
redis.exists?(key('worker', worker_id, 'queue'))
rescue *CONNECTION_ERRORS
false
end
else
def retrying?
redis.exists(key('worker', worker_id, 'queue'))
rescue *CONNECTION_ERRORS
false
end
end
def retry_queue
failures = build.failed_tests.to_set
log = redis.lrange(key('worker', worker_id, 'queue'), 0, -1)
log.select! { |id| failures.include?(id) }
log.uniq!
log.reverse!
Retry.new(log, config, redis: redis)
end
def supervisor
Supervisor.new(redis_url, config)
end
def build
@build ||= CI::Queue::Redis::BuildRecord.new(self, redis, config)
end
def acknowledge(test)
test_key = test.id
raise_on_mismatching_test(test_key)
eval_script(
:acknowledge,
keys: [key('running'), key('processed')],
argv: [test_key],
) == 1
end
def requeue(test, offset: Redis.requeue_offset)
test_key = test.id
raise_on_mismatching_test(test_key)
global_max_requeues = config.global_max_requeues(total)
requeued = config.max_requeues > 0 && global_max_requeues > 0 && eval_script(
:requeue,
keys: [key('processed'), key('requeues-count'), key('queue'), key('running')],
argv: [config.max_requeues, global_max_requeues, test_key, offset],
) == 1
@reserved_test = test_key unless requeued
requeued
end
private
attr_reader :index
def worker_id
config.worker_id
end
def timeout
config.timeout
end
def raise_on_mismatching_test(test)
if @reserved_test == test
@reserved_test = nil
else
raise ReservationError, "Acknowledged #{test.inspect} but #{@reserved_test.inspect} was reserved"
end
end
def reserve
if @reserved_test
raise ReservationError, "#{@reserved_test.inspect} is already reserved. " \
"You have to acknowledge it before you can reserve another one"
end
@reserved_test = (try_to_reserve_lost_test || try_to_reserve_test)
end
def try_to_reserve_test
eval_script(
:reserve,
keys: [key('queue'), key('running'), key('processed'), key('worker', worker_id, 'queue')],
argv: [Time.now.to_f],
)
end
def try_to_reserve_lost_test
lost_test = eval_script(
:reserve_lost,
keys: [key('running'), key('completed'), key('worker', worker_id, 'queue')],
argv: [Time.now.to_f, timeout],
)
if lost_test
build.record_warning(Warnings::RESERVED_LOST_TEST, test: lost_test, timeout: timeout)
end
lost_test
end
def push(tests)
@total = tests.size
if @master = redis.setnx(key('master-status'), 'setup')
redis.multi do
redis.lpush(key('queue'), tests) unless tests.empty?
redis.set(key('total'), @total)
redis.set(key('master-status'), 'ready')
end
end
register
rescue *CONNECTION_ERRORS
raise if @master
end
def register
redis.sadd(key('workers'), worker_id)
end
end
end
end
end
| 26.255319 | 109 | 0.538695 |
037f8cd175041465c02d7df2a4216e59c0c2e373 | 719 | class CreateOriginalUrlAndService < ActiveRecord::Migration
def up
add_utf8mb4('stash_engine_file_uploads', 'original_url', 'utf8mb4_general_ci')
add_column :stash_engine_file_uploads, :cloud_service, :string
end
def down
remove_column :stash_engine_file_uploads, :original_url
remove_column :stash_engine_file_uploads, :cloud_service
end
private
def add_utf8mb4(table_name, col_name, collation = 'utf8mb4_bin')
warn "Table '#{table_name}' does not exist" unless table_exists?(table_name)
return unless table_exists?(table_name)
execute <<-SQL
ALTER TABLE #{table_name} ADD
#{col_name} TEXT
CHARACTER SET utf8mb4 COLLATE #{collation}
SQL
end
end
| 29.958333 | 82 | 0.741307 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.