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
|
---|---|---|---|---|---|
267f7dd71118d954d2ab7ba26f6e0641fa566290 | 1,684 | require 'rails_helper'
RSpec.describe CoursesController, type: :controller do
before(:each) do
@user = FactoryBot.create(:user)
@attr = FactoryBot.attributes_for(:course)
@model = FactoryBot.create(:course)
@entity = 'Course'
@path = courses_path
end
include_examples "permission_controller"
describe "POST #create" do
context 'params with empty value' do
it "renders page with error message" do
add_permission @entity, @user, create: true
sign_in @user
post :create, params: { "#{@entity.downcase}": { name: '' }}
expect(response).to render_template(:new)
expect(flash[:error]).to_not be_nil
expect(flash[:error].first).to match(/não pode ficar em branco/)
end
end
end
describe "PUT #update" do
context 'params with empty value' do
it "renders page with error message" do
add_permission @entity, @user, update: true
sign_in @user
put :update, params: { id: @model.id, "#{@entity.downcase}": { name: '' } }
expect(response).to render_template(:edit)
expect(flash[:error]).to_not be_nil
expect(flash[:error].first).to match(/não pode ficar em branco/)
end
end
end
describe "DELETE #destroy" do
context 'params with empty value' do
it "renders page with error message" do
expect_any_instance_of(Course).to receive(:destroy).and_return(false)
add_permission @entity, @user, destroy: true
sign_in @user
delete :destroy, params: { id: @model.id }
expect(response).to render_template(:new)
expect(flash[:error]).to_not be_nil
end
end
end
end
| 31.185185 | 83 | 0.643705 |
872aadc14619ac8caa4812039400edf13117fce3 | 749 | class Redis
module Objects
class ConnectionPoolProxy
def initialize(pool)
raise ArgumentError "Should only proxy ConnectionPool!" unless self.class.should_proxy?(pool)
@pool = pool
end
def method_missing(name, *args, &block)
@pool.with { |x| x.send(name, *args, &block) }
end
def respond_to_missing?(name, include_all = false)
@pool.with { |x| x.respond_to?(name, include_all) }
end
def self.should_proxy?(conn)
defined?(::ConnectionPool) && conn.is_a?(::ConnectionPool)
end
def self.proxy_if_needed(conn)
if should_proxy?(conn)
ConnectionPoolProxy.new(conn)
else
conn
end
end
end
end
end
| 24.16129 | 101 | 0.606142 |
abdc2cb7e042fb2806eb0a81366ed0feb7976d5c | 2,204 | require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: 'Example User', email: "[email protected]",
password: 'foobar', password_confirmation: "foobar")
end
test 'should be valid' do
assert @user.valid?
end
test "name should be present" do
@user.name = " "
assert_not @user.valid?
end
test "email should be present" do
@user.email = " "
assert_not @user.valid?
end
test "name should not be too long" do
@user.name = 'p' * 51
assert_not @user.valid?
end
test "email should not be too long" do
@user.email = 'a' * 244 + "@example.com"
assert_not @user.valid?
end
test "email validation should accept valid addresses" do
valid_addresses = %w[[email protected] [email protected] [email protected] [email protected] [email protected]]
valid_addresses.each do |valid_address|
@user.email = valid_address
assert @user.valid?, "#{valid_address.inspect} should be valid"
end
end
test "email validation should reject invalid addresses" do
invalid_addresses = %w[user@example,com user_at_foo.org user.name@example.
foo@bar_baz.com foo@bar+baz.com]
invalid_addresses.each do |invalid_address|
@user.email = invalid_address
assert_not @user.valid?, "#{invalid_address.inspect} should be invalid"
end
end
test "email addresses should be unique" do
duplicate_user = @user.dup
duplicate_user.email = @user.email.upcase
@user.save
assert_not duplicate_user.valid?
end
test "emails should be saved as lowercase" do
mixed_case_email = "[email protected]"
@user.email = mixed_case_email
@user.save
assert_equal mixed_case_email.downcase, @user.reload.email
end
test "password should be present" do
@user.password = @user.password_confirmation = " " * 6
assert_not @user.valid?
end
test "password should have a minimum length" do
@user.password = @user.password_confirmation = "a" * 5
assert_not @user.valid?
end
test "authenticated? should return false for a user with nil digest" do
assert_not @user.authenticated?(:remember, '')
end
end
| 28.25641 | 110 | 0.679673 |
fffbbb97a9b0379182991c3ac794b421b6072535 | 1,490 | # 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::MediaServices::Mgmt::V2019_05_01_preview
module Models
#
# Represents a token claim.
#
class ContentKeyPolicyTokenClaim
include MsRestAzure
# @return [String] Token claim type.
attr_accessor :claim_type
# @return [String] Token claim value.
attr_accessor :claim_value
#
# Mapper for ContentKeyPolicyTokenClaim class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ContentKeyPolicyTokenClaim',
type: {
name: 'Composite',
class_name: 'ContentKeyPolicyTokenClaim',
model_properties: {
claim_type: {
client_side_validation: true,
required: false,
serialized_name: 'claimType',
type: {
name: 'String'
}
},
claim_value: {
client_side_validation: true,
required: false,
serialized_name: 'claimValue',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 25.689655 | 70 | 0.536242 |
3319115ebfc98bb298c1f2f22db399d40c880e08 | 12,967 | module Doozer
class App
include Doozer::Util::Logger
attr_accessor :options
def initialize(args={})
@options=args
# load routes
load_routes
# load the application models, coontrollers, views, and helpers
load_files
# attach the file watcher for the mvc/lib/etc in development mode
load_watcher if Doozer::Configs.rack_env != :deployment
puts "=> Doozer racked up"
end
# This method is called along the rackup chain and maps the request path to the route, controller, and view for the format type.
def call(env)
# p env.inspect
# [200, {"Content-Type" => "text/html"}, "DOH!!!"]
path = env["PATH_INFO"]
# match env.path_info against the route compile
#p env.inspect
route = Doozer::Routing::Routes::match(path)
# p "path: #{path}"
# p "route: #{route.inspect}"
app = nil
if not route.nil?
if route.app.nil?
extra_params = route.extra_params(path)
controller_klass = handler(route.controller.to_sym)
controller = controller_klass.new({:env=>env, :route=>route, :extra_params=>extra_params, :port=>@options[:Port]})
# call after_initialize test for excludes
#execution_time('controller.after_initialize',:start)
controller.after_initialize if not controller_klass.after_initialize_exclude.include?(route.action.to_sym)
#execution_time(nil, :end)
begin
# call before_filter test for excludes
#execution_time('controller.before_filter',:start)
controller.before_filter if not controller_klass.before_filter_exclude.include?(route.action.to_sym)
#execution_time(nil,:end)
# call the action method
#execution_time('controller.method(route.action).call',:start)
controller.method(route.action).call()
#execution_time(nil,:end)
# call after_filter test for excludes
#execution_time('controller.after_filter',:start)
controller.after_filter if not controller_klass.after_filter_exclude.include?(route.action.to_sym)
#execution_time(nil, :end)
# render controller...
#execution_time('controller.render_result',:start)
r = Rack::Response.new(controller.render_result, route.status, {"Content-Type" => route.content_type})
#execution_time(nil,:end)
r.set_cookie('flash',{:value=>nil, :path=>'/'})
r.set_cookie('session',{:value=>controller.session_to_cookie(), :path=>'/'})
r = controller.write_response_cookies(r)
# finalize the request
controller.finished!
controller = nil
app = r.to_a
rescue Doozer::Redirect => redirect
# set the status to the one defined in the route which type of redirect do we need to handle?
status = (route.status==301) ? 301 : 302
# check to make sure the status wasn't manually changed in the controller
status = redirect.status if not redirect.status.nil?
r = Rack::Response.new("redirect...", status, {"Content-Type" => "text/html", "Location"=>redirect.url})
# if we get a redirect we need to do something with the flash messages...
r.set_cookie('flash',{:value=>controller.flash_to_cookie(), :path=>'/'}) # might need to set the domain from config app_name value
r.set_cookie('session',{:value=>controller.session_to_cookie(), :path=>'/'})
# finalize the request
controller.finished!
controller = nil
app = r.to_a
rescue => e
# finalize the request
controller.finished!
controller = nil
if Doozer::Configs.rack_env == :deployment
logger.error("RuntimeError: #{e.to_s}")
for line in e.backtrace
logger.error(" #{line}")
end
logger.error("Printing env variables:")
logger.error(env.inspect)
app = [500, {"Content-Type" => "text/html"}, @@errors[500]]
else
raise e
end
end
else
app = route.app.call(env)
end
else
app = [404, {"Content-Type" => "text/html"}, @@errors[404]]
end
# pass the app through route.middleware_after if defined
app = route.middleware_after.new(app, {:config=>Doozer::Configs, :route=>route}).call(env) if route.middleware_after
return app
end
def execution_time(name = nil, point = :start)
if Doozer::Configs.rack_env == :development
@execution_time_name = name if name
@execution_time_start = Time.now().to_f if point == :start
@execution_time_end = Time.now().to_f if point == :end
logger.info("Excecution Time: #{@execution_time_name}: #{("%0.2f" % ( (@execution_time_end - @execution_time_start) * 1000).to_f)}ms") if point == :end
end
end
# Load all application files for app/helpers/*, app/views/layouts/*, app/views/* and app/controllers/*
def load_files
# load models
load_models
puts "=> Caching files"
@@controllers = {}
@@mailers = {}
@@layouts={}
@@views={}
@@errors={}
# require helper files and include into Doozer::Partial
helper_files = Dir.glob(File.join(app_path,'app/helpers/*_helper.rb'))
helper_files.each {|f|
require f
key = f.split("helpers/")[1].gsub(/.rb/,'')
Doozer::Partial.include_view_helper(key)
}
# cache contoller classes
controller_files = Dir.glob(File.join(app_path,'app/controllers/*_controller.rb'))
# we need to load the application_controller first since this might not be the first in the list...
if controller_files.length > 0
i=0
for f in controller_files
break if i==0 and f.index('application_controller.rb')
if f.index('application_controller.rb')
controller_files.insert(0, controller_files.delete(f))
break
end
i+=1
end
end
controller_files.each { |f|
require f
key = f.split("controllers/")[1].split("_controller.rb")[0]
if key.index("_")
value = key.split('_').each{ | k | k.capitalize! }.join('')
else
value = key.capitalize
end
klass_name = "#{value}Controller"
@@controllers[key.to_sym] = klass_name
# p "cache controller: #{key.to_sym}"
# importing view helpers into controller
controller_klass = Object.const_get(klass_name)
# automatically ads the application helper to the class
controller_klass.include_view_helper('application_helper')
controller_klass.include_view_helpers
}
# cache layout erb's
layout_files = Dir.glob(File.join(app_path,'app/views/layouts/*.erb'))
layout_files.each {|f|
key = f.split("layouts/")[1].split(".html.erb")[0].gsub(/.xml.erb/, '_xml').gsub(/.json.erb/, '_json').gsub(/.js.erb/, '_js').gsub(/.rss.erb/, '_rss').gsub(/.atom.erb/, '_atom')
results = []
File.new(f, "r").each { |line| results << line }
@@layouts[key.to_sym] = ERB.new(results.join(""))
}
#lood 404 and 500 pages if they exist
pnf = Doozer::Configs.page_not_found_url
if pnf
file = File.join(app_path,"#{pnf}")
results = []
File.new(file, "r").each { |line| results << line }
@@errors[404] = results.join("")
else
@@errors[404] = "<html><body>Sorry, this page can't be found.</body></html>"
end
ise = Doozer::Configs.internal_server_error_url
if ise
file = File.join(app_path,"#{ise}")
results = []
File.new(file, "r").each { |line| results << line }
@@errors[500] = results.join("")
else
@@errors[500] = "<html><body>There was an internal server error which borked this request.</body></html>"
end
@@controllers.each_key { | key |
# p key.inspect
files = Dir.glob(File.join(app_path,"app/views/#{key.to_s}/*.erb"))
files.each { | f |
#!!!don't cache partials here!!!
view = f.split("#{key.to_s}/")[1].split(".erb")[0].gsub(/\./,'_')
# p "check view: #{view}"
if not /^_/.match( view )
# p "cache view: #{view}"
results = []
File.new(f, "r").each { |line| results << line }
@@views[key] = {} if @@views[key].nil?
@@views[key][view.to_sym] = ERB.new(results.join(""))
end
}
}
mailer_files = Dir.glob(File.join(app_path,'app/mailers/*_mailer.rb'))
mailer_files.each { |f|
require f
key = f.split("mailers/")[1].split("_mailer.rb")[0]
if key.index("_")
value = key.split('_').each{ | k | k.capitalize! }.join('')
else
value = key.capitalize
end
klass_name = "#{value}Mailer"
@@mailers[key.to_sym] = klass_name
# puts "cache mailer: #{key.to_sym}"
# importing view helpers into controller
mailer_klass = Object.const_get(klass_name)
# automatically ads the application helper to the class
mailer_klass.include_view_helper('application_helper')
mailer_klass.include_view_helpers
}
mail_key = :mail
mailer_files = Dir.glob(File.join(app_path,"app/views/#{mail_key.to_s}/*.erb"))
mailer_files.each { | f |
#!!!don't cache partials here!!!
view = f.split("#{mail_key.to_s}/")[1].split(".erb")[0].gsub(/\./,'_')
if not /^_/.match( view )
# puts "cache view: #{view}"
results = []
File.new(f, "r").each { |line| results << line }
@@views[mail_key] = {} if @@views[mail_key].nil?
@@views[mail_key][view.to_sym] = ERB.new(results.join(""))
end
}
end
# Load application routes
def load_routes
require File.join(app_path, 'config/routes')
end
# Load all application models in app/models
def load_models
puts "=> Loading models"
Dir.glob(File.join(app_path,'app/models/*.rb')).each { | model |
require model
}
end
# Loads the file watcher for all application files while in development mode-only.
#
# This allows you to edit files without restarting the app server to pickup new changes.
def load_watcher
require 'doozer/watcher'
puts "=> Watching files for changes"
watcher = FileSystemWatcher.new()
# watcher.addDirectory(File.join(File.dirname(__FILE__),'../doozer/'), "*.rb")
watcher.addDirectory( app_path + '/app/', "**/*")
watcher.addDirectory( app_path + '/app', "**/**/*")
watcher.addDirectory( app_path + '/config/', "*.*")
watcher.addDirectory( app_path + '/lib/', "*.*")
watcher.addDirectory( app_path + '/static/', "*.*")
watcher.addDirectory( app_path + '/static/', "**/**/*")
watcher.sleepTime = 1
watcher.start { |status, file|
if(status == FileSystemWatcher::CREATED) then
puts "created: #{file}"
load_files
Doozer::Partial.clear_loaded_partials
Doozer::MailerPartial.clear_loaded_partials
elsif(status == FileSystemWatcher::MODIFIED) then
puts "modified: #{file}"
load_files
Doozer::Partial.clear_loaded_partials
Doozer::MailerPartial.clear_loaded_partials
Doozer::Configs.clear_static_files
elsif(status == FileSystemWatcher::DELETED) then
puts "deleted: #{file}"
load_files
Doozer::Partial.clear_loaded_partials
Doozer::MailerPartial.clear_loaded_partials
Doozer::Configs.clear_static_files
end
}
#don't join the thread it messes up rackup threading watcher.join()
# p watcher.isStarted?
# p watcher.isStopped?
# p watcher.foundFiles.inspect
end
def handler(key)
return Object.const_get(@@controllers[key])
end
def app_path
Doozer::Configs.app_path
end
def self.controllers
@@controllers
end
def self.layouts
@@layouts
end
def self.views
@@views
end
end #App
end #Doozer | 38.250737 | 185 | 0.568443 |
f740727f627ab5a25fc7c9450cc584959b71a9ff | 756 | cask 'lingon-x' do
if MacOS.version <= :high_sierra
version '6.6.4'
sha256 'fc788402fa16df39a3d48cdc501dae31368ec6fd69ffe0026ba99932b28cae19'
else
version '7.3.1'
sha256 '13f39ef6859ada42398389376906e12b07b48a4938907f26f7658df0ccfe99a2'
end
url "https://www.peterborgapps.com/downloads/LingonX#{version.major}.zip"
appcast "https://www.peterborgapps.com/updates/lingonx#{version.major}.plist"
name 'Lingon X'
homepage 'https://www.peterborgapps.com/lingon/'
depends_on macos: '>= :high_sierra'
app 'Lingon X.app'
zap trash: [
"~/Library/Application Scripts/com.peterborgapps.LingonX#{version.major}",
"~/Library/Containers/com.peterborgapps.LingonX#{version.major}",
]
end
| 31.5 | 89 | 0.708995 |
b9ee3e758c290c417944a7a3f08c27baf4bdf28f | 1,237 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'Users API', type: :request do
let(:user) { build(:user) }
let(:headers) { valid_headers.except('Authorization') }
let(:valid_attributes) do
attributes_for(:user, password_confirmation: user.password)
end
# User signup test suite
describe 'POST /signup' do
context 'when valid request' do
before { post '/signup', params: valid_attributes.to_json, headers: headers }
it 'creates a new user' do
expect(response).to have_http_status(201)
end
it 'returns success message' do
expect(json['message']).to match(/Account created successfully/)
end
it 'returns an authentication token' do
expect(json['auth_token']).not_to be_nil
end
end
context 'when invalid request' do
before { post '/signup', params: {}, headers: headers }
it 'does not create a new user' do
expect(response).to have_http_status(422)
end
it 'returns failure message' do
expect(json['message'])
.to match(/Validation failed: Password can't be blank, Name can't be blank, Email can't be blank, Password digest can't be blank/)
end
end
end
end
| 28.113636 | 140 | 0.660469 |
281df2dfa2c1d5fc3743f3f970fef691b1e29041 | 3,867 | module ConfigurationScriptHelper
include TextualMixins::TextualGroupTags
def textual_group_properties
TextualGroup.new(
_("Properties"),
%i[hostname ipmi_present ipaddress mac_address provider_name zone]
)
end
def textual_hostname
{:label => _("Hostname"),
:icon => "ff ff-configured-system",
:value => @record.hostname}
end
def textual_ipmi_present
{:label => _("IPMI Present"), :value => @record.ipmi_present}
end
def textual_ipaddress
{:label => _("IP Address"), :value => @record.ipaddress}
end
def textual_mac_address
{:label => _("Mac address"), :value => @record.mac_address}
end
def textual_provider_name
{:label => _("Provider"),
:image => @record.configuration_manager.decorate.fileicon,
:value => @record.configuration_manager.try(:name),
:explorer => true}
end
def textual_zone
{:label => _("Zone"), :value => @record.configuration_manager.my_zone}
end
def textual_inventory_group_properties
%i[inventory_group_name
inventory_group_region]
end
def textual_inventory_group_name
{:label => _("Name"), :value => @record.name}
end
def textual_inventory_group_region
{:label => _("Region"), :value => @record.region_description}
end
def textual_inventory_group_architecture
{:label => _("Architecture"), :value => @record.configuration_architecture_name}
end
def textual__inventory_group_os
{:label => _("OS"), :value => @record.operating_system_flavor_name}
end
def textual_inventory_group_medium
{:label => _("Medium"), :value => @record.customization_script_medium_name}
end
def textual_inventory_group_partition_table
{:label => _("Partition Table"), :value => @record.customization_script_ptable_name}
end
def textual_configuration_script_group_properties
%i[configuration_script_name
configuration_script_region]
end
def textual_configuration_script_name
{:label => _("Name"), :value => @record.name}
end
def textual_configuration_script_region
{:label => _("Region"), :value => @record.region_description}
end
def textual_configuration_script_variables
textual_variables(@record.variables)
end
def textual_configuration_script_survey
textual_survey_group(@record.survey_spec['spec'])
end
def textual_configuration_script_group_os
%i[configuration_script_medium
configuration_script_partition_table]
end
def textual_survey_group(items)
return unless items
h = {:title => _("Surveys"),
:headers => [_('Question Name'), _('Question Description'), _('Variable'),
_('Type'), _('Min'), _('Max'), _('Default'), _('Required'), _('Choices')],
:col_order => %w[question_name question_description variable type min max default required choices]}
h[:value] = items.collect do |item|
{
:title => item['index'],
:question_name => item['question_name'],
:question_description => item['question_description'],
:variable => item['variable'],
:type => item['type'],
:min => item['min'],
:max => item['max'],
:default => item['default'],
:required => item['required'],
:choices => item['choices']
}
end
h
end
def textual_variables(vars)
return unless vars
h = {:title => _("Variables"),
:headers => [_('Name'), _('Value')],
:col_order => %w[name value]}
h[:value] = vars.collect do |item|
{
:name => item[0].to_s,
:value => item[1].to_s
}
end
h
end
def textual_group_smart_management
TextualTags.new(_("Smart Management"), %i[tags])
end
end
#
| 28.226277 | 109 | 0.633307 |
ff4aa6db79ca31cb28a383adbae864006801fce3 | 1,618 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::AlertsManagement::Mgmt::V2018_05_05_preview
module Models
#
# Summary of alerts by state
#
class AlertsSummaryPropertiesSummaryByState < AlertsSummaryByState
include MsRestAzure
#
# Mapper for AlertsSummaryPropertiesSummaryByState class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'alertsSummaryProperties_summaryByState',
type: {
name: 'Composite',
class_name: 'AlertsSummaryPropertiesSummaryByState',
model_properties: {
new: {
client_side_validation: true,
required: false,
serialized_name: 'new',
type: {
name: 'Number'
}
},
acknowledged: {
client_side_validation: true,
required: false,
serialized_name: 'acknowledged',
type: {
name: 'Number'
}
},
closed: {
client_side_validation: true,
required: false,
serialized_name: 'closed',
type: {
name: 'Number'
}
}
}
}
}
end
end
end
end
| 27.423729 | 76 | 0.510507 |
e85702a020101ac4bb982d644366ba1f89c0d2c1 | 120 | require "quick_search/blacklight/engine"
module QuickSearch
module Blacklight
# Your code goes here...
end
end
| 15 | 40 | 0.75 |
1c136c5066530bb4cc3289dbe43f7930cf164d91 | 1,234 | =begin
#Datadog API V1 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 'date'
require 'time'
module DatadogAPIClient::V1
class ApmStatsQueryRowType
SERVICE = "service".freeze
RESOURCE = "resource".freeze
SPAN = "span".freeze
# Builds the enum from string
# @param [String] The enum value in the form of the string
# @return [String] The enum value
def self.build_from_hash(value)
new.build_from_hash(value)
end
# Builds the enum from string
# @param [String] The enum value in the form of the string
# @return [String] The enum value
def build_from_hash(value)
constantValues = ApmStatsQueryRowType.constants.select { |c| ApmStatsQueryRowType::const_get(c) == value }
raise "Invalid ENUM value #{value} for class #ApmStatsQueryRowType" if constantValues.empty?
value
end
end
end
| 29.380952 | 112 | 0.730956 |
ed0ae18307648b500c1dfdf52f3d581cb8ea08ed | 361 | name 'barricade'
maintainer 'Barricade Security Systems Limited'
maintainer_email '[email protected]'
license 'Simplified 2-Clause BSD License'
description 'Installs/Configures the barricade agent'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.0'
supports 'ubuntu'
| 40.111111 | 72 | 0.700831 |
acb89ce3ccc0de38ce16c9ae57b4f3b6d6e7cd1d | 5,538 | require_relative "../spec"
describe SparkleFormation::SparkleCollection do
describe "Basic behavior" do
before do
@collection = SparkleFormation::SparkleCollection.new
end
let(:collection) { @collection }
let(:root_pack) {
SparkleFormation::Sparkle.new(
:root => File.join(File.dirname(__FILE__), "sparkleformation"),
)
}
let(:extra_pack) {
SparkleFormation::Sparkle.new(
:root => File.join(File.dirname(__FILE__), "packs", "valid_pack"),
)
}
it "should return empty when it has no contents" do
collection.empty?.must_equal true
end
it "should have no size when empty" do
collection.size.must_equal 0
end
it "should register root pack at index 0" do
collection.set_root(root_pack).must_equal collection
collection.sparkle_at(0).must_equal root_pack
end
it "should accept additional packs" do
collection.set_root(root_pack).must_equal collection
collection.add_sparkle(extra_pack).must_equal collection
collection.sparkle_at(0).must_equal extra_pack
collection.sparkle_at(1).must_equal root_pack
end
it "should allow removal of packs" do
collection.set_root(root_pack).must_equal collection
collection.add_sparkle(extra_pack).must_equal collection
collection.size.must_equal 2
collection.remove_sparkle(extra_pack).must_equal collection
collection.size.must_equal 1
end
it "should provide templates when contained within pack" do
collection.set_root(root_pack)
collection.templates.wont_be :empty?
end
it "should apply empty settings to other collection" do
new_collection = SparkleFormation::SparkleCollection.new
new_collection.apply(collection)
new_collection.send(:sparkles).must_equal collection.send(:sparkles)
end
it "should apply settings to other collection" do
collection.set_root(root_pack).add_sparkle(extra_pack)
new_collection = SparkleFormation::SparkleCollection.new
new_collection.apply(collection)
new_collection.send(:sparkles).must_equal collection.send(:sparkles)
end
end
describe SparkleFormation::SparkleCollection::Rainbow do
before do
@rainbow = SparkleFormation::SparkleCollection::Rainbow.new(:dummy, :component)
end
let(:rainbow) { @rainbow }
it "should have a name" do
rainbow.name.must_equal "dummy"
end
it "should have a type" do
rainbow.type.must_equal :component
end
it "should have an empty spectrum" do
rainbow.spectrum.must_be :empty?
end
it "should act like a hash" do
rainbow.empty?.must_equal true
rainbow[:item].must_be_nil
end
it "should error when created with invalid type" do
-> {
SparkleFormation::SparkleCollection::Rainbow.new(:test, :invalid)
}.must_raise ArgumentError
end
it "should error when invalid type added as layer" do
-> { rainbow.add_layer(:symbol) }.must_raise TypeError
end
it "should allow adding layers" do
rainbow.add_layer(:one => true).add_layer(:two => true).must_equal rainbow
end
it "should access top layer when used as a hash" do
rainbow.add_layer(:one => true).add_layer(:two => true)
rainbow[:one].must_be_nil
rainbow[:two].must_equal true
end
it "should collapse spectrum to just top layer when no merging" do
rainbow.add_layer(:one => true).add_layer(:two => true)
rainbow.monochrome.must_equal ["two" => true]
end
it "should collapse spectrum to just last merging layers" do
rainbow.add_layer(:one => true).add_layer(:two => true, :args => {:layering => :merge})
rainbow.add_layer(:three => true).add_layer(:four => true, :args => {:layering => :merge})
rainbow.monochrome.must_equal [
{"three" => true},
{"four" => true, "args" => {"layering" => :merge}},
]
end
it "should allow layer access by index" do
rainbow.add_layer(:one => true).add_layer(:two => true, :args => {:layering => :merge})
rainbow.add_layer(:three => true).add_layer(:four => true, :args => {:layering => :merge})
rainbow.layer_at(0).must_equal "one" => true
rainbow.layer_at(2).must_equal "three" => true
end
end
describe "Provider specific loading" do
before do
@collection = SparkleFormation::SparkleCollection.new
@collection.set_root(
SparkleFormation::Sparkle.new(
:root => File.join(
File.dirname(__FILE__), "packs", "valid_pack"
),
)
)
@collection
end
it "should load AWS by default" do
template = @collection.get(:template, :stack)
template = SparkleFormation.compile(template[:path], :sparkle)
template.sparkle.apply @collection
result = template.dump.to_smash
result["AwsTemplate"].must_equal true
result["AwsDynamic"].must_equal true
result["Registry"].must_equal "aws"
result["SharedItem"].must_equal "shared"
end
it "should load HEAT when defined as provider" do
template = @collection.get(:template, :stack, :heat)
template = SparkleFormation.compile(template[:path], :sparkle)
template.sparkle.apply @collection
result = template.dump.to_smash
result["heat_template"].must_equal true
result["heat_dynamic"].must_equal true
result["registry"].must_equal "heat"
result["shared_item"].must_equal "shared"
end
end
end
| 32.576471 | 96 | 0.673709 |
1cfc8a02bd7e6b3a34816874f37a8fcac3068f2d | 334 | require "active_model/type"
require "active_record/type"
require "tod/time_of_day_type"
module Tod
class Railtie < Rails::Railtie
initializer "tod.register_active_model_type" do
ActiveModel::Type.register(:time_only, Tod::TimeOfDayType)
ActiveRecord::Type.register(:time_only, Tod::TimeOfDayType)
end
end
end
| 25.692308 | 65 | 0.760479 |
f8e2e20c10a143b0e786e2a7c02d718147fd58be | 1,355 | # -*- coding: utf-8 -*-
# /(^o^)\
require File.expand_path(File.dirname(__FILE__+'/utils'))
miquire :core, 'environment', 'serialthread', 'skin'
miquire :mui, 'web_image_loader'
require 'gtk2'
require 'observer'
# Web上の画像をレンダリングできる。
# レンダリング中は読み込み中の代替イメージが表示され、ロードが終了したら指定された画像が表示される。
# メモリキャッシュ、ストレージキャッシュがついてる。
module Gtk
class WebIcon < Image
DEFAULT_RECTANGLE = Gdk::Rectangle.new(0, 0, 48, 48)
include Observable
# ==== Args
# [url] 画像のURLもしくはパス(String)
# [rect] 画像のサイズ(Gdk::Rectangle) または幅(px)
# [height] 画像の高さ(px)
def initialize(url, rect = DEFAULT_RECTANGLE, height = nil)
rect = Gdk::Rectangle.new(0, 0, rect, height) if height
if(Gdk::WebImageLoader.is_local_path?(url))
url = File.expand_path(url)
if FileTest.exist?(url)
super begin
Gdk::Pixbuf.new(url, rect.width, rect.height)
rescue
Gdk::WebImageLoader.notfound_pixbuf(rect.width, rect.height) end
else
super(Gdk::WebImageLoader.notfound_pixbuf(rect.width, rect.height)) end
else
super(Gdk::WebImageLoader.pixbuf(url, rect.width, rect.height) { |pixbuf, success|
unless destroyed?
self.pixbuf = pixbuf
self.changed
self.notify_observers end }) end end
end
end
| 30.795455 | 90 | 0.628044 |
f85f6184494637f955110ff43d6e489a78772267 | 1,740 | #
# Be sure to run `pod lib lint CustomUIWidget.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'CustomUIWidget'
s.version = '0.2.1'
s.summary = '可自定义配置使用的ui组件库.'
# 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
TODO: 此工程将日常使用频繁的ui组件集合到一起,同时各ui组件均可进行不同的自定义定制,满足大部分的需求场景.
DESC
s.homepage = 'https://github.com/lucyDad/CustomUIWidget'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'lucyDad' => '[email protected]' }
s.source = { :git => 'https://github.com/lucyDad/CustomUIWidget.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '9.0'
s.source_files = 'CustomUIWidget/Classes/**/*'
# s.resource_bundles = {
# 'CustomUIWidget' => ['CustomUIWidget/Assets/*.png']
# }
s.public_header_files = 'Pod/Classes/Public/**/*.h'
s.frameworks = 'UIKit', 'Foundation'
s.dependency 'Masonry'
s.dependency 'YYCategories'
s.dependency 'YYText'
s.dependency 'YYModel'
s.dependency 'YYWebImage'
s.dependency 'libextobjc'
end
| 36.25 | 106 | 0.659195 |
b941582016b0063e02b606b796a0992614d41653 | 645 | Pod::Spec.new do |s|
s.name = "TransitionableTab"
s.version = "0.2.0"
s.summary = "between tab animation"
s.description = "TransitionableTab makes it easy to animate when switching between tab"
s.homepage = "https://github.com/Interactive-Studio/TransitionableTab"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "gwangbeom" => "[email protected]" }
s.ios.deployment_target = "8.0"
s.source = { :git => "https://github.com/Interactive-Studio/TransitionableTab.git", :tag => s.version.to_s }
s.source_files = "Sources/**/*"
s.frameworks = "Foundation"
end
| 46.071429 | 116 | 0.629457 |
abd016a6dfe8cdd5d76e7a3ccab5483064c5f5fc | 158 | if __FILE__ == $0
dir = File.dirname(__FILE__)
Dir["#{dir}/**/*_spec.rb"].reverse.each do |file|
# puts "require '#{file}'"
require file
end
end
| 19.75 | 51 | 0.601266 |
08277a7633672ebca32a41f5f2ae8d06aea78f56 | 577 | module ProsperWorks
class Client
extend Forwardable
API_VERSION_NUMBER = 1
def headers
{
"Content-Type": "application/json",
"X-PW-Application": "developer_api",
"X-PW-UserEmail": configuration.user_email,
"X-PW-AccessToken": configuration.access_token
}
end
def base_url
"https://api.prosperworks.com/developer_api/v#{API_VERSION_NUMBER}/"
end
def configure
yield configuration if block_given?
end
def configuration
@configuration ||= Configuration.new
end
end
end | 19.896552 | 74 | 0.64818 |
0843f08c9a650886071286405fe6a6351e78a587 | 3,179 | # -*- coding: binary -*-
require 'msf/base'
module Msf
module Simple
###
#
# Wraps interaction with a generated buffer from the framework.
# Its primary use is to transform a raw buffer into another
# format.
#
###
module Buffer
#
# Serializes a buffer to a provided format. The formats supported are raw,
# num, dword, ruby, python, perl, bash, c, js_be, js_le, java and psh
#
def self.transform(buf, fmt = "ruby", var_name = 'buf')
default_wrap = 60
case fmt
when 'raw'
when 'num'
buf = Rex::Text.to_num(buf)
when 'hex'
buf = Rex::Text.to_hex(buf, '')
when 'dword', 'dw'
buf = Rex::Text.to_dword(buf)
when 'python', 'py'
buf = Rex::Text.to_python(buf, default_wrap, var_name)
when 'ruby', 'rb'
buf = Rex::Text.to_ruby(buf, default_wrap, var_name)
when 'perl', 'pl'
buf = Rex::Text.to_perl(buf, default_wrap, var_name)
when 'bash', 'sh'
buf = Rex::Text.to_bash(buf, default_wrap, var_name)
when 'c'
buf = Rex::Text.to_c(buf, default_wrap, var_name)
when 'csharp'
buf = Rex::Text.to_csharp(buf, default_wrap, var_name)
when 'js_be'
buf = Rex::Text.to_unescape(buf, ENDIAN_BIG)
when 'js_le'
buf = Rex::Text.to_unescape(buf, ENDIAN_LITTLE)
when 'java'
buf = Rex::Text.to_java(buf, var_name)
when 'powershell', 'ps1'
buf = Rex::Text.to_powershell(buf, var_name)
when 'vbscript'
buf = Rex::Text.to_vbscript(buf, var_name)
when 'vbapplication'
buf = Rex::Text.to_vbapplication(buf, var_name)
else
raise ArgumentError, "Unsupported buffer format: #{fmt}", caller
end
return buf
end
#
# Creates a comment using the supplied format. The formats supported are
# raw, ruby, python, perl, bash, js_be, js_le, c, and java.
#
def self.comment(buf, fmt = "ruby")
case fmt
when 'raw'
when 'num', 'dword', 'dw', 'hex'
buf = Rex::Text.to_js_comment(buf)
when 'ruby', 'rb', 'python', 'py'
buf = Rex::Text.to_ruby_comment(buf)
when 'perl', 'pl'
buf = Rex::Text.to_perl_comment(buf)
when 'bash', 'sh'
buf = Rex::Text.to_bash_comment(buf)
when 'c'
buf = Rex::Text.to_c_comment(buf)
when 'csharp'
buf = Rex::Text.to_c_comment(buf)
when 'js_be', 'js_le'
buf = Rex::Text.to_js_comment(buf)
when 'java'
buf = Rex::Text.to_c_comment(buf)
else
raise ArgumentError, "Unsupported buffer format: #{fmt}", caller
end
return buf
end
#
# Returns the list of supported formats
#
def self.transform_formats
[
'bash',
'c',
'csharp',
'dw',
'dword',
'hex',
'java',
'js_be',
'js_le',
'num',
'perl',
'pl',
'powershell',
'ps1',
'py',
'python',
'raw',
'rb',
'ruby',
'sh',
'vbapplication',
'vbscript'
]
end
end
end
end
| 25.031496 | 78 | 0.54514 |
913c712c1199e3380cbcbced0b54cf1b4393ae5e | 2,366 | RSpec.describe Airbrake::NestedException do
describe "#as_json" do
context "given exceptions with backtraces" do
it "unwinds nested exceptions" do
begin
begin
raise AirbrakeTestError
rescue AirbrakeTestError
Ruby21Error.raise_error('bingo')
end
rescue Ruby21Error => ex
nested_exception = described_class.new(ex)
exceptions = nested_exception.as_json
expect(exceptions.size).to eq(2)
expect(exceptions[0][:message]).to eq('bingo')
expect(exceptions[1][:message]).to eq('App crashed!')
expect(exceptions[0][:backtrace]).not_to be_empty
expect(exceptions[1][:backtrace]).not_to be_empty
end
end
it "unwinds no more than 3 nested exceptions" do
begin
begin
raise AirbrakeTestError
rescue AirbrakeTestError
begin
Ruby21Error.raise_error('bongo')
rescue Ruby21Error
begin
Ruby21Error.raise_error('bango')
rescue Ruby21Error
Ruby21Error.raise_error('bingo')
end
end
end
rescue Ruby21Error => ex
nested_exception = described_class.new(ex)
exceptions = nested_exception.as_json
expect(exceptions.size).to eq(3)
expect(exceptions[0][:message]).to eq('bingo')
expect(exceptions[1][:message]).to eq('bango')
expect(exceptions[2][:message]).to eq('bongo')
expect(exceptions[0][:backtrace]).not_to be_empty
expect(exceptions[1][:backtrace]).not_to be_empty
end
end
end
context "given exceptions without backtraces" do
it "sets backtrace to nil" do
begin
begin
raise AirbrakeTestError
rescue AirbrakeTestError => ex2
ex2.set_backtrace([])
Ruby21Error.raise_error('bingo')
end
rescue Ruby21Error => ex1
ex1.set_backtrace([])
nested_exception = described_class.new(ex1)
exceptions = nested_exception.as_json
expect(exceptions.size).to eq(2)
expect(exceptions[0][:backtrace]).to be_empty
expect(exceptions[1][:backtrace]).to be_empty
end
end
end
end
end
| 31.972973 | 63 | 0.586644 |
262994b06c476efef0cea6f0b741ff2a6580463b | 525 | class AddAttributesToSchools < ActiveRecord::Migration
def change
add_column :schools, :bpsid, :integer
add_column :schools, :org_code, :integer
add_column :schools, :teachers_count, :integer
add_column :schools, :core_areas_teachers_count, :integer
add_column :schools, :licensed_teachers_percentage, :float
add_column :schools, :qualified_teachers_percentage, :float
add_column :schools, :qualified_classes_percentage, :float
add_column :schools, :staff_to_student_ratio, :float
end
end
| 40.384615 | 63 | 0.773333 |
e99d720058a5a83872aade0c9634e448c0280254 | 6,030 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::Usage::MetricDefinition do
let(:attributes) do
{
description: 'GitLab instance unique identifier',
value_type: 'string',
product_category: 'collection',
product_stage: 'growth',
status: 'data_available',
default_generation: 'generation_1',
key_path: 'uuid',
product_group: 'group::product analytics',
time_frame: 'none',
data_source: 'database',
distribution: %w(ee ce),
tier: %w(free starter premium ultimate bronze silver gold),
name: 'count_boards'
}
end
let(:path) { File.join('metrics', 'uuid.yml') }
let(:definition) { described_class.new(path, attributes) }
let(:yaml_content) { attributes.deep_stringify_keys.to_yaml }
def write_metric(metric, path, content)
path = File.join(metric, path)
dir = File.dirname(path)
FileUtils.mkdir_p(dir)
File.write(path, content)
end
it 'has all definitons valid' do
expect { described_class.definitions }.not_to raise_error(Gitlab::Usage::Metric::InvalidMetricError)
end
describe '#key' do
subject { definition.key }
it 'returns a symbol from name' do
is_expected.to eq('uuid')
end
end
describe '#validate' do
using RSpec::Parameterized::TableSyntax
where(:attribute, :value) do
:description | nil
:value_type | nil
:value_type | 'test'
:status | nil
:key_path | nil
:product_group | nil
:time_frame | nil
:time_frame | '29d'
:data_source | 'other'
:data_source | nil
:distribution | nil
:distribution | 'test'
:tier | %w(test ee)
:name | 'count_<adjective_describing>_boards'
end
with_them do
before do
attributes[attribute] = value
end
it 'raise exception' do
expect(Gitlab::ErrorTracking).to receive(:track_and_raise_for_dev_exception).at_least(:once).with(instance_of(Gitlab::Usage::Metric::InvalidMetricError))
described_class.new(path, attributes).validate!
end
context 'with skip_validation' do
it 'raise exception if skip_validation: false' do
expect(Gitlab::ErrorTracking).to receive(:track_and_raise_for_dev_exception).at_least(:once).with(instance_of(Gitlab::Usage::Metric::InvalidMetricError))
described_class.new(path, attributes.merge( { skip_validation: false } )).validate!
end
it 'does not raise exception if has skip_validation: true' do
expect(Gitlab::ErrorTracking).not_to receive(:track_and_raise_for_dev_exception)
described_class.new(path, attributes.merge( { skip_validation: true } )).validate!
end
end
end
end
describe 'statuses' do
using RSpec::Parameterized::TableSyntax
where(:status, :skip_validation?) do
'deprecated' | true
'removed' | true
'data_available' | false
'implemented' | false
'not_used' | false
end
with_them do
subject(:validation) do
described_class.new(path, attributes.merge( { status: status } )).send(:skip_validation?)
end
it 'returns true/false for skip_validation' do
expect(validation).to eq(skip_validation?)
end
end
end
describe '.load_all!' do
let(:metric1) { Dir.mktmpdir('metric1') }
let(:metric2) { Dir.mktmpdir('metric2') }
let(:definitions) { {} }
before do
allow(described_class).to receive(:paths).and_return(
[
File.join(metric1, '**', '*.yml'),
File.join(metric2, '**', '*.yml')
]
)
end
subject { described_class.send(:load_all!) }
it 'has empty list when there are no definition files' do
is_expected.to be_empty
end
it 'has one metric when there is one file' do
write_metric(metric1, path, yaml_content)
is_expected.to be_one
end
it 'when the same meric is defined multiple times raises exception' do
write_metric(metric1, path, yaml_content)
write_metric(metric2, path, yaml_content)
expect(Gitlab::ErrorTracking).to receive(:track_and_raise_for_dev_exception).with(instance_of(Gitlab::Usage::Metric::InvalidMetricError))
subject
end
after do
FileUtils.rm_rf(metric1)
FileUtils.rm_rf(metric2)
end
end
describe 'dump_metrics_yaml' do
let(:other_attributes) do
{
description: 'Test metric definition',
value_type: 'string',
product_category: 'collection',
product_stage: 'growth',
status: 'data_available',
default_generation: 'generation_1',
key_path: 'counter.category.event',
product_group: 'group::product analytics',
time_frame: 'none',
data_source: 'database',
distribution: %w(ee ce),
tier: %w(free starter premium ultimate bronze silver gold)
}
end
let(:other_yaml_content) { other_attributes.deep_stringify_keys.to_yaml }
let(:other_path) { File.join('metrics', 'test_metric.yml') }
let(:metric1) { Dir.mktmpdir('metric1') }
let(:metric2) { Dir.mktmpdir('metric2') }
before do
allow(described_class).to receive(:paths).and_return(
[
File.join(metric1, '**', '*.yml'),
File.join(metric2, '**', '*.yml')
]
)
# Reset memoized `definitions` result
described_class.instance_variable_set(:@definitions, nil)
end
after do
FileUtils.rm_rf(metric1)
FileUtils.rm_rf(metric2)
end
subject { described_class.dump_metrics_yaml }
it 'returns a YAML with both metrics in a sequence' do
write_metric(metric1, path, yaml_content)
write_metric(metric2, other_path, other_yaml_content)
is_expected.to eq([attributes, other_attributes].map(&:deep_stringify_keys).to_yaml)
end
end
end
| 29.271845 | 163 | 0.635655 |
1d72dbc63f82f5cc6068c4efc1584f854d692d66 | 506 | # frozen_string_literal: true
class PostMessageToKikService
def initialize(message, token, uid)
@message = message
@token = token
@uid = uid
end
def call
kik_client.call('message', 'POST', options)
end
private
attr_reader :message, :token, :uid
def kik_client
@_kik_client ||= Kik.new(token, uid)
end
def options
{
messages: [
{
body: message.text,
to: message.user,
type: 'text'
}
]
}
end
end
| 14.882353 | 47 | 0.573123 |
e2994bdd99d4f83e1d110a84c8fde2898005ccd7 | 162 | FactoryBot.define do
factory :sys_site, class: Sys::Site do
name { "sys" }
host { "test-sys" }
domains { "test-sys.com" }
#group_id 1
end
end
| 18 | 40 | 0.598765 |
f7a1cec4519e31d3dbe5299d1005967b559a496a | 2,630 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "adserver_#{Rails.env}"
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
end
| 39.253731 | 96 | 0.756654 |
abaf6117bb86f61b8d6082328828229f456d0c6f | 1,025 | require 'helper'
class TestConfiguration < Test::Unit::TestCase
context "loading configuration" do
setup do
@path = File.join(Dir.pwd, '_config.yml')
end
should "fire warning with no _config.yml" do
mock(YAML).safe_load_file(@path) { raise SystemCallError, "No such file or directory - #{@path}" }
mock($stderr).puts("Configuration file: none")
assert_equal Jekyll::DEFAULTS, Jekyll.configuration({})
end
should "load configuration as hash" do
mock(YAML).safe_load_file(@path) { Hash.new }
mock($stdout).puts("Configuration file: #{@path}")
assert_equal Jekyll::DEFAULTS, Jekyll.configuration({})
end
should "fire warning with bad config" do
mock(YAML).safe_load_file(@path) { Array.new }
mock($stderr).puts(" WARNING: Error reading configuration. Using defaults (and options).")
mock($stderr).puts("Configuration file: (INVALID) #{@path}")
assert_equal Jekyll::DEFAULTS, Jekyll.configuration({})
end
end
end
| 35.344828 | 106 | 0.668293 |
62edfd63d62369504a26c55aad0e3060652f56c4 | 120 | require 'test_helper'
class MeganeTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 15 | 42 | 0.7 |
ab0870742a148d3edcc4a37caaf06a580f5b795e | 863 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'The photographer field of the item display view', :clean, type: :system do
before do
solr = Blacklight.default_index.connection
solr.add(work_attributes)
solr.commit
end
let(:ark) { 'ark:/123/photographer_display' }
let(:solr_id) { ark.sub('ark:/', '').sub('/', '-').reverse }
let(:work_attributes) do
{
id: solr_id,
ark_ssi: ark,
photographer_tesim: ['photographer1'],
read_access_group_ssim: ["public"],
has_model_ssim: ['Work']
}
end
it 'lists the photographer as a link to a search for that photographer' do
visit("/catalog/#{ark}")
page.within('dd.blacklight-photographer_tesim') do
expect(page).to have_link('photographer1', href: '/catalog?f%5Bphotographer_sim%5D%5B%5D=photographer1')
end
end
end
| 26.96875 | 110 | 0.674392 |
79d59aa4549960b433270e68349f27081e3664ba | 139 | require 'test_helper'
describe NewsController, :locale do
it "gets index" do
get news_path
must_respond_with :success
end
end
| 15.444444 | 35 | 0.741007 |
21fc983fb1b0f1f51fa33736d3dcc2f7fb867082 | 1,893 | class Crc32c < Formula
desc "Implementation of CRC32C with CPU-specific acceleration"
homepage "https://github.com/google/crc32c"
url "https://github.com/google/crc32c/archive/1.1.1.tar.gz"
sha256 "a6533f45b1670b5d59b38a514d82b09c6fb70cc1050467220216335e873074e8"
license "BSD-3-Clause"
head "https://github.com/google/crc32c.git"
bottle do
sha256 cellar: :any, arm64_big_sur: "82e70741895a3e29dc0f8e48b0dd10e13e8cd380012457c1bf984ace3fd6dd03"
sha256 cellar: :any, big_sur: "a37c7daabc55476ee3828211b32a63f052af9feeff1430fe53be9cef2038a069"
sha256 cellar: :any, catalina: "8ac4299583c3155c0410e246277214110bbbe453df5cc6b67694c67ba722bfbc"
sha256 cellar: :any, mojave: "f5e232ed8a57eea6b226f4596f94281ea4ea5467c626e83a1576e74aee32711e"
sha256 cellar: :any, high_sierra: "a8f21980c0fee7ffb9911b1eaa1bf7641940b4bb798a7dbd508ae60a6c1a46a8"
end
depends_on "cmake" => :build
def install
system "cmake", ".", "-DCRC32C_BUILD_TESTS=0",
"-DCRC32C_BUILD_BENCHMARKS=0", "-DCRC32C_USE_GLOG=0",
*std_cmake_args
system "make", "install"
system "make", "clean"
system "cmake", ".", "-DBUILD_SHARED_LIBS=ON", "-DCRC32C_BUILD_TESTS=0",
"-DCRC32C_BUILD_BENCHMARKS=0", "-DCRC32C_USE_GLOG=0",
*std_cmake_args
system "make", "install"
end
test do
(testpath/"test.cpp").write <<~EOS
#include <cassert>
#include <crc32c/crc32c.h>
#include <cstdint>
#include <string>
int main()
{
std::uint32_t expected = 0xc99465aa;
std::uint32_t result = crc32c::Crc32c(std::string("hello world"));
assert(result == expected);
return 0;
}
EOS
system ENV.cxx, "test.cpp", "-I#{include}", "-L#{lib}", "-lcrc32c", "-o", "test"
system "./test"
end
end
| 37.117647 | 106 | 0.665082 |
e251b445223f24216fc10d2ad33ed56009a791b7 | 324 | # frozen_string_literal: true
FactoryBot.define do
factory :conviction_reason_form do
revoked_reason { "foo" }
initialize_with do
new(create(:renewing_registration,
:requires_conviction_check,
workflow_state: "renewal_received_pending_conviction_form"))
end
end
end
| 23.142857 | 77 | 0.697531 |
39828967433014acf262e056e9adbd35349c26a4 | 1,113 | require_relative "../test_helper"
describe Yahoofx::Converter do
before do
mock_eur_dkk_bid = MiniTest::Mock.new
mock_eur_dkk_bid.expect(:bid, 7.4556)
mock_rate_pair_class = MiniTest::Mock.new
mock_rate_pair_class.expect(:new, mock_eur_dkk_bid, ['EUR', 'DKK'])
@converter = Yahoofx::Converter.new(mock_rate_pair_class)
end
it "should convert amount from one to the other" do
assert_equal 745.56, @converter.convert("100 EUR in DKK").to_f
end
describe "when calling answer method" do
it "should convert amount when it looks like a conversion" do
assert_equal 745.56, @converter.answer("100 EUR in DKK").to_f
end
it "should work the same without space between amount and 'from currency'" do
assert_equal 745.56, @converter.answer("100EUR in DKK").to_f
end
it "should show currency rate when two valid currency codes are provided" do
assert_equal 7.4556, @converter.answer("EURDKK").to_f
end
it "should work with decimal in amount" do
assert_equal 11.92896, @converter.answer("1.6EUR in DKK").to_f
end
end
end
| 32.735294 | 81 | 0.709793 |
1dd472ed17a731ea997ed591ad82ea3b1b9f1d5b | 1,006 | class Mustang < Formula
# cite Konagurthu_2006: "https://doi.org/10.1002/prot.20921"
desc "Multiple structural alignment algorithm"
homepage "https://lcb.infotech.monash.edu/mustang/"
url "https://lcb.infotech.monash.edu/mustang/mustang_v3.2.3.tgz"
sha256 "f1c8d64acc04c70e30b3128c370e485438eb38db96b1b3180d31eaa24a52704a"
license "BSD-3-Clause"
bottle do
root_url "https://ghcr.io/v2/brewsci/bio"
sha256 cellar: :any_skip_relocation, catalina: "466f19e29390334352ef8b330dd0f5c54e211dcff02a62ca7eea507f600aec86"
sha256 cellar: :any_skip_relocation, x86_64_linux: "defaa2d7344845564154baa2e2bf6ffaecb4186936cca25e620926017d3f09f9"
end
uses_from_macos "zlib"
def install
inreplace "Makefile", "-traditional", "" if OS.mac?
inreplace "Makefile", "mustang-3.2.3", "mustang"
system "make"
bin.install "bin/mustang"
man1.install "man/mustang.1"
end
test do
assert_match "A MUltiple STuructural", shell_output("#{bin}/mustang --help")
end
end
| 34.689655 | 121 | 0.751491 |
abcfb3d501a8b1a6b862d327e455e65999046674 | 406 | # frozen_string_literal: true
require 'yaml'
require 'json'
require 'pathname'
require 'rspec'
require 'rspec_file_fixtures/version'
require 'rspec_file_fixtures/fixture'
# Provides a `fixture` method in all RSpec tests.
module RSpecFileFixtures
class Error < StandardError; end
def fixture(path)
Fixture.new(path)
end
end
RSpec.configure do |config|
config.include(RSpecFileFixtures)
end
| 17.652174 | 49 | 0.775862 |
7a1462ae981339735621e6cddb4f92f91ccbcadf | 6,476 | require 'test/unit'
require 'external/test_support'
IWATestSupport.set_src_dir
require 'iowa/caches/DiskCache'
require 'iowa/caches/DiskStore'
require 'tmpdir'
require 'fileutils'
require 'benchmark'
require 'pstore'
TMPDIR = Dir::tmpdir
class TC_DiskCache < Test::Unit::TestCase
def make_tmpdir_path; FileUtils.mkdir("#{TMPDIR}/tc_diskcache.#{Time.now.to_i}#{rand}").first; end
def make_shm_tmpdir_path; FileUtils.mkdir("/dev/shm/tc_diskcache.#{Time.now.to_i}#{rand}").first; end
@@testdir = IWATestSupport.test_dir(__FILE__)
def setup
Dir.chdir(@@testdir)
IWATestSupport.announce(:diskcache,"Iowa::Caches::DiskCache / Iowa::Caches::DiskStore")
end
def test_creation
tmpdir = make_tmpdir_path
assert_nothing_raised("Failed while creating an Iowa::Caches::DiskCache object") do
@cache = Iowa::Caches::DiskCache.new({:directory => tmpdir, :maxsize => 12})
end
FileUtils.rm_rf(tmpdir)
end
def test_cache_size
tmpdir = make_tmpdir_path
@cache = Iowa::Caches::DiskCache.new({:directory => tmpdir, :maxsize => 12})
(1..14).each {|n| @cache[n] = n}
s = @cache.size
assert_equal(12,s,"The expected size (12) did not match the returned size (#{s}).")
FileUtils.rm_rf(tmpdir)
end
def test_cache_size2
tmpdir = make_tmpdir_path
@cache = Iowa::Caches::DiskCache.new({:directory => tmpdir, :maxsize => 12})
(1..14).each {|n| @cache[n] = n}
@cache.size=3
s = @cache.size
assert_equal(3,s,"The cache size does not appear to to have change as expected; want size of 3, have size of #{s}.")
FileUtils.rm_rf(tmpdir)
end
def test_values
tmpdir = make_tmpdir_path
@cache = Iowa::Caches::DiskCache.new({:directory => tmpdir, :maxsize => 3})
@cache['a'] = 1
@cache['b'] = 2
@cache['c'] = 3
s = @cache['b']
assert_equal(2,s,"The value retrieved from the cache (#{s}) did not match what was expected (2).")
FileUtils.rm_rf(tmpdir)
end
def test_expire1
tmpdir = make_tmpdir_path
@cache = Iowa::Caches::DiskCache.new({:directory => tmpdir, :maxsize => 3})
@cache['a'] = 1
@cache['b'] = 2
@cache['c'] = 3
s = @cache['b']
@cache['d'] = 4
s = true
s = false if @cache.include? 'a'
assert_equal(true,s,"Key 'a' should have fallen out of the cache. It did not.")
FileUtils.rm_rf(tmpdir)
end
def test_expire2
tmpdir = make_tmpdir_path
@cache = Iowa::Caches::DiskCache.new({:directory => tmpdir, :maxsize => 3})
@cache['a'] = 1
@cache['b'] = 2
@cache['c'] = 3
s = @cache['b']
@cache['d'] = 4
s = false
s = true if @cache.include? 'b'
assert_equal(true,s,"Key 'b' appears to have fallen out of the cache. It should not have.")
FileUtils.rm_rf(tmpdir)
end
def test_transactions
tmpdir = make_tmpdir_path
@cache = Iowa::Caches::DiskCache.new({:directory => tmpdir, :maxsize => 20})
assert_nothing_raised("Something blew up when trying to test transactions.") do
@cache[:a] = 1
@cache[:b] = 2
@cache.transaction do
@cache[:c] = 3
end
assert_equal(3,@cache[:c],"Transaction failed.")
@cache.transaction do
@cache[:d] = 4
@cache.commit
@cache[:e] = 5
end
assert_equal(4,@cache[:d],"Transaction failed.")
assert_equal(5,@cache[:e],"Transaction failed.")
@cache.transaction do
@cache[:f] = 6
@cache.rollback
end
assert([email protected]?(:f),"Transaction rollback failed.")
@cache.transaction do
@cache[:f] = 6
@cache.rollback
@cache[:g] = 6
end
assert([email protected]?(:f),"Transaction rollback failed.")
assert_equal(6,@cache[:g],"Transaction failed.")
@cache.transaction do
@cache[:h] = 7
@cache.transaction do
@cache[:i] = 8
@cache.transaction do
@cache[:j] = 9
@cache.rollback
end
@cache.transaction do
@cache[:k] = 9
end
@cache.rollback
end
end
assert([email protected]?(:j),"Nested transaction rollback(:j) failed.")
assert([email protected]?(:i),"Nexted transaction rollback(:i) failed.")
assert_equal(7,@cache[:h],"Transaction failed.")
assert_equal(9,@cache[:k],"Transaction failed.")
end
end
def test_speed
n = 2000
test_dirs = []
test_dirs << ["In-Memory (/dev/shm) Test", make_shm_tmpdir_path] if FileTest.exist?('/dev/shm') and FileTest.writable?('/dev/shm')
test_dirs << ["On Disk Test (performance directly related to disk i/o performance)", make_tmpdir_path]
assert_nothing_raised("Something blew up during the DiskCache stress test.") do
test_dirs.each do |td|
puts "\n#{td[0]}"
cache = Iowa::Caches::DiskCache.new({:directory => td[1], :maxsize => 4294967296})
Benchmark.benchmark do |bm|
flush_disk
puts "Writing #{n} records to disk cache:"
bm.report('dc write') do
n.times {|x| cache[x] = x}
end
flush_disk
puts "Updating #{n} records in disk cache:"
bm.report('dc update') do
n.times {|x| cache[x] = x * 2}
end
flush_disk
puts "Reading #{n} records from disk cache:"
bm.report('dc read') do
(n).times {|x| cache[x]}
end
flush_disk
puts "Deleting #{n} records from disk cache:"
bm.report('dc delete') do
n.times {|x| cache.delete(x)}
end
flush_disk
end
FileUtils.rm_rf(td[1])
end
end
flush_disk
puts "\n\nNow Running speed comparison of DiskStore"
test_dirs = []
test_dirs << ["In-Memory (/dev/shm) Test", make_shm_tmpdir_path] if FileTest.exist?('/dev/shm') and FileTest.writable?('/dev/shm')
test_dirs << ["On Disk Test (performance directly related to disk i/o performance)", make_tmpdir_path]
assert_nothing_raised("Something blew up during the DiskCache stress test.") do
test_dirs.each do |td|
puts "\n#{td[0]}"
cache = Iowa::Caches::DiskStore.new({:directory => td[1]})
Benchmark.benchmark do |bm|
flush_disk
puts "Writing #{n} records to disk cache:"
bm.report('dc write') do
n.times {|x| cache[x] = x}
end
flush_disk
puts "Updating #{n} records in disk cache:"
bm.report('dc update') do
n.times {|x| cache[x] = x * 2}
end
flush_disk
puts "Reading #{n} records from disk cache:"
bm.report('dc read') do
(n).times {|x| cache[x]}
end
flush_disk
puts "Deleting #{n} records from disk cache:"
bm.report('dc delete') do
n.times {|x| cache.delete(x)}
end
flush_disk
end
FileUtils.rm_rf(td[1])
end
end
end
def flush_disk
if FileTest.exist?('/bin/sync')
system('/bin/sync')
end
end
end
| 29.570776 | 132 | 0.647159 |
39b0e5d9032b0ddeffa6e01ea22585aa8e55d203 | 1,350 | cask 'netbeans' do
version '8.2'
sha256 'ddcf37e91d960cca6b6a37c95eabf2c6f15330ed708bfd79be796de00da20e5e'
url "http://download.netbeans.org/netbeans/#{version}/final/bundles/netbeans-#{version}-macosx.dmg"
name 'NetBeans IDE'
homepage 'https://netbeans.org/'
pkg "NetBeans #{version}.pkg"
# Theoretically this uninstall could conflict with a separate GlassFish
# installation.
#
# In practice, it appears that the normal GlassFish installation process does
# not use the macOS installer and so isn't in the pkgutil receipts database.
#
# https://glassfish.java.net/docs/4.0/installation-guide.pdf
#
# Arguably if the GlassFish installation by NetBeans inside its own target
# directory were to conflict with a standard GlassFish installation in the
# receipts database that would be a bug upstream with NetBeans not prefixing
# its GlassFish package with "org.netbeans."
#
# If this ever becomes an issue, pkgutil: 'glassfish.*' could be moved to a
# separate "zap" stanza.
#
# The NetBeans installer does some postflight unpacking of paths installed by
# the macOS installer, so it's insufficient to just delete the paths exposed
# by pkgutil, hence the additional ":delete" option below.
uninstall pkgutil: 'org.netbeans.ide.*|glassfish.*',
delete: '/Applications/NetBeans'
end
| 39.705882 | 101 | 0.744444 |
39a44075f2876fd5d72502d8f4d3ab202d52d4af | 188 | class StoreController < ApplicationController
include Current_Cart
skip_before_action :authorize
before_action :set_cart
def index
@products = Product.order(:title)
end
end
| 18.8 | 45 | 0.781915 |
1c839cc1ffb6e14fae9f955575cbe95debdc96a0 | 892 | #
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint fair.podspec' to validate before publishing.
#
Pod::Spec.new do |s|
s.name = 'fair'
s.version = '0.0.1'
s.summary = 'A new Flutter plugin.'
s.description = <<-DESC
A new Flutter plugin.
DESC
s.homepage = 'http://example.com'
s.license = { :file => '../LICENSE' }
s.author = { 'Your Company' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.public_header_files = 'Classes/**/*.h'
s.dependency 'Flutter'
s.platform = :ios, '8.0'
# Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' }
end
| 37.166667 | 104 | 0.587444 |
03fc20a52207ae1208a424fc9224f7e790d02467 | 1,558 | RSpec.describe SiteguardLite::CustomSignature::TextDumper do
describe '.dump' do
context 'have a exclusion_action' do
let(:rule_hash) {
{
name: 'name',
comment: 'comment',
exclusion_action: 'EXCLUDE_OFFICIAL',
signature: '^.+$',
}
}
let(:rule) { SiteguardLite::CustomSignature::Rule.new(rule_hash) }
subject { SiteguardLite::CustomSignature::TextDumper.dump([rule]) }
context 'when a rule is valid' do
it 'not raise error' do
expect { subject }.not_to raise_error
end
end
context 'when a rule is invalid' do
before { rule_hash[:name] = 'a' * 30 }
it 'raise error' do
expect { subject }.to raise_error ActiveModel::ValidationError
end
end
context "when a rule's condition is invalid" do
before { rule.add_condition('URL', 'a' * 2000, ['PCRD_CASELESS']) }
it 'raise error' do
expect { subject }.to raise_error ActiveModel::ValidationError
end
end
end
context 'have no exclusion_action' do
let(:rule_hash) {
{
name: 'name',
action: 'BLOCK',
comment: 'comment',
}
}
let(:rule) { SiteguardLite::CustomSignature::Rule.new(rule_hash) }
subject { SiteguardLite::CustomSignature::TextDumper.dump([rule]) }
context 'when a rule is valid' do
it 'not raise error' do
expect { subject }.not_to raise_error
end
end
end
end
end
| 27.333333 | 75 | 0.57638 |
e93ff9cdd44ab64a8a0ffa57869d741918555424 | 3,045 | # Copyright 2012 The ham21/radio Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'rack'
require 'erb'
class Radio
class HTTP
MOUNTS = [
['', File.expand_path(File.join(File.dirname(__FILE__), '../../../www'))]
]
class Server
ENV_THREAD_BYPASS = 'radio.thread_bypass'
def initialize
@working_dir = Dir.getwd
end
# Thin can run some processes in threads if we provide the logic.
# Static files are served without deferring to a thread.
# Everything else is tried in the EventMachine thread pool.
def deferred? env
path_info = Rack::Utils.unescape(env['PATH_INFO'])
return false if path_info =~ /\.(\.|erb$)/ # unsafe '..' and '.erb'
MOUNTS.each do |path, dir|
if path_info =~ %r{^#{Regexp.escape(path)}(/.*|)$}
filename = File.join(dir, $1)
Dir.chdir @working_dir
response = FileResponse.new(env, filename)
if !response.found? and File.extname(path_info) == ''
response = FileResponse.new(env, filename + '.html')
end
if response.found?
env[ENV_THREAD_BYPASS] = response
return false
end
env[ENV_THREAD_BYPASS] = filename
end
end
return true
end
# Rack interface.
# @param (Hash) env Rack environment.
# @return (Array)[status, headers, body]
def call(env)
# The preprocessing left us with nothing, a response,
# or a filename that we should try to run.
case deferred_result = env.delete(ENV_THREAD_BYPASS)
when String
filename = deferred_result
response = Script.new(env, filename).response
if response.header["X-Cascade"] == 'pass'
index_response = Script.new(env, filename + '/index').response
response = index_response unless index_response.header["X-Cascade"] == 'pass'
end
response.finish
when NilClass
not_found
else
deferred_result.finish
end
end
# Status 404 with X-Cascade => pass.
# @return (Array)[status, headers, body]
def not_found
return @not_found if @not_found
body = "404 Not Found\n"
@not_found = [404, {'Content-Type' => 'text/plain',
'Content-Length' => body.size.to_s,
'X-Cascade' => 'pass'},
[body]]
@not_found
end
end
end
end
| 32.052632 | 89 | 0.6 |
03ddc3456c334815eccf122430fe37e2b0e4809d | 5,332 | #
# Be sure to run `pod spec lint LiveneoGaoDeSDK.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 = "LiveneoGaoDeSDK"
s.version = "0.1.6"
s.summary = "This is a simple GaoDe SDK Tools"
# 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 a simple GaoDe SDK Tools that cteated by jiang
DESC
s.homepage = "https://github.com/jiangquanqi/Liveneo-GaoDeSDK"
# 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 => "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 = { "jiangquanqi" => "[email protected]" }
# Or just: s.author = "jiangquanqi"
# s.authors = { "jiangquanqi" => "[email protected]" }
# s.social_media_url = "http://twitter.com/jiangquanqi"
# ――― 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, "7.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/jiangquanqi/Liveneo-GaoDeSDK.git", :tag => "#{s.version}" }
# ――― 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 = "Tools/*.{h,m}"
# 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 = "OpenGLES", "UIKit","Foundation","CoreGraphics","QuartzCore","CoreLocation","CoreTelephony","SystemConfiguration","Security","AdSupport","JavaScriptCore"
# s.library = "iconv"
# s.libraries = "z", "stdc++6.0.9","c++"
# ――― 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 "AMapNavi", "~> 2.3.0"
s.dependency "AMapSearch", "~> 4.4.1"
end
| 38.359712 | 171 | 0.597149 |
d53cbf07c7a1cf177c968de6f7396b5db1a87509 | 1,589 | #
# Cookbook Name:: apache2
# Recipe:: fastcgi
#
# Copyright 2008-2013, Opscode, 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.
#
if platform_family?('debian')
package 'libapache2-mod-fastcgi'
elsif platform_family?('rhel')
%w[gcc make libtool httpd-devel apr-devel apr].each do |package|
yum_package package do
action :upgrade
end
end
src_filepath = "#{Chef::Config['file_cache_path']}/fastcgi.tar.gz"
remote_file 'download fastcgi source' do
source node['apache']['mod_fastcgi']['download_url']
path src_filepath
backup false
end
top_dir = node['apache']['lib_dir']
bash 'compile fastcgi source' do
notifies :run, 'execute[generate-module-list]', :immediately
not_if "test -f #{node['apache']['dir']}/mods-available/fastcgi.conf"
cwd ::File.dirname(src_filepath)
code <<-EOH
tar zxf #{::File.basename(src_filepath)} &&
cd mod_fastcgi-* &&
cp Makefile.AP2 Makefile &&
make top_dir=#{top_dir} && make install top_dir=#{top_dir}
EOH
end
end
apache_module 'fastcgi' do
conf true
end
| 29.981132 | 75 | 0.702329 |
ff4b913b1f7cac309b15ced05ec6ce2f68788192 | 2,739 | #!/usr/bin/env ruby
# -*- encoding: us-ascii -*-
# TODO Extract multiple files
# TODO Extract multiple shards
desc "decode FILE [TO]", "Uncompress a frozen Honeywell file"
option 'asis', :aliases=>'-a', :type=>'boolean', :desc=>"Do not attempt to unpack file first"
option "delete", :aliases=>'-d', :type=>'boolean', :desc=>"Keep deleted lines (only with text files)"
option "force", :aliases=>'-f', :type=>'boolean', :desc=>"Overwrite existing files"
option "expand", :aliases=>'-e', :type=>'boolean', :desc=>"Expand freezer archives into multiple files"
option "inspect", :aliases=>'-i', :type=>'boolean', :desc=>"Display long format details for each line (only with normal files)"
option "quiet", :aliases=>'-q', :type=>'boolean', :desc=>"Quiet mode"
option "shard", :aliases=>'-S', :type=>'string', :desc=>"Select shards with this pattern (only with frozen files)"
option "scrub", :aliases=>'-s', :type=>'boolean', :desc=>"Remove control characters from output"
option "warn", :aliases=>"-w", :type=>"boolean", :desc=>"Warn if bad data is found"
long_desc <<-EOT
FILE may have some special formats: '+-nnn' (where nnn is an integer) denotes file number nnn. '-nnn' denotes the nnnth
file from the end of the archive. Anything else denotes the name of a file. A backslash character is ignored at the
beginning of a file name, so that '\\+1' refers to a file named '+1', whereas '+1' refers to the first file in the archive,
whatever its name.
EOT
def decode(file_name, out=nil)
check_for_unknown_options(file_name, out)
shard = options[:shard]
file_name, shard_2 = Bun::File.get_shard(file_name)
shard = shard_2 || shard
out ||= '-'
# TODO The following should be a simple primitive operation
case File.format(file_name)
when :baked
if options[:quiet]
stop
else
stop "!Can't decode file. It is already baked"
end
when :decoded
out ||= '-'
File::Decoded.open(file_name) {|f| f.decode(out, options)}
else
File::Unpacked.open(file_name, :promote=>!options[:asis]) do |file|
begin
file.decode(out, options.merge(:shard=>shard))
rescue Bun::File::Huffman::Data::Base::BadFileContentError => e
stop "!Bad Huffman encoded file: #{e}", quiet: options[:quiet]
rescue Bun::File::Huffman::Data::Base::TreeTooDeepError => e
stop "!Bad Huffman encoded file: #{e}", quiet: options[:quiet]
rescue Bun::File::CantExpandError
stop "!Can't expand frozen archive. Provide --shard option or --expand and directory name", quiet: options[:quiet]
end
warn %Q{Decoded with #{file.errors.count} decoding errors:\n#{file.errors.join("\n")}} if !options[:quiet] && options[:warn] && file.errors.size > 0
end
end
end | 51.679245 | 154 | 0.673604 |
f8ec97fbbbbf15fcf209673644b3ebd2ed69dcd0 | 3,922 | require File.expand_path("../../helpers", __FILE__)
class ParserProperties < Test::Unit::TestCase
modes = ['p', 'P']
example_props = [
'Alnum',
'Any',
'Age=1.1',
'Dash',
'di',
'Default_Ignorable_Code_Point',
'Math',
'Noncharacter-Code_Point', # test dash
'sd',
'Soft Dotted', # test whitespace
'sterm',
'xidc',
'XID_Continue',
'Emoji',
'InChessSymbols',
]
modes.each do |mode|
token_type = mode == 'p' ? :property : :nonproperty
example_props.each do |property|
define_method "test_parse_#{token_type}_#{property}" do
t = RP.parse "ab\\#{mode}{#{property}}", '*'
assert t.expressions.last.is_a?(UnicodeProperty::Base),
"Expected property, but got #{t.expressions.last.class.name}"
assert_equal token_type, t.expressions.last.type
assert_equal property, t.expressions.last.name
end
end
end
def test_parse_all_properties_of_current_ruby
unsupported = RegexpPropertyValues.all_for_current_ruby.reject do |prop|
begin RP.parse("\\p{#{prop}}"); rescue SyntaxError, StandardError; nil end
end
assert_empty unsupported
end
def test_parse_property_negative
t = RP.parse 'ab\p{L}cd', 'ruby/1.9'
assert_equal false, t.expressions[1].negative?
end
def test_parse_nonproperty_negative
t = RP.parse 'ab\P{L}cd', 'ruby/1.9'
assert_equal true, t.expressions[1].negative?
end
def test_parse_caret_nonproperty_negative
t = RP.parse 'ab\p{^L}cd', 'ruby/1.9'
assert_equal true, t.expressions[1].negative?
end
def test_parse_double_negated_property_negative
t = RP.parse 'ab\P{^L}cd', 'ruby/1.9'
assert_equal false, t.expressions[1].negative?
end
def test_parse_property_shortcut
assert_equal 'm', RP.parse('\p{mark}').expressions[0].shortcut
assert_equal 'sc', RP.parse('\p{sc}').expressions[0].shortcut
assert_equal nil, RP.parse('\p{in_bengali}').expressions[0].shortcut
end
def test_parse_property_age
t = RP.parse 'ab\p{age=5.2}cd', 'ruby/1.9'
assert t.expressions[1].is_a?(UnicodeProperty::Age),
"Expected Age property, but got #{t.expressions[1].class.name}"
end
def test_parse_property_derived
t = RP.parse 'ab\p{Math}cd', 'ruby/1.9'
assert t.expressions[1].is_a?(UnicodeProperty::Derived),
"Expected Derived property, but got #{t.expressions[1].class.name}"
end
def test_parse_property_script
t = RP.parse 'ab\p{Hiragana}cd', 'ruby/1.9'
assert t.expressions[1].is_a?(UnicodeProperty::Script),
"Expected Script property, but got #{t.expressions[1].class.name}"
end
def test_parse_property_script_V1_9_3
t = RP.parse 'ab\p{Brahmi}cd', 'ruby/1.9.3'
assert t.expressions[1].is_a?(UnicodeProperty::Script),
"Expected Script property, but got #{t.expressions[1].class.name}"
end
def test_parse_property_script_V2_2_0
t = RP.parse 'ab\p{Caucasian_Albanian}cd', 'ruby/2.2'
assert t.expressions[1].is_a?(UnicodeProperty::Script),
"Expected Script property, but got #{t.expressions[1].class.name}"
end
def test_parse_property_block
t = RP.parse 'ab\p{InArmenian}cd', 'ruby/1.9'
assert t.expressions[1].is_a?(UnicodeProperty::Block),
"Expected Block property, but got #{t.expressions[1].class.name}"
end
def test_parse_property_following_literal
t = RP.parse 'ab\p{Lu}cd', 'ruby/1.9'
assert t.expressions[2].is_a?(Literal),
"Expected Literal, but got #{t.expressions[2].class.name}"
end
def test_parse_abandoned_newline_property
t = RP.parse '\p{newline}', 'ruby/1.9'
assert t.expressions.last.is_a?(UnicodeProperty::Base),
"Expected property, but got #{t.expressions.last.class.name}"
assert_raise(Regexp::Syntax::NotImplementedError) {
RP.parse('\p{newline}', 'ruby/2.0')
}
end
end
| 29.051852 | 80 | 0.666242 |
0190ad81c34b841ce15437dbef249ea696b50797 | 911 | # Copyright 2011-2019, The Trustees of Indiana University and Northwestern
# University. 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.
# --- END LICENSE_HEADER BLOCK ---
module MigrationTarget
extend ActiveSupport::Concern
included do
property :migrated_from, predicate: RDF::URI("http://www.w3.org/ns/prov#wasDerivedFrom"), multiple: true do |index|
index.as :symbol
end
end
end
| 35.038462 | 119 | 0.742042 |
ac2d360be27667234f496637cc30214fd636871a | 4,871 | require File.dirname(__FILE__) + '/../../spec_helper.rb'
require 'spec/expectations/differs/default'
describe "should ==" do
it "should delegate message to target" do
subject = "apple"
subject.should_receive(:==).with("apple").and_return(true)
subject.should == "apple"
end
it "should return true on success" do
subject = "apple"
(subject.should == "apple").should be_true
end
it "should fail when target.==(actual) returns false" do
subject = "apple"
Spec::Expectations.should_receive(:fail_with).with(%[expected: "orange",\n got: "apple" (using ==)], "orange", "apple")
subject.should == "orange"
end
end
describe "should_not ==" do
it "should delegate message to target" do
subject = "orange"
subject.should_receive(:==).with("apple").and_return(false)
subject.should_not == "apple"
end
it "should return true on success" do
subject = "apple"
(subject.should_not == "orange").should be_true
end
it "should fail when target.==(actual) returns false" do
subject = "apple"
Spec::Expectations.should_receive(:fail_with).with(%[expected not: == "apple",\n got: "apple"], "apple", "apple")
subject.should_not == "apple"
end
end
describe "should ===" do
it "should delegate message to target" do
subject = "apple"
subject.should_receive(:===).with("apple").and_return(true)
subject.should === "apple"
end
it "should fail when target.===(actual) returns false" do
subject = "apple"
subject.should_receive(:===).with("orange").and_return(false)
Spec::Expectations.should_receive(:fail_with).with(%[expected: "orange",\n got: "apple" (using ===)], "orange", "apple")
subject.should === "orange"
end
end
describe "should_not ===" do
it "should delegate message to target" do
subject = "orange"
subject.should_receive(:===).with("apple").and_return(false)
subject.should_not === "apple"
end
it "should fail when target.===(actual) returns false" do
subject = "apple"
subject.should_receive(:===).with("apple").and_return(true)
Spec::Expectations.should_receive(:fail_with).with(%[expected not: === "apple",\n got: "apple"], "apple", "apple")
subject.should_not === "apple"
end
end
describe "should =~" do
it "should delegate message to target" do
subject = "foo"
subject.should_receive(:=~).with(/oo/).and_return(true)
subject.should =~ /oo/
end
it "should fail when target.=~(actual) returns false" do
subject = "fu"
subject.should_receive(:=~).with(/oo/).and_return(false)
Spec::Expectations.should_receive(:fail_with).with(%[expected: /oo/,\n got: "fu" (using =~)], /oo/, "fu")
subject.should =~ /oo/
end
end
describe "should_not =~" do
it "should delegate message to target" do
subject = "fu"
subject.should_receive(:=~).with(/oo/).and_return(false)
subject.should_not =~ /oo/
end
it "should fail when target.=~(actual) returns false" do
subject = "foo"
subject.should_receive(:=~).with(/oo/).and_return(true)
Spec::Expectations.should_receive(:fail_with).with(%[expected not: =~ /oo/,\n got: "foo"], /oo/, "foo")
subject.should_not =~ /oo/
end
end
describe "should >" do
it "should pass if > passes" do
4.should > 3
end
it "should fail if > fails" do
Spec::Expectations.should_receive(:fail_with).with(%[expected: > 5,\n got: 4], 5, 4)
4.should > 5
end
end
describe "should >=" do
it "should pass if >= passes" do
4.should > 3
4.should >= 4
end
it "should fail if > fails" do
Spec::Expectations.should_receive(:fail_with).with(%[expected: >= 5,\n got: 4], 5, 4)
4.should >= 5
end
end
describe "should <" do
it "should pass if < passes" do
4.should < 5
end
it "should fail if > fails" do
Spec::Expectations.should_receive(:fail_with).with(%[expected: < 3,\n got: 4], 3, 4)
4.should < 3
end
end
describe "should <=" do
it "should pass if <= passes" do
4.should <= 5
4.should <= 4
end
it "should fail if > fails" do
Spec::Expectations.should_receive(:fail_with).with(%[expected: <= 3,\n got: 4], 3, 4)
4.should <= 3
end
end
describe Spec::Matchers::PositiveOperatorMatcher do
it "should work when the target has implemented #send" do
o = Object.new
def o.send(*args); raise "DOH! Library developers shouldn't use #send!" end
lambda {
o.should == o
}.should_not raise_error
end
end
describe Spec::Matchers::NegativeOperatorMatcher do
it "should work when the target has implemented #send" do
o = Object.new
def o.send(*args); raise "DOH! Library developers shouldn't use #send!" end
lambda {
o.should_not == :foo
}.should_not raise_error
end
end
| 25.369792 | 130 | 0.63334 |
21b9504996abce15c2dbe68374d6ef42c81c6af4 | 5,326 | #!/opt/puppetlabs/puppet/bin/ruby
require 'json'
require 'puppet'
require 'openssl'
def delete_extensions_v1beta1_collection_pod_security_policy(*args)
header_params = {}
params=args[0][1..-1].split(',')
arg_hash={}
params.each { |param|
mapValues= param.split(':',2)
if mapValues[1].include?(';')
mapValues[1].gsub! ';',','
end
arg_hash[mapValues[0][1..-2]]=mapValues[1][1..-2]
}
# Remove task name from arguments - should contain all necessary parameters for URI
arg_hash.delete('_task')
operation_verb = 'Delete'
query_params, body_params, path_params = format_params(arg_hash)
uri_string = "#{arg_hash['kube_api']}/apis/extensions/v1beta1/podsecuritypolicies" % path_params
if query_params
uri_string = uri_string + '?' + to_query(query_params)
end
header_params['Content-Type'] = 'application/json' # first of #{parent_consumes}
if arg_hash['token']
header_params['Authentication'] = 'Bearer ' + arg_hash['token']
end
uri = URI(uri_string)
verify_mode= OpenSSL::SSL::VERIFY_NONE
if arg_hash['ca_file']
verify_mode=OpenSSL::SSL::VERIFY_PEER
end
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', verify_mode: verify_mode, ca_file: arg_hash['ca_file']) do |http|
if operation_verb == 'Get'
req = Net::HTTP::Get.new(uri)
elsif operation_verb == 'Put'
req = Net::HTTP::Put.new(uri)
elsif operation_verb == 'Delete'
req = Net::HTTP::Delete.new(uri)
elsif operation_verb == 'Post'
req = Net::HTTP::Post.new(uri)
end
header_params.each { |x, v| req[x] = v } unless header_params.empty?
unless body_params.empty?
if body_params.key?('file_content')
req.body = body_params['file_content']
else
req.body = body_params.to_json
end
end
Puppet.debug("URI is (#{operation_verb}) #{uri} headers are #{header_params}")
response = http.request req # Net::HTTPResponse object
Puppet.debug("response code is #{response.code} and body is #{response.body}")
success = response.is_a? Net::HTTPSuccess
Puppet.debug("Called (#{operation_verb}) endpoint at #{uri}, success was #{success}")
response
end
end
def to_query(hash)
if hash
return_value = hash.map { |x, v| "#{x}=#{v}" }.reduce { |x, v| "#{x}&#{v}" }
if !return_value.nil?
return return_value
end
end
return ''
end
def op_param(name, inquery, paramalias, namesnake)
{ :name => name, :location => inquery, :paramalias => paramalias, :namesnake => namesnake }
end
def format_params(key_values)
query_params = {}
body_params = {}
path_params = {}
key_values.each { | key, value |
if value.include?("=>")
Puppet.debug("Running hash from string on #{value}")
value.gsub!("=>",":")
value.gsub!("'","\"")
key_values[key] = JSON.parse(value)
Puppet.debug("Obtained hash #{key_values[key].inspect}")
end
}
if key_values.key?('body')
if File.file?(key_values['body'])
if key_values['body'].include?('json')
body_params['file_content'] = File.read(key_values['body'])
else
body_params['file_content'] =JSON.pretty_generate(YAML.load_file(key_values['body']))
end
end
end
op_params = [
op_param('apiversion', 'body', 'apiversion', 'apiversion'),
op_param('continue', 'query', 'continue', 'continue'),
op_param('fieldSelector', 'query', 'field_selector', 'field_selector'),
op_param('kind', 'body', 'kind', 'kind'),
op_param('labelSelector', 'query', 'label_selector', 'label_selector'),
op_param('limit', 'query', 'limit', 'limit'),
op_param('metadata', 'body', 'metadata', 'metadata'),
op_param('pretty', 'query', 'pretty', 'pretty'),
op_param('resourceVersion', 'query', 'resource_version', 'resource_version'),
op_param('spec', 'body', 'spec', 'spec'),
op_param('timeoutSeconds', 'query', 'timeout_seconds', 'timeout_seconds'),
op_param('watch', 'query', 'watch', 'watch'),
]
op_params.each do |i|
location = i[:location]
name = i[:name]
paramalias = i[:paramalias]
name_snake = i[:namesnake]
if location == 'query'
query_params[name] = key_values[name_snake] unless key_values[name_snake].nil?
query_params[name] = ENV["azure__#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil?
elsif location == 'body'
body_params[name] = key_values[name_snake] unless key_values[name_snake].nil?
body_params[name] = ENV["azure_#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil?
else
path_params[name_snake.to_sym] = key_values[name_snake] unless key_values[name_snake].nil?
path_params[name_snake.to_sym] = ENV["azure__#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil?
end
end
return query_params,body_params,path_params
end
def task
# Get operation parameters from an input JSON
params = STDIN.read
result = delete_extensions_v1beta1_collection_pod_security_policy(params)
if result.is_a? Net::HTTPSuccess
puts result.body
else
raise result.body
end
rescue StandardError => e
result = {}
result[:_error] = {
msg: e.message,
kind: 'puppetlabs-kubernetes/error',
details: { class: e.class.to_s },
}
puts result
exit 1
end
task | 31.329412 | 135 | 0.656027 |
eda6c2fb38b8386d8771e898aeaf072841a2f66d | 692 | require File.dirname(__FILE__) + '/../../test/test_helper'
class FleximageOperatorAutoOrientTest < Test::Unit::TestCase
def setup
@photo = PhotoBare.create(:image_file => files(:auto_orient_photo))
end
def test_should_auto_orient
# image is stored as landscape orientation
assert_equal 672, @photo.load_image.rows
assert_equal 896, @photo.load_image.columns
# but, exif data describes rotation necessary to get it to portrait orientation
@photo.operate { |p| p.auto_orient }
# after auto_orient, should now have portrait orientation
assert_equal 896, @photo.load_image.rows
assert_equal 672, @photo.load_image.columns
end
end | 31.454545 | 83 | 0.726879 |
d591e3e0a91404dba3eec66002c5cd05c79f1b80 | 2,824 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2018_10_05_005915) do
create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
t.integer "record_id", null: false
t.integer "blob_id", null: false
t.datetime "created_at", null: false
t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
end
create_table "active_storage_blobs", force: :cascade do |t|
t.string "key", null: false
t.string "filename", null: false
t.string "content_type"
t.text "metadata"
t.bigint "byte_size", null: false
t.string "checksum", null: false
t.datetime "created_at", null: false
t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
end
create_table "activities", force: :cascade do |t|
t.integer "venue_id"
t.string "name"
t.text "schedule"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "description"
t.string "hardness"
t.index ["venue_id"], name: "index_activities_on_venue_id"
end
create_table "activities_tags", force: :cascade do |t|
t.integer "activity_id"
t.integer "tag_id"
t.index ["activity_id"], name: "index_activities_tags_on_activity_id"
t.index ["tag_id"], name: "index_activities_tags_on_tag_id"
end
create_table "tags", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "tags_activities", force: :cascade do |t|
t.integer "activity_id"
t.integer "tag_id"
t.index ["activity_id"], name: "index_tags_activities_on_activity_id"
t.index ["tag_id"], name: "index_tags_activities_on_tag_id"
end
create_table "venues", force: :cascade do |t|
t.string "name"
t.string "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "phone"
end
end
| 37.157895 | 126 | 0.719193 |
e976fe5d33a8c2f37a10279f4cf285e0cde863d0 | 5,672 | class Member < ActiveRecord::Base
acts_as_taggable
acts_as_reader
has_many :orders
has_many :accounts
has_many :payment_addresses, through: :accounts
has_many :withdraws
has_many :fund_sources
has_many :deposits
has_many :api_tokens
has_many :tickets, foreign_key: 'author_id'
has_many :comments, foreign_key: 'author_id'
has_many :signup_histories
has_one :id_document
has_many :authentications, dependent: :destroy
scope :enabled, -> { where(disabled: false) }
delegate :name, to: :id_document, allow_nil: true
delegate :full_name, to: :id_document, allow_nil: true
delegate :verified?, to: :id_document, prefix: true, allow_nil: true
before_validation :sanitize, :generate_sn
validates :sn, presence: true
validates :display_name, uniqueness: true, allow_blank: true
validates :email, email: true, uniqueness: true, allow_nil: true
before_create :build_default_id_document
after_create :touch_accounts
after_update :resend_activation
after_update :sync_update
class << self
def from_auth(auth_hash)
locate_auth(auth_hash) || locate_email(auth_hash) || create_from_auth(auth_hash)
end
def current
Thread.current[:user]
end
def current=(user)
Thread.current[:user] = user
end
def admins
Figaro.env.admin.split(',')
end
def search(field: nil, term: nil)
result = case field
when 'email'
where('members.email LIKE ?', "%#{term}%")
when 'phone_number'
where('members.phone_number LIKE ?', "%#{term}%")
when 'name'
joins(:id_document).where('id_documents.name LIKE ?', "%#{term}%")
when 'wallet_address'
members = joins(:fund_sources).where('fund_sources.uid' => term)
if members.empty?
members = joins(:payment_addresses).where('payment_addresses.address' => term)
end
members
else
all
end
result.order(:id).reverse_order
end
private
def locate_auth(auth_hash)
Authentication.locate(auth_hash).try(:member)
end
def locate_email(auth_hash)
return nil if auth_hash['info']['email'].blank?
member = find_by_email(auth_hash['info']['email'])
return nil unless member
member.add_auth(auth_hash)
member
end
def create_from_auth(auth_hash)
new(email: auth_hash['info']['email'],
nickname: auth_hash['info']['nickname'],
activated: auth_hash['provider'] != 'identity'
).tap do |member|
member.save!
member.add_auth(auth_hash)
member.send_activation if auth_hash['provider'] == 'identity'
end
end
end
def create_auth_for_identity(identity)
self.authentications.create(provider: 'identity', uid: identity.id)
end
def trades
Trade.where('bid_member_id = ? OR ask_member_id = ?', id, id)
end
def active!
update activated: true
end
def update_password(password)
identity.update password: password, password_confirmation: password
send_password_changed_notification
end
def admin?
@is_admin ||= self.class.admins.include?(self.email)
end
def add_auth(auth_hash)
authentications.build_auth(auth_hash).save
end
def trigger(event, data)
AMQPQueue.enqueue(:pusher_member, {member_id: id, event: event, data: data})
end
def notify(event, data)
::Pusher["private-#{sn}"].trigger_async event, data
end
def to_s
"#{name || email} - #{sn}"
end
def gravatar
"//gravatar.com/avatar/" + Digest::MD5.hexdigest(email.strip.downcase) + "?d=retro"
end
def initial?
name? and !name.empty?
end
def get_account(currency)
account = accounts.with_currency(currency.to_sym).first
if account.nil?
touch_accounts
account = accounts.with_currency(currency.to_sym).first
end
account
end
alias :ac :get_account
def touch_accounts
less = Currency.codes - self.accounts.map(&:currency).map(&:to_sym)
less.each do |code|
self.accounts.create(currency: code, balance: 0, locked: 0)
end
end
def identity
authentication = authentications.find_by(provider: 'identity')
authentication ? Identity.find(authentication.uid) : nil
end
def auth(name)
authentications.where(provider: name).first
end
def auth_with?(name)
auth(name).present?
end
def remove_auth(name)
identity.destroy if name == 'identity'
auth(name).destroy
end
def send_activation
Token::Activation.create(member: self)
end
def send_password_changed_notification
MemberMailer.reset_password_done(self.id).deliver
end
def unread_comments
ticket_ids = self.tickets.open.collect(&:id)
if ticket_ids.any?
Comment.where(ticket_id: ticket_ids).where('author_id <> ?', id).unread_by(self).to_a
else
[]
end
end
def as_json(options = {})
super(options).merge({
"name" => self.name,
"memo" => self.id
})
end
private
def sanitize
self.email.try(:downcase!)
end
def generate_sn
self.sn and return
begin
self.sn = "PEA#{ROTP::Base32.random_base32(8).upcase}TIO"
end while Member.where(:sn => self.sn).any?
end
def build_default_id_document
build_id_document
true
end
def resend_activation
self.send_activation if self.email_changed?
end
def sync_update
::Pusher["private-#{sn}"].trigger_async('members', { type: 'update', id: self.id, attributes: self.changes_attributes_as_json })
end
end
| 24.239316 | 132 | 0.65885 |
1a631558d0734bb845f1a85cc75fef436b65a4c5 | 3,540 | require 'albacore'
require 'version_bumper'
require './packages/packaging'
task :default => [:build]
desc "Build the project as debug"
task :build => 'build:debug'
directory 'dist'
namespace :build do
desc "create solutioninfo.cs file"
assemblyinfo :solutioninfo do |asm|
asm.version = bumper_version.to_s
asm.file_version = bumper_version.to_s
asm.product_name = "FluentMigrator"
asm.copyright = "Copyright - Sean Chambers 2008-" + Time.now.year.to_s
asm.custom_attributes :AssemblyConfigurationAttribute => "Debug", :'System.CLSCompliantAttribute' => true
asm.output_file = "src/SolutionInfo.cs"
end
msbuild :debug do |msb|
# this doesnt work for me, and it builds fine w/o it. sry if it breaks for you. -josh c
# to josh c, Please upgrade your Albacore. --tkellogg
#msb.path_to_command = File.join(ENV['windir'], 'Microsoft.NET', 'Framework', 'v4.0.30319', 'MSBuild.exe')
msb.properties :configuration => :Debug
msb.targets :Clean, :Rebuild
msb.verbosity = 'quiet'
msb.solution = "FluentMigrator (2010).sln"
end
desc "build the release version of the solution"
msbuild :release do |msb|
# this doesnt work for me, and it builds fine w/o it. sry if it breaks for you. -josh c
#msb.path_to_command = File.join(ENV['windir'], 'Microsoft.NET', 'Framework', 'v4.0.30319', 'MSBuild.exe')
msb.properties :configuration => :Release
msb.targets :Clean, :Rebuild
msb.verbosity = 'quiet'
msb.solution = "FluentMigrator (2010).sln"
end
@platforms = ['x86', 'AnyCPU']
@versions = ['v3.5', 'v4.0']
@platforms.each do |p|
@versions.each do |v|
directory "dist/console-#{v}-#{p}"
desc "build the console app for target .NET Framework version ${v}"
task "console-#{v}-#{p}" => [:release, "compile-console-#{v}-#{p}", "dist/console-#{v}-#{p}"] do
cp_r FileList['lib/Postgres/*', 'lib/MySql.Data.dll', 'lib/Oracle.DataAccess.dll', 'lib/System.Data.SQLite.dll', 'lib/SQLServerCE4/Private/*', 'lib/FirebirdSql.Data.FirebirdClient.dll', 'lib/Oracle.ManagedDataAccess.dll'], "dist/console-#{v}-#{p}"
cp_r FileList['src/FluentMigrator.Console/bin/Release/*'].exclude('src/FluentMigrator.Console/bin/Release/SQLServerCENative'), "dist/console-#{v}-#{p}"
cp_r FileList['src/FluentMigrator.Nant/bin/Release/FluentMigrator.Nant.*'], "dist/console-#{v}-#{p}"
cp_r FileList['src/FluentMigrator.MSBuild/bin/Release/FluentMigrator.MSBuild.*'], "dist/console-#{v}-#{p}"
if to_nuget_version(v) == '35' then
File.delete("dist/console-#{v}-#{p}/Migrate.exe.config")
File.rename("dist/console-#{v}-#{p}/app.35.config", "dist/console-#{v}-#{p}/Migrate.exe.config")
else
File.delete("dist/console-#{v}-#{p}/app.35.config")
end
end
msbuild "compile-console-#{v}-#{p}" do |msb|
msb.properties :configuration => :Release, :TargetFrameworkVersion => v, :PlatformTarget => p
msb.targets :Clean, :Rebuild
msb.verbosity = 'quiet'
msb.solution = 'FluentMigrator (2010).sln'
end
end
end
# FYI: `Array.product` will only work in ruby 1.9
desc "compile the console runner for all x86/64/4.0/3.5 combinations"
task :console => @platforms.product(@versions).map {|x| "console-#{x[1]}-#{x[0]}"}
end
nunit :test => :build do |nunit|
nunit.command = "tools/NUnit/nunit-console.exe"
nunit.assemblies "src/FluentMigrator.Tests/bin/Debug/FluentMigrator.Tests.dll"
end
| 40.689655 | 252 | 0.657345 |
ffacd05338df9ecf6341fe8cfc3c91641218b3d0 | 3,766 | require 'rails_helper'
RSpec.describe 'Articles', type: :feature do
context 'Creation' do
before(:each) do
@article = {
title: 'test',
category: 'test2',
author: 'Megaman',
text: '# Testing'
}
@article2 = {
title: 'test2',
category: 'test3',
author: 'Zero',
text: '# Testing2'
}
end
it 'from index' do
# Go to create
visit '/'
click_link 'mode_edit'
# Fill
fill_and_save_article(@article)
end
it 'from welcome' do
visit '/'
click_link 'Write your first article'
# Fill
fill_and_save_article(@article2)
end
end
context 'Validation' do
before(:each) do
@article = create(:article)
end
it 'should validate all fields when create' do
visit new_article_path
click_link('Save')
sleep(1)
# User musn't be redirected
expect(page.current_path).to eq(new_article_path)
%w(title author category text).each do |field|
expect(page).to have_selector(".article-#{field}.error")
end
end
it 'should validate all fields when edit' do
visit edit_article_path(@article)
# Clear elements
%w(title category text).each do |field|
fill_in field, with: ''
end
# Try to update
click_link('Update')
sleep(1)
# User musn't be redirected
expect(page.current_path).to eq(edit_article_path(@article))
%w(title category text).each do |field|
expect(page).to have_selector(".article-#{field}.error")
end
end
end
context 'Visualization' do
before(:each) do
@article = create(:article, :unpermitted_tags)
end
it 'must escape unpermitted tags' do
visit article_path(@article)
%w(title author category).each do |field|
script = @article.send(field)
.scan(%r{(\w+)<script>.*<\/script>}).flatten.first
# Expect the text include the content of unpermitted tags
expect(page).to have_content(script)
end
# check text
script = @article.text.scan(%r{<script>(.*)<\/script>}).flatten.first
# Expect the text include the content of unpermitted tags
expect(page).to have_content(script)
end
end
context 'Edition' do
before(:each) do
@article = create(:article)
@new_title = 'This is a new title, OMG'
end
it 'an existent article' do
visit '/'
# Click on title
expect(page).to have_content(@article.title)
click_link @article.title
# Click on edit
sleep(1)
click_link 'border_color'
# Save
fill_and_save_article({ title: @new_title }, button: 'Update')
end
end
context 'Search' do
before(:each) do
number = 25
FactoryGirl.create_list(:article, number)
@other_title = 'Supernintendo'
create(:article, title: @other_title)
end
it 'show only 15 more relevant articles' do
visit '/'
# Fill input
fill_in 'search', with: 'Title'
sleep(1)
expect(page).to have_selector('.article-result', count: 15)
end
it 'show only the article' do
visit '/'
# Fill input
fill_in 'search', with: @other_title
sleep(1)
expect(page).to have_selector('.article-result', count: 1)
expect(page).to have_content(@other_title)
end
it 'must show a call to action when scroll down' do
visit '/'
# Fill input
fill_in 'search', with: 'Title'
sleep(1)
find_link 'Start an article about Title'
# Fill input
fill_in 'search', with: @other_title
sleep(1)
find_link "Start an article about #{@other_title}"
end
end
end
| 25.794521 | 75 | 0.598513 |
627859f8b7b73b95f8d18d8302e64e732d649210 | 854 |
class ExecutionJournal < ActiveRecord::Base
unloadable
belongs_to :test_case
belongs_to :version
belongs_to :result, :class_name => 'ExecutionResult'
belongs_to :executor, :class_name => 'User'
belongs_to :environment, :class_name => 'ExecutionEnvironment'
# attr_protected :id
# TODO: Move to view f.ex. using JBuilder
# (https://github.com/rails/jbuilder)
def to_json
{
'created_on' => created_on.strftime('%d.%m.%Y %H:%M:%S'),
'result' => result.name,
'comment' => comment,
'executor' => (executor.nil? ? '' : executor.name),
'environment' => environment.name,
'version' => version.name,
'report' => ''
}
end
def self.find_by_issue_id(issue_id)
test_case = TestCase.find_by_issue_id(issue_id)
ExecutionJournal
.order('created_on desc')
.where({test_case_id: test_case.id})
end
end
| 24.4 | 63 | 0.677986 |
61455c3358ad49e42c1c5012b4ead7186ad96837 | 2,390 | class TowersOfHanoiGame
def self.disks
# can always make the game harder by changing max value :-)
(1..3).to_a.reverse
end
def self.default_stacks
[TowersOfHanoiGame.disks, [], []]
end
def initialize(stacks = TowersOfHanoiGame.default_stacks)
@stacks = stacks
end
def render
max_height = @stacks.map(&:count).max
(max_height - 1).downto(0).map do |height|
@stacks.map do |stack|
# this || trick says that if stack[height] is `nil` (that is,
# the stack isn't that high), print `" "` instead of `nil`,
# because we need a blank space.
stack[height] || " "
end.join("\t")
end.join("\n")
end
def display
puts render
end
def move(from_stack_num, to_stack_num)
# `values_at` is pretty sweet; check out the RubyDoc; here I use
# it alongside destructuring.
from_stack, to_stack =
@stacks.values_at(from_stack_num, to_stack_num)
raise "cannot move from empty stack" if from_stack.empty?
unless (to_stack.empty? || to_stack.last > from_stack.last)
raise "cannot move onto smaller disk"
end
to_stack.push(from_stack.pop)
# what should `move` return? Perhaps `nil`, since we only call
# `move` for its side-effect. But returning `self` is also common
# with side-effect methods, this let's us *chain* calls to `move`:
# `towers.move(1, 2).move(0, 1).move(3, 0)`.
self
end
def game_won?
# move everything from first stack to some other stack.
@stacks[0].empty? && @stacks[1..2].any?(&:empty?)
end
def run_game
# I wrote this last; I often write the user input last, so I can
# first test the game in IRB.
until game_won?
display
# this uses *array destructuring*
from_stack_num, to_stack_num = get_move
move(from_stack_num, to_stack_num)
end
puts "You did it!"
end
private
def get_move
from_stack_num = get_stack("Move from: ")
to_stack_num = get_stack("Move to: ")
# returning two things is normally done via array
[from_stack_num, to_stack_num]
end
def get_stack(prompt)
move_hash = {
"a" => 0,
"b" => 1,
"c" => 2
}
while true
print prompt
stack_num = move_hash[gets.chomp]
return stack_num unless stack_num.nil?
# otherwise, try again
puts "Invalid move!"
end
end
end
| 24.141414 | 70 | 0.634728 |
61e66eec08b2b23e3b19d930001a63f1a087ecc5 | 2,911 | require 'spec_helper'
describe "Admin::Projects" do
before do
@project = Factory :project,
name: "LeGiT",
code: "LGT"
login_as :admin
end
describe "GET /admin/projects" do
before do
visit admin_projects_path
end
it "should be ok" do
current_path.should == admin_projects_path
end
it "should have projects list" do
page.should have_content(@project.name)
end
end
describe "GET /admin/projects/:id" do
before do
visit admin_projects_path
click_link "#{@project.name}"
end
it "should have project info" do
page.should have_content(@project.code)
page.should have_content(@project.name)
end
end
describe "GET /admin/projects/:id/edit" do
before do
visit admin_projects_path
click_link "edit_project_#{@project.id}"
end
it "should have project edit page" do
page.should have_content("Project name")
page.should have_content("URL")
end
describe "Update project" do
before do
fill_in "project_name", with: "Big Bang"
fill_in "project_code", with: "BB1"
click_button "Save Project"
@project.reload
end
it "should show page with new data" do
page.should have_content("BB1")
page.should have_content("Big Bang")
end
it "should change project entry" do
@project.name.should == "Big Bang"
@project.code.should == "BB1"
end
end
end
describe "GET /admin/projects/new" do
before do
visit admin_projects_path
click_link "New Project"
end
it "should be correct path" do
current_path.should == new_admin_project_path
end
it "should have labels for new project" do
page.should have_content("Project name is")
page.should have_content("Git Clone")
page.should have_content("URL")
end
end
describe "POST /admin/projects" do
before do
visit new_admin_project_path
fill_in 'project_name', with: 'NewProject'
fill_in 'project_code', with: 'NPR'
fill_in 'project_path', with: 'gitlabhq_1'
expect { click_button "Create project" }.to change { Project.count }.by(1)
@project = Project.last
end
it "should be correct path" do
current_path.should == admin_project_path(@project)
end
it "should show project" do
page.should have_content(@project.name)
page.should have_content(@project.path)
end
end
describe "Add new team member" do
before do
@new_user = Factory :user
visit admin_project_path(@project)
end
it "should create new user" do
select @new_user.name, from: "user_ids"
expect { click_button "Add" }.to change { UsersProject.count }.by(1)
page.should have_content @new_user.name
current_path.should == admin_project_path(@project)
end
end
end
| 24.462185 | 80 | 0.648918 |
ab24235df6c845736a5c2ddacf463ba562f7c702 | 1,466 | #
# Be sure to run `pod lib lint MXCardsSwipingView.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'MXCardsSwipingView'
s.version = '0.2.0'
s.summary = 'A UIView offering Tinder style card swiping on iOS.'
s.description = <<-DESC
It's a lightweight `UIView` to extract the pan gesture and animations involved in the card swiping
paradigm which has become so popular. Other card-swiping libraries try to do too much IMO and make it
hard to customize. To use it, you simply instantiate a `MXCardsSwipingView` and enqueue cards. You can
enqueue more cards when its delegate methods are called. And the card you enqueue can optionally conform to the
`MXSwipableCard` protocol to provide additional customizability (e.g. fading views in on swipe left or right).
DESC
s.homepage = 'https://github.com/skensell/MXCardsSwipingView'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Scott Kensell' => '[email protected]' }
s.source = { :git => 'https://github.com/skensell/MXCardsSwipingView.git', :tag => s.version.to_s }
s.ios.deployment_target = '7.0'
s.source_files = 'MXCardsSwipingView/Classes/**/*'
s.frameworks = 'UIKit'
end
| 47.290323 | 112 | 0.686903 |
d5574a8b3232d0aa7ef94fb128d09e67dbc8cf4e | 3,049 | # frozen_string_literal: true
class Users::RegistrationsController < Devise::RegistrationsController
# before_action :configure_sign_up_params, only: [ :create ]
before_action :configure_account_update_params, only: [ :update ]
before_action :set_filters_open, only: :index
def index
params[:page] ||= 1
@show_search_bar = true
@show_sorting_options = true
@users = User
@users = @users.tagged_with(params[:skills]) if params[:skills].present?
if params[:query].present?
@users = @users.search(params[:query])
else
@users = @users
end
@users = @users.order(get_order_param) if params[:sort_by]
@users = @users.where(visibility: true).page(params[:page]).per(25)
@index_from = (@users.prev_page || 0) * @users.current_per_page + 1
@index_to = [@index_from + @users.current_per_page - 1, @users.total_count].min
@total_count = @users.total_count
@show_filters = true
end
def show
@user = User.find(params[:id])
if @user.blank?
flash[:error] = 'Sorry, no such user.'
redirect_to projects_path
return
end
if [email protected]_visible_to_user?(current_user)
flash[:error] = 'Sorry, no such user.'
redirect_to projects_path
return
end
end
# GET /resource/sign_up
# def new
# super
# end
# POST /resource
# def create
# super
# end
# GET /resource/edit
# def edit
# super
# end
# PUT /resource
# def update
# super
# end
# DELETE /resource
# def destroy
# super
# end
# GET /resource/cancel
# Forces the session data which is usually expired after sign
# in to be expired now. This is useful if the user wants to
# cancel oauth signing in/up in the middle of the process,
# removing all OAuth session data.
# def cancel
# super
# end
protected
# If you have extra params to permit, append them to the sanitizer.
# def configure_sign_up_params
# devise_parameter_sanitizer.permit(:sign_up, keys: [ :about, :profile_links, :location ])
# end
# If you have extra params to permit, append them to the sanitizer.
def configure_account_update_params
devise_parameter_sanitizer.permit(:account_update, keys: [ :name, :about, :profile_links, :location, :visibility, :pair_with_projects, :level_of_availability, :skill_list => []])
end
# The path used after sign up.
def after_sign_up_path_for(resource)
projects_path
end
# The path used after sign up for inactive accounts.
# def after_inactive_sign_up_path_for(resource)
# super(resource)
# end
def update_resource(resource, params)
if params[:password].present?
super(resource, params)
else
Rails.logger.error 'here pac pac'
params.delete(:password_confirmation)
params.delete(:current_password)
resource.update_without_password(params)
end
end
def get_order_param
return 'created_at desc' if params[:sort_by] == 'latest'
return 'created_at asc' if params[:sort_by] == 'earliest'
end
end
| 24.991803 | 183 | 0.681207 |
e9ac5b4be564a9b03106fde80f862853dd61cfb9 | 143 | class AddEntriesCountToPacks < ActiveRecord::Migration[6.0]
def change
add_column :packs, :entries_count, :integer, default: 0
end
end
| 23.833333 | 59 | 0.755245 |
d5225893060735fc79604e6e285b952afe3aae3c | 1,182 | # This file is copied to spec/ when you run 'rails generate rspec:install'
require "spec_helper"
ENV["RAILS_ENV"] ||= "test"
require File.expand_path("../config/environment", __dir__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require "rspec/rails"
require "active_support/testing/time_helpers"
require "webmock/rspec"
require "vcr"
Dir[Rails.root.join("spec", "support", "**", "*.rb")].each { |f| require f }
ActiveRecord::Migration.maintain_test_schema!
WebMock.disable_net_connect!
VCR.configure do |c|
c.cassette_library_dir = "spec/fixtures/cassettes"
c.hook_into :webmock
end
RSpec.configure do |config|
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
config.include ActiveSupport::Testing::TimeHelpers
config.include FactoryGirl::Syntax::Methods
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run
end
end
end
| 26.266667 | 86 | 0.763959 |
ac3f895a0a28f816f33919750f11bc925f682d41 | 920 | module Rapns
module Daemon
class DeliveryHandler
include Reflectable
attr_accessor :queue
def start
@thread = Thread.new do
loop do
handle_next_notification
break if @stop
end
end
end
def stop
@stop = true
if @thread
queue.wakeup(@thread)
@thread.join
end
stopped
end
protected
def stopped
end
def handle_next_notification
begin
notification = queue.pop
rescue DeliveryQueue::WakeupError
return
end
begin
deliver(notification)
reflect(:notification_delivered, notification)
rescue StandardError => e
Rapns.logger.error(e)
reflect(:error, e)
ensure
queue.notification_processed
end
end
end
end
end
| 18.039216 | 56 | 0.53587 |
87f458773045b51a87af8d517c8512381d5c2891 | 159 | Rails.application.config.middleware.use OmniAuth::Builder do
provider :github, ENV['GITHUB_CLIENT_ID'], ENV['GITHUB_CLIENT_SECRET'], scope: 'user:email'
end
| 39.75 | 93 | 0.786164 |
e80331a3fce428cdd83b5c17ca8e39f677811352 | 6,188 | require 'date'
require 'spec_helper'
require 'bibliografia'
describe Bibliografia do
before :each do
serie = "Serie1"
autores = Array.new
autores = %w{ Autor1 Autor2 }
isbn = { "isbn-1" => " 193778", "isbn-12" => " 978-19377" }
@libro = Bibliografia::Libro.new(autores, "TituloLibro", serie, "Editorial Libro", "Numero Edicion Libro", Date.new(2015, 11, 17), isbn)
serie2 = "Serie2"
autores = Array.new
autores = %w{ Autor1 Autor2 }
issn = "1133-9721"
@revista = Bibliografia::Revista.new(autores, "TituloRevista", serie2, "Editorial Revista", "Numero Edicion Revista", Date.new(2015, 11, 17), issn)
autores = Array.new
autores = %w{ Autor1 Autor2 }
url = "www.libroelectronico.com"
@doc = Bibliografia::DocumentoElectronico.new(autores, "TituloDoc", Date.new(2015, 11, 17), url)
@Node = Struct.new(:prev, :value, :sig)
@Lista = Bibliografia::ListaEnlazada.new(@libro)
end #before each
########################################################PRUEBAS PRACTICA 10
context "Referencias segun APA" do
it "Debe existir clase de prueba" do
autores = Array.new
autores = ["Alejandro Alvaro", "Florentino Fernandez"]
a=Bibliografia::Clase_Nueva.new(autores, "TITULO", Date.new(2015, 11, 17))
expect(a.is_a?Bibliografia::Clase_Nueva).to eq(true)
end
it "Debe mostrar el nombre y apellidos de forma inversa" do
autores = Array.new
autores = ["Alejandro Alvaro", "Florentino Fernandez"]
serie = "Serie1"
isbn = { "isbn-1" => " 193778", "isbn-12" => " 978-19377" }
@libro = Bibliografia::Libro.new(autores, "ZTituloLibro", serie, "Editorial Libro", "Numero Edicion Libro", Date.new(2015, 11, 14), isbn)
@libro.getAutores()
end
it "Ordenado segun APA" do
serie = "Serie1"
autores = Array.new
autores = ["Alejandro Alvaro", "Florentino Fernandez"]
isbn = { "isbn-1" => " 193778", "isbn-12" => " 978-19377" }
@libro = Bibliografia::Libro.new(autores, "ZTituloLibro", serie, "Editorial Libro", "Numero Edicion Libro", Date.new(2015, 11, 14), isbn)
serie2 = "Serie2"
autores1 = Array.new
autores1 = ["Alejandro Alvaro", "Florentino Fernandez"]
issn = "1133-9721"
@revista = Bibliografia::Revista.new(autores1, "TituloRevista", serie2, "Editorial Revista", "Numero Edicion Revista", Date.new(2015, 11, 15), issn)
@lista = Bibliografia::ListaEnlazada.new(@libro)
@lista.insertar_delante(@revista)
puts""
puts "Comienzo sort: Mismos autores exactamente, ordena por fecha"
puts @lista.sort
puts "Final sort: Debe salir libro y luego revista"
end
it "Ordenado segun APA" do
serie = "Serie1"
autores = Array.new
autores = ["Alejandro Alvaro"]
isbn = { "isbn-1" => " 193778", "isbn-12" => " 978-19377" }
@libro = Bibliografia::Libro.new(autores, "ZTituloLibro", serie, "Editorial Libro", "Numero Edicion Libro", Date.new(2015, 11, 14), isbn)
serie2 = "Serie2"
autores1 = Array.new
autores1 = ["Alejandro Alvaro", "Florentino Fernandez"]
issn = "1133-9721"
@revista = Bibliografia::Revista.new(autores1, "TituloRevista", serie2, "Editorial Revista", "Numero Edicion Revista", Date.new(2015, 11, 15), issn)
@lista = Bibliografia::ListaEnlazada.new(@libro)
@lista.insertar_delante(@revista)
puts""
puts "Comienzo sort: Mismo primer autor, imprime primero el de solo un autor"
puts @lista.sort
puts "Final sort: Debe salir libro primero y luego revista"
end
it "Ordenado segun APA" do
serie = "Serie1"
autores = Array.new
autores = ["Alejandro Alvaro", "Florentino Fernandez"]
isbn = { "isbn-1" => " 193778", "isbn-12" => " 978-19377" }
@libro = Bibliografia::Libro.new(autores, "ZTituloLibro", serie, "Editorial Libro", "Numero Edicion Libro", Date.new(2015, 11, 14), isbn)
serie2 = "Serie2"
autores1 = Array.new
autores1 = ["Alejandro Alvaro", "Florentino Fernandez"]
issn = "1133-9721"
@revista = Bibliografia::Revista.new(autores1, "TituloRevista", serie2, "Editorial Revista", "Numero Edicion Revista", Date.new(2015, 11, 14), issn)
@lista = Bibliografia::ListaEnlazada.new(@libro)
@lista.insertar_delante(@revista)
puts""
puts "Comienzo sort: Mismos autores y misma fecha, ordena por titulo"
puts @lista.sort
puts "Final sort: Debe salir revista primero y luego libro"
end
it "Salida formateada con nombre autor y sangria" do
serie = "Serie1"
autores = Array.new
autores = ["Alejandro Alvaro", "Florentino Fernandez"]
isbn = { "isbn-1" => " 193778", "isbn-12" => " 978-19377" }
@libro = Bibliografia::Libro.new(autores, "ZTituloLibro", serie, "Editorial Libro", "Numero Edicion Libro", Date.new(2015, 11, 14), isbn)
serie2 = "Serie2"
autores1 = Array.new
autores1 = ["Alejandro Alvaro", "Florentino Fernandez"]
issn = "1133-9721"
@revista = Bibliografia::Revista.new(autores1, "TituloRevista", serie2, "Editorial Revista", "Numero Edicion Revista", Date.new(2015, 11, 14), issn)
@lista = Bibliografia::ListaEnlazada.new(@libro)
@lista.insertar_delante(@revista)
puts ""
puts "Salida formateada"
@lista.extraer_delante()
puts ""
end
end
end
| 44.84058 | 160 | 0.557046 |
e921e58a3688831bd0deaffe8e79343da579fc5f | 542 | require 'spec_helper'
module BugReport600
describe "stubbing a class method" do
class ExampleClass
def self.method_that_uses_define_method
define_method "defined_method" do |attributes|
load_address(address, attributes)
end
end
end
it "works" do
ExampleClass.should_receive(:define_method).with("defined_method")
ExampleClass.method_that_uses_define_method
end
it "restores the original method" do
ExampleClass.method_that_uses_define_method
end
end
end
| 23.565217 | 72 | 0.715867 |
031ff14d616f6300ce04ec7ecf93c7c59e558754 | 93 | module Ordering
class FakeNumberGenerator
def call
"2019/01/60"
end
end
end | 13.285714 | 27 | 0.666667 |
edd3d40ea57b4269785982bfba5a5e6b18f07fcb | 10,074 | # ------------------------------------------------------------------------------------
# <copyright company="Aspose" file="document.rb">
# Copyright (c) 2020 Aspose.Words for Cloud
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# </summary>
# ------------------------------------------------------------------------------------
require 'date'
module AsposeWordsCloud
# Represents Words document DTO.
class Document
# Gets or sets the document properties.
attr_accessor :document_properties
# Gets or sets the name of the file.
attr_accessor :file_name
# Gets or sets a value indicating whether the document is encrypted and requires a password to open.
attr_accessor :is_encrypted
# Gets or sets a value indicating whether the document contains a digital signature. This property merely informs that a digital signature is present on a document, but it does not specify whether the signature is valid or not.
attr_accessor :is_signed
# Gets or sets the list of links that originate from this document.
attr_accessor :links
# Gets or sets the original format of the document.
attr_accessor :source_format
class EnumAttributeValidator
attr_reader :datatype
attr_reader :allowable_values
def initialize(datatype, allowable_values)
@allowable_values = allowable_values.map do |value|
case datatype.to_s
when /Integer/i
value.to_i
when /Float/i
value.to_f
else
value
end
end
end
def valid?(value)
!value || allowable_values.include?(value)
end
end
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'document_properties' => :'DocumentProperties',
:'file_name' => :'FileName',
:'is_encrypted' => :'IsEncrypted',
:'is_signed' => :'IsSigned',
:'links' => :'Links',
:'source_format' => :'SourceFormat'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'document_properties' => :'DocumentProperties',
:'file_name' => :'String',
:'is_encrypted' => :'BOOLEAN',
:'is_signed' => :'BOOLEAN',
:'links' => :'Array<Link>',
:'source_format' => :'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.key?(:'DocumentProperties')
self.document_properties = attributes[:'DocumentProperties']
end
if attributes.key?(:'FileName')
self.file_name = attributes[:'FileName']
end
if attributes.key?(:'IsEncrypted')
self.is_encrypted = attributes[:'IsEncrypted']
end
if attributes.key?(:'IsSigned')
self.is_signed = attributes[:'IsSigned']
end
if attributes.key?(:'Links')
if (value = attributes[:'Links']).is_a?(Array)
self.links = value
end
end
if attributes.key?(:'SourceFormat')
self.source_format = attributes[:'SourceFormat']
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 = []
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?
source_format_validator = EnumAttributeValidator.new('String', ["Unknown", "Doc", "Dot", "DocPreWord60", "Docx", "Docm", "Dotx", "Dotm", "FlatOpc", "Rtf", "WordML", "Html", "Mhtml", "Epub", "Text", "Odt", "Ott", "Pdf", "Xps", "Tiff", "Svg"])
return false unless source_format_validator.valid?(@source_format)
return true
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] source_format Object to be assigned
def source_format=(source_format)
validator = EnumAttributeValidator.new('String', ["Unknown", "Doc", "Dot", "DocPreWord60", "Docx", "Docm", "Dotx", "Dotm", "FlatOpc", "Rtf", "WordML", "Html", "Mhtml", "Epub", "Text", "Odt", "Ott", "Pdf", "Xps", "Tiff", "Svg"])
if source_format.to_i == 0
unless validator.valid?(source_format)
raise ArgumentError, "invalid value for 'source_format', must be one of #{validator.allowable_values}."
end
@source_format = source_format
else
@source_format = validator.allowable_values[source_format.to_i]
end
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(other)
return true if self.equal?(other)
self.class == other.class &&
document_properties == other.document_properties &&
file_name == other.file_name &&
is_encrypted == other.is_encrypted &&
is_signed == other.is_signed &&
links == other.links &&
source_format == other.source_format
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(other)
self == other
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[document_properties, file_name, is_encrypted, is_signed, links, source_format].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.swagger_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
Time.at(/\d/.match(value)[0].to_f).to_datetime
when :Date
Time.at(/\d/.match(value)[0].to_f).to_date
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :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 = AsposeWordsCloud.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
| 34.149153 | 247 | 0.62696 |
216bc0cc955779c6b97b89119ef5ff0e407935f4 | 997 | # typed: true
require 'datadog/core/utils/only_once'
require 'datadog/tracing/contrib/httpclient/instrumentation'
require 'datadog/tracing/contrib/patcher'
module Datadog
module Tracing
module Contrib
# Datadog Httpclient integration.
module Httpclient
# Patcher enables patching of 'httpclient' module.
module Patcher
include Contrib::Patcher
PATCH_ONLY_ONCE = Core::Utils::OnlyOnce.new
module_function
def patched?
PATCH_ONLY_ONCE.ran?
end
def target_version
Integration.version
end
# patch applies our patch
def patch
PATCH_ONLY_ONCE.run do
begin
::HTTPClient.include(Instrumentation)
rescue StandardError => e
Datadog.logger.error("Unable to apply httpclient integration: #{e}")
end
end
end
end
end
end
end
end
| 23.738095 | 84 | 0.588766 |
031a6e75103194f288e1a9520bd88893a683ed73 | 17,078 | module Sass::Script::Value
# A SassScript object representing a number.
# SassScript numbers can have decimal values,
# and can also have units.
# For example, `12`, `1px`, and `10.45em`
# are all valid values.
#
# Numbers can also have more complex units, such as `1px*em/in`.
# These cannot be inputted directly in Sass code at the moment.
class Number < Base
# The Ruby value of the number.
#
# @return [Numeric]
attr_reader :value
# A list of units in the numerator of the number.
# For example, `1px*em/in*cm` would return `["px", "em"]`
# @return [Array<String>]
attr_reader :numerator_units
# A list of units in the denominator of the number.
# For example, `1px*em/in*cm` would return `["in", "cm"]`
# @return [Array<String>]
attr_reader :denominator_units
# The original representation of this number.
# For example, although the result of `1px/2px` is `0.5`,
# the value of `#original` is `"1px/2px"`.
#
# This is only non-nil when the original value should be used as the CSS value,
# as in `font: 1px/2px`.
#
# @return [Boolean, nil]
attr_accessor :original
def self.precision
@precision ||= 5
end
# Sets the number of digits of precision
# For example, if this is `3`,
# `3.1415926` will be printed as `3.142`.
def self.precision=(digits)
@precision = digits.round
@precision_factor = 10.0**@precision
end
# the precision factor used in numeric output
# it is derived from the `precision` method.
def self.precision_factor
@precision_factor ||= 10.0**precision
end
# Used so we don't allocate two new arrays for each new number.
NO_UNITS = []
# @param value [Numeric] The value of the number
# @param numerator_units [::String, Array<::String>] See \{#numerator\_units}
# @param denominator_units [::String, Array<::String>] See \{#denominator\_units}
def initialize(value, numerator_units = NO_UNITS, denominator_units = NO_UNITS)
numerator_units = [numerator_units] if numerator_units.is_a?(::String)
denominator_units = [denominator_units] if denominator_units.is_a?(::String)
super(value)
@numerator_units = numerator_units
@denominator_units = denominator_units
normalize!
end
# The SassScript `+` operation.
# Its functionality depends on the type of its argument:
#
# {Number}
# : Adds the two numbers together, converting units if possible.
#
# {Color}
# : Adds this number to each of the RGB color channels.
#
# {Value}
# : See {Value::Base#plus}.
#
# @param other [Value] The right-hand side of the operator
# @return [Value] The result of the operation
# @raise [Sass::UnitConversionError] if `other` is a number with incompatible units
def plus(other)
if other.is_a? Number
operate(other, :+)
elsif other.is_a?(Color)
other.plus(self)
else
super
end
end
# The SassScript binary `-` operation (e.g. `$a - $b`).
# Its functionality depends on the type of its argument:
#
# {Number}
# : Subtracts this number from the other, converting units if possible.
#
# {Value}
# : See {Value::Base#minus}.
#
# @param other [Value] The right-hand side of the operator
# @return [Value] The result of the operation
# @raise [Sass::UnitConversionError] if `other` is a number with incompatible units
def minus(other)
if other.is_a? Number
operate(other, :-)
else
super
end
end
# The SassScript unary `+` operation (e.g. `+$a`).
#
# @return [Number] The value of this number
def unary_plus
self
end
# The SassScript unary `-` operation (e.g. `-$a`).
#
# @return [Number] The negative value of this number
def unary_minus
Number.new(-value, @numerator_units, @denominator_units)
end
# The SassScript `*` operation.
# Its functionality depends on the type of its argument:
#
# {Number}
# : Multiplies the two numbers together, converting units appropriately.
#
# {Color}
# : Multiplies each of the RGB color channels by this number.
#
# @param other [Number, Color] The right-hand side of the operator
# @return [Number, Color] The result of the operation
# @raise [NoMethodError] if `other` is an invalid type
def times(other)
if other.is_a? Number
operate(other, :*)
elsif other.is_a? Color
other.times(self)
else
raise NoMethodError.new(nil, :times)
end
end
# The SassScript `/` operation.
# Its functionality depends on the type of its argument:
#
# {Number}
# : Divides this number by the other, converting units appropriately.
#
# {Value}
# : See {Value::Base#div}.
#
# @param other [Value] The right-hand side of the operator
# @return [Value] The result of the operation
def div(other)
if other.is_a? Number
res = operate(other, :/)
if original && other.original
res.original = "#{original}/#{other.original}"
end
res
else
super
end
end
# The SassScript `%` operation.
#
# @param other [Number] The right-hand side of the operator
# @return [Number] This number modulo the other
# @raise [NoMethodError] if `other` is an invalid type
# @raise [Sass::UnitConversionError] if `other` has incompatible units
def mod(other)
if other.is_a?(Number)
operate(other, :%)
else
raise NoMethodError.new(nil, :mod)
end
end
# The SassScript `==` operation.
#
# @param other [Value] The right-hand side of the operator
# @return [Boolean] Whether this number is equal to the other object
def eq(other)
return Bool::FALSE unless other.is_a?(Sass::Script::Value::Number)
this = self
begin
if unitless?
this = this.coerce(other.numerator_units, other.denominator_units)
else
other = other.coerce(@numerator_units, @denominator_units)
end
rescue Sass::UnitConversionError
return Bool::FALSE
end
Bool.new(this.value == other.value)
end
def hash
[value, numerator_units, denominator_units].hash
end
# Hash-equality works differently than `==` equality for numbers.
# Hash-equality must be transitive, so it just compares the exact value,
# numerator units, and denominator units.
def eql?(other)
value == other.value && numerator_units == other.numerator_units &&
denominator_units == other.denominator_units
end
# The SassScript `>` operation.
#
# @param other [Number] The right-hand side of the operator
# @return [Boolean] Whether this number is greater than the other
# @raise [NoMethodError] if `other` is an invalid type
def gt(other)
raise NoMethodError.new(nil, :gt) unless other.is_a?(Number)
operate(other, :>)
end
# The SassScript `>=` operation.
#
# @param other [Number] The right-hand side of the operator
# @return [Boolean] Whether this number is greater than or equal to the other
# @raise [NoMethodError] if `other` is an invalid type
def gte(other)
raise NoMethodError.new(nil, :gte) unless other.is_a?(Number)
operate(other, :>=)
end
# The SassScript `<` operation.
#
# @param other [Number] The right-hand side of the operator
# @return [Boolean] Whether this number is less than the other
# @raise [NoMethodError] if `other` is an invalid type
def lt(other)
raise NoMethodError.new(nil, :lt) unless other.is_a?(Number)
operate(other, :<)
end
# The SassScript `<=` operation.
#
# @param other [Number] The right-hand side of the operator
# @return [Boolean] Whether this number is less than or equal to the other
# @raise [NoMethodError] if `other` is an invalid type
def lte(other)
raise NoMethodError.new(nil, :lte) unless other.is_a?(Number)
operate(other, :<=)
end
# @return [String] The CSS representation of this number
# @raise [Sass::SyntaxError] if this number has units that can't be used in CSS
# (e.g. `px*in`)
def to_s(opts = {})
return original if original
raise Sass::SyntaxError.new("#{inspect} isn't a valid CSS value.") unless legal_units?
inspect
end
# Returns a readable representation of this number.
#
# This representation is valid CSS (and valid SassScript)
# as long as there is only one unit.
#
# @return [String] The representation
def inspect(opts = {})
return original if original
value = self.class.round(self.value)
str = value.to_s
# Ruby will occasionally print in scientific notation if the number is
# small enough. That's technically valid CSS, but it's not well-supported
# and confusing.
str = ("%0.#{self.class.precision}f" % value).gsub(/0*$/, '') if str.include?('e')
unitless? ? str : "#{str}#{unit_str}"
end
alias_method :to_sass, :inspect
# @return [Fixnum] The integer value of the number
# @raise [Sass::SyntaxError] if the number isn't an integer
def to_i
super unless int?
value.to_i
end
# @return [Boolean] Whether or not this number is an integer.
def int?
value % 1 == 0.0
end
# @return [Boolean] Whether or not this number has no units.
def unitless?
@numerator_units.empty? && @denominator_units.empty?
end
# Checks whether the number has the numerator unit specified.
#
# @example
# number = Sass::Script::Value::Number.new(10, "px")
# number.is_unit?("px") => true
# number.is_unit?(nil) => false
#
# @param unit [::String, nil] The unit the number should have or nil if the number
# should be unitless.
# @see Number#unitless? The unitless? method may be more readable.
def is_unit?(unit)
if unit
denominator_units.size == 0 && numerator_units.size == 1 && numerator_units.first == unit
else
unitless?
end
end
# @return [Boolean] Whether or not this number has units that can be represented in CSS
# (that is, zero or one \{#numerator\_units}).
def legal_units?
(@numerator_units.empty? || @numerator_units.size == 1) && @denominator_units.empty?
end
# Returns this number converted to other units.
# The conversion takes into account the relationship between e.g. mm and cm,
# as well as between e.g. in and cm.
#
# If this number has no units, it will simply return itself
# with the given units.
#
# An incompatible coercion, e.g. between px and cm, will raise an error.
#
# @param num_units [Array<String>] The numerator units to coerce this number into.
# See {\#numerator\_units}
# @param den_units [Array<String>] The denominator units to coerce this number into.
# See {\#denominator\_units}
# @return [Number] The number with the new units
# @raise [Sass::UnitConversionError] if the given units are incompatible with the number's
# current units
def coerce(num_units, den_units)
Number.new(if unitless?
value
else
value * coercion_factor(@numerator_units, num_units) /
coercion_factor(@denominator_units, den_units)
end, num_units, den_units)
end
# @param other [Number] A number to decide if it can be compared with this number.
# @return [Boolean] Whether or not this number can be compared with the other.
def comparable_to?(other)
operate(other, :+)
true
rescue Sass::UnitConversionError
false
end
# Returns a human readable representation of the units in this number.
# For complex units this takes the form of:
# numerator_unit1 * numerator_unit2 / denominator_unit1 * denominator_unit2
# @return [String] a string that represents the units in this number
def unit_str
rv = @numerator_units.sort.join("*")
if @denominator_units.any?
rv << "/"
rv << @denominator_units.sort.join("*")
end
rv
end
private
# @private
def self.round(num)
if num.is_a?(Float) && (num.infinite? || num.nan?)
num
elsif num % 1 == 0.0
num.to_i
else
((num * precision_factor).round / precision_factor).to_f
end
end
OPERATIONS = [:+, :-, :<=, :<, :>, :>=, :%]
def operate(other, operation)
this = self
if OPERATIONS.include?(operation)
if unitless?
this = this.coerce(other.numerator_units, other.denominator_units)
else
other = other.coerce(@numerator_units, @denominator_units)
end
end
# avoid integer division
value = :/ == operation ? this.value.to_f : this.value
result = value.send(operation, other.value)
if result.is_a?(Numeric)
Number.new(result, *compute_units(this, other, operation))
else # Boolean op
Bool.new(result)
end
end
def coercion_factor(from_units, to_units)
# get a list of unmatched units
from_units, to_units = sans_common_units(from_units, to_units)
if from_units.size != to_units.size || !convertable?(from_units | to_units)
raise Sass::UnitConversionError.new(
"Incompatible units: '#{from_units.join('*')}' and '#{to_units.join('*')}'.")
end
from_units.zip(to_units).inject(1) {|m, p| m * conversion_factor(p[0], p[1])}
end
def compute_units(this, other, operation)
case operation
when :*
[this.numerator_units + other.numerator_units,
this.denominator_units + other.denominator_units]
when :/
[this.numerator_units + other.denominator_units,
this.denominator_units + other.numerator_units]
else
[this.numerator_units, this.denominator_units]
end
end
def normalize!
return if unitless?
@numerator_units, @denominator_units =
sans_common_units(@numerator_units, @denominator_units)
@denominator_units.each_with_index do |d, i|
if convertable?(d) && (u = @numerator_units.find(&method(:convertable?)))
@value /= conversion_factor(d, u)
@denominator_units.delete_at(i)
@numerator_units.delete_at(@numerator_units.index(u))
end
end
end
# This is the source data for all the unit logic. It's pre-processed to make
# it efficient to figure out whether a set of units is mutually compatible
# and what the conversion ratio is between two units.
#
# These come from http://www.w3.org/TR/2012/WD-css3-values-20120308/.
relative_sizes = [
{
'in' => Rational(1),
'cm' => Rational(1, 2.54),
'pc' => Rational(1, 6),
'mm' => Rational(1, 25.4),
'pt' => Rational(1, 72),
'px' => Rational(1, 96)
},
{
'deg' => Rational(1, 360),
'grad' => Rational(1, 400),
'rad' => Rational(1, 2 * Math::PI),
'turn' => Rational(1)
},
{
's' => Rational(1),
'ms' => Rational(1, 1000)
},
{
'Hz' => Rational(1),
'kHz' => Rational(1000)
},
{
'dpi' => Rational(1),
'dpcm' => Rational(1, 2.54),
'dppx' => Rational(1, 96)
}
]
# A hash from each known unit to the set of units that it's mutually
# convertible with.
MUTUALLY_CONVERTIBLE = {}
relative_sizes.map do |values|
set = values.keys.to_set
values.keys.each {|name| MUTUALLY_CONVERTIBLE[name] = set}
end
# A two-dimensional hash from two units to the conversion ratio between
# them. Multiply `X` by `CONVERSION_TABLE[X][Y]` to convert it to `Y`.
CONVERSION_TABLE = {}
relative_sizes.each do |values|
values.each do |(name1, value1)|
CONVERSION_TABLE[name1] ||= {}
values.each do |(name2, value2)|
value = value1 / value2
CONVERSION_TABLE[name1][name2] = value.denominator == 1 ? value.to_i : value.to_f
end
end
end
def conversion_factor(from_unit, to_unit)
CONVERSION_TABLE[from_unit][to_unit]
end
def convertable?(units)
units = Array(units).to_set
return true if units.empty?
return false unless (mutually_convertible = MUTUALLY_CONVERTIBLE[units.first])
units.subset?(mutually_convertible)
end
def sans_common_units(units1, units2)
units2 = units2.dup
# Can't just use -, because we want px*px to coerce properly to px*mm
units1 = units1.map do |u|
j = units2.index(u)
next u unless j
units2.delete_at(j)
nil
end
units1.compact!
return units1, units2
end
end
end
| 32.161959 | 97 | 0.623492 |
abb08a3ae7f208e143cd1158198ffb4fdb12d293 | 372 | require "bundler/setup"
require "protest_articles"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| 24.8 | 66 | 0.758065 |
abb22d30885dbc5e637c6a0f8cb05dbc8d818067 | 1,005 | # coding: utf-8
Gem::Specification.new do |spec|
spec.name = 'agency-jekyll-theme'
spec.version = '1.0.0'
spec.authors = ["Klaudia Alvarez"]
spec.email = '[email protected]'
spec.summary = "Agency Jekyll Theme is a jekyll theme gem, based on Agency theme created by Start Bootstrap."
spec.description = "Agency Jekyll Theme is a single-page theme. It features several content sections, a responsive portfolio grid with hover effects, full page portfolio item modals, a responsive timeline, and a contact form."
spec.homepage = "http://github.com/laklau/agency-jekyll-theme"
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").select { |f| f.match(%r{^(assets|_layouts|_includes|_sass|_data|vendor|LICENSE|README.md|index.md|screenshot.png)}i) }
spec.add_development_dependency "jekyll", "~> 3.3"
spec.add_development_dependency "bundler", "~> 1.12"
spec.add_development_dependency "rake", "~> 10.0"
end
| 52.894737 | 230 | 0.689552 |
91d4182f7d3a74203f9f8e4e9e3b7ad6c9ba55ec | 879 | # Pull down EPEL repo
remote_file "/tmp/epel-release-latest-7.noarch.rpm" do
source "https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm"
owner 'root'
group 'root'
mode 0755
end
# Install epel-release package
package 'epel-release' do
source "/tmp/epel-release-latest-7.noarch.rpm"
action :install
end
# Install nginx package
package 'nginx' do
end
# Copy index.html file to web root
cookbook_file '/usr/share/nginx/html/index.html' do
source 'index.html'
end
# Copy image to web root
cookbook_file '/usr/share/nginx/html/hello-nurse.jpg' do
source 'hello-nurse.jpg'
end
# Copy nginx.conf to /etc/nginx
cookbook_file '/etc/nginx/nginx.conf' do
source 'nginx.conf'
end
# Ensure nginx service is started and enabled
service 'nginx' do
supports status: true, restart: true, reload: true
action [:start, :enable]
end | 23.131579 | 83 | 0.724687 |
79c7efbb18eecb8c80f443809d0a222873a18950 | 223 | service 'explicit_action' do
action :start
end
service 'with_attributes' do
pattern 'pattern'
action :start
end
service 'specifying the identity attribute' do
service_name 'identity_attribute'
action :start
end
| 15.928571 | 46 | 0.775785 |
87094531df386a633964f740679632e42c19c228 | 765 | require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require "capybara/rails"
require 'fuubar'
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
config.fuubar_progress_bar_options = { format: 'Completed Tests <%B> %p%% %a' }
end
| 30.6 | 86 | 0.756863 |
4a12baf19d9320d759a9bcea82fe9ca8ae387101 | 5,112 | FactoryBot.define do
factory :school_profile, class: 'Schools::SchoolProfile' do
before(:create) do |sp|
sp.bookings_school = Bookings::School.find_by(urn: 123456) || create(:bookings_school, urn: 123456)
end
trait :with_dbs_requirement do
after :build do |profile|
profile.dbs_requirement = FactoryBot.build :dbs_requirement
end
end
trait :with_candidate_requirements_choice do
after :build do |profile|
profile.candidate_requirements_choice = \
FactoryBot.build :candidate_requirements_choice
end
end
trait :without_candidate_requirements_choice do
after :build do |profile|
profile.candidate_requirements_choice = \
FactoryBot.build :candidate_requirements_choice,
has_requirements: false
end
end
trait :with_candidate_requirements_selection do
candidate_requirements_selection_step_completed { true }
after :build do |profile|
profile.candidate_requirements_selection = \
FactoryBot.build :candidate_requirements_selection
end
end
trait :with_fees do
fees_administration_fees { true }
fees_dbs_fees { true }
fees_other_fees { true }
end
trait :with_administration_fee do
administration_fee_amount_pounds { 123.45 }
administration_fee_description { 'General administration' }
administration_fee_interval { 'Daily' }
administration_fee_payment_method { 'Travelers Cheques' }
administration_fee_step_completed { true }
end
trait :with_dbs_fee do
dbs_fee_amount_pounds { 200 }
dbs_fee_description { 'DBS check' }
dbs_fee_interval { 'One-off' }
dbs_fee_payment_method { 'Ethereum' }
dbs_fee_step_completed { true }
end
trait :with_other_fee do
other_fee_amount_pounds { 444.44 }
other_fee_description { 'Owl repellent / other protective gear' }
other_fee_interval { 'One-off' }
other_fee_payment_method { 'Stamps' }
other_fee_step_completed { true }
end
trait :with_phases do
phases_list_primary { true }
phases_list_secondary { true }
phases_list_college { true }
end
trait :with_only_early_years_phase do
phases_list_primary { true }
phases_list_secondary { false }
phases_list_college { false }
end
trait :with_key_stage_list do
key_stage_list_early_years { true }
key_stage_list_key_stage_1 { true }
key_stage_list_key_stage_2 { true }
end
trait :with_subjects do
after :create do |profile|
profile.subjects << FactoryBot.create(:bookings_subject)
end
end
trait :with_description do
after :build do |profile|
profile.description = FactoryBot.build :description
end
end
transient do
parking { true }
times_flexible { true }
end
trait :with_candidate_experience_detail do
after :build do |profile, evaluator|
traits = []
if evaluator.parking == false
traits << :without_parking
end
if evaluator.times_flexible == false
traits << :without_flexible_times
end
profile.candidate_experience_detail = FactoryBot.build :candidate_experience_detail, *traits
end
end
trait :with_access_needs_support do
after :build do |profile|
profile.access_needs_support = FactoryBot.build :access_needs_support
end
end
trait :without_access_needs_support do
after :build do |profile|
profile.access_needs_support = \
FactoryBot.build :access_needs_support, supports_access_needs: false
end
end
trait :with_access_needs_detail do
after :build do |profile|
profile.access_needs_detail = FactoryBot.build :access_needs_detail
end
end
trait :with_disability_confident do
after :build do |profile|
profile.disability_confident = FactoryBot.build :disability_confident
end
end
trait :with_access_needs_policy do
after :build do |profile|
profile.access_needs_policy = FactoryBot.build :access_needs_policy
end
end
trait :with_experience_outline do
after :build do |profile|
profile.experience_outline = FactoryBot.build :experience_outline
end
end
trait :with_admin_contact do
after :build do |profile|
profile.admin_contact = FactoryBot.build :admin_contact
end
end
trait :completed do
with_dbs_requirement
with_candidate_requirements_choice
with_candidate_requirements_selection
with_fees
with_administration_fee
with_dbs_fee
with_other_fee
with_only_early_years_phase
with_phases
with_key_stage_list
with_subjects
with_description
with_candidate_experience_detail
with_access_needs_support
with_access_needs_detail
with_disability_confident
with_access_needs_policy
with_experience_outline
with_admin_contact
end
end
end
| 27.934426 | 105 | 0.689554 |
bbffda50e4bc08f5832e095c987e1635cc112377 | 1,345 | module Network
class Config
attr_reader :cells
COUNTRY_REGEX = /country=(?<country>[A-Z]{2})/
UPDATE_CONFIG_REGEX = /update_config=(?<update_config>[0-1])/
NETWORK_REGEX = /(?<network>network\s*=\s*{(?:\s*[^}]*){2}})/x
def initialize
file_output = `cat /etc/wpa_supplicant/wpa_supplicant.conf`
country_match = COUNTRY_REGEX.match(file_output)
@country = country_match[:country] if country_match
update_config_match = UPDATE_CONFIG_REGEX.match(file_output)
@update_config = update_config_match[:update_config] if country_match
@cells = file_output.scan(NETWORK_REGEX).flatten.map do |network|
Network::Cell.new(network)
end
end
def set_priority(cell)
@cells.each do |c|
c.set_priority false
end
cell.set_priority true
end
def remove_cells(cells)
@cells = @cells.select do |cell|
!cells.include? cell
end
end
def to_s
[
"ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev",
"country=#{@country}",
"update_config=#{@update_config}",
""
].concat(
@cells.map do |cell|
cell.to_s
end
).join("\n")
end
def save!
File.write("/etc/wpa_supplicant/wpa_supplicant.conf", to_s)
end
end
end
| 24.907407 | 75 | 0.613383 |
87189b736a1722d35926b034ede6488d198164ac | 3,370 | #
# Copyright (c) 2021 Michael Morris. All Rights Reserved.
#
# Licensed under the MIT license (the "License"). You may not use this file except in compliance
# with the License. A copy of the License is located at
#
# https://github.com/mmmorris1975/aws-runas/blob/master/LICENSE
#
# or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
# for the specific language governing permissions and limitations under the License.
#
require 'spec_helper'
require_relative 'shared_examples'
describe 'okta saml credentials' do
before(:all) do
# !!!! command to test is echoed in the output, don't put password as a cmdline option !!!!
ENV['SAML_PASSWORD'] = ENV['OKTA_PASSWORD']
end
after(:each) do
FileUtils.rm_f(Pathname.glob(Pathname($config_path).join(".aws_saml_role_*")))
end
after(:all) do
FileUtils.rm_f(Pathname.glob(Pathname($config_path).join(".aws_runas.cookies")))
ENV.delete('SAML_PASSWORD')
end
describe 'with command line config' do
if ENV.has_key?('OKTA_SAML_URL')
it_should_behave_like 'saml role credentials', 'okta-saml', "-S '#{ENV['OKTA_SAML_URL']}'"
else
skip 'OKTA_SAML_URL not set, skipping'
end
end
describe 'with env var config' do
before(:all) do
ENV['AWS_PROFILE'] = 'okta-saml'
ENV['SAML_AUTH_URL'] = ENV['OKTA_SAML_URL']
end
if ENV.has_key?('OKTA_SAML_URL')
it_should_behave_like 'saml role credentials'
else
skip 'OKTA_SAML_URL not set, skipping'
end
after(:all) do
ENV.delete('SAML_AUTH_URL')
ENV.delete('AWS_PROFILE')
end
end
end
describe 'okta web identity credentials' do
before(:all) do
# !!!! command to test is echoed in the output, don't put password as a cmdline option !!!!
ENV['WEB_PASSWORD'] = ENV['OKTA_PASSWORD']
end
after(:each) do
FileUtils.rm_f(Pathname.glob(Pathname($config_path).join(".aws_web_role_*")))
end
after(:all) do
FileUtils.rm_f(Pathname.glob(Pathname($config_path).join(".aws_runas.cookies")))
FileUtils.rm_f(Pathname.glob(Pathname($config_path).join(".aws_runas_identity_token.cache")))
ENV.delete('WEB_PASSWORD')
end
describe 'with command line config' do
if ENV.has_key?('OKTA_OIDC_URL')
opts = "-W '#{ENV['OKTA_OIDC_URL']}' -C '#{ENV['OKTA_OIDC_CLIENT_ID']}'"
it_should_behave_like 'web identity role credentials', 'okta-oidc', opts
else
skip 'OKTA_OIDC_URL not set, skipping'
end
end
describe 'with env var config' do
before(:all) do
ENV['AWS_PROFILE'] = 'okta-oidc'
ENV['WEB_AUTH_URL'] = ENV['OKTA_OIDC_URL']
ENV['WEB_CLIENT_ID'] = ENV['OKTA_OIDC_CLIENT_ID']
end
if ENV.has_key?('OKTA_OIDC_URL')
it_should_behave_like 'web identity role credentials'
else
skip 'OKTA_OIDC_URL not set, skipping'
end
after(:all) do
ENV.delete('WEB_AUTH_URL')
ENV.delete('WEB_CLIENT_ID')
ENV.delete('AWS_PROFILE')
end
end
end | 32.403846 | 102 | 0.630861 |
7a7c0db5e8a28aaa274e173b4f69f87a42ff2059 | 2,452 | module Jets::Resource::ApiGateway
class Authorizer < Jets::Resource::Base
def initialize(props={})
@props = props # associated_properties from dsl.rb
end
def definition
{
authorizer_logical_id => {
type: "AWS::ApiGateway::Authorizer",
properties: props,
}
}
end
def props
default = {
# authorizer_credentials: '',
# authorizer_result_ttl_in_seconds: '',
# auth_type: '',
# identity_source: '', # required
# identity_validation_expression: '',
# name: '',
# provider_arns: [],
rest_api_id: '!Ref RestApi', # Required: Yes
type: '', # Required: Yes
}
unless @props[:type].to_s.upcase == 'COGNITO_USER_POOLS'
@props[:authorizer_uri] = { # Required: Conditional
"Fn::Join" => ['', [
'arn:aws:apigateway:',
"!Ref 'AWS::Region'",
':lambda:path/2015-03-31/functions/',
{"Fn::GetAtt" => ["{namespace}LambdaFunction", "Arn"]},
'/invocations'
]]
}
end
@props[:authorizer_result_ttl_in_seconds] = @props.delete(:ttl) if @props[:ttl]
normalize_type!(@props)
normalize_identity_source!(@props)
default.merge(@props)
end
def authorizer_logical_id
"{namespace}_authorizer" # IE: protect_authorizer
end
def outputs
# IE: ProtectAuthorizer: !Ref ProtectAuthorizer
{
logical_id => "!Ref #{logical_id}",
}
end
private
# Also sets a default if it's not provided
def normalize_type!(props)
type = props[:type] || :request
@props[:type] = type.to_s.upcase
end
# Also sets a default if it's not provided
def normalize_identity_source!(props)
identity_source = props[:identity_source] || Jets.config.api.authorizers.default_token_source
# request authorizer type can have multiple identity sources.
# token authorizer type has only one identity source.
# We handle both cases.
identity_sources = identity_source.split(',') # to handle multipe
identity_sources.map! do |source|
if source.include?(".") # if '.' is detected assume full identify source provided
source
else
"method.request.header.#{source}" # convention
end
end
@props[:identity_source] = identity_sources.join(',')
end
end
end
| 29.542169 | 99 | 0.593393 |
28c422921acc83546cf309dd262d844fa5485bc6 | 502 | require File.expand_path('boot', __dir__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module TestApp
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
end
end
| 31.375 | 82 | 0.760956 |
e8f9f09e2e2660ad1728392a794bc63fb274fb5f | 113 | json.extract! contact, :id, :email, :phone, :created_at, :updated_at
json.url contact_url(contact, format: :json) | 56.5 | 68 | 0.752212 |
bf77eafa626a1aaf092411f30ff221b76d6d8500 | 1,007 | require "story_teller"
require "story_teller/sidekiq"
describe StoryTeller::Sidekiq do
around(:each) do |example|
StoryTeller.clear!
example.run
StoryTeller.clear!
end
context "clearing the books" do
it "clears the books before the middleware exits" do
middleware = StoryTeller::Sidekiq.new
3.times do
middleware.call("worker", "job", "queue") do
StoryTeller.tell(StoryTeller::Story.new(message: "test"))
end
end
expect(StoryTeller.empty?).to eq(true)
end
it "clears the books even if an error is thrown" do
middleware = StoryTeller::Sidekiq.new
expect {
middleware.call("worker", "job", "queue") do
StoryTeller.tell(StoryTeller::Story.new(message: "test"))
raise StandardError.new("Oops!")
end
}.to raise_error(StandardError)
expect(StoryTeller.send(:book).dispatcher.events.size).to_not eq(0)
expect(StoryTeller.empty?).to eq(true)
end
end
end
| 27.216216 | 73 | 0.650447 |
1c59c5e2a72fb7d7bd0899c3dc14239e8898c7f6 | 683 | Rails.application.routes.draw do
# Pages controller Route
root 'pages#index'
# Sessions controller routes
get '/signin', to: 'sessions#new'
post '/signin', to: 'sessions#create'
delete '/signout', to: 'sessions#destroy'
# User controller routes
get '/signup', to: 'users#new'
post '/users', to: 'users#create'
get '/users/:id', to: 'users#show', as: 'profile'
# Categories controller routes
resources :categories, only: [:show]
# Reviews controller routes
resources :reviews, except: [:index]
# Votes controller routes
post '/reviews/:id/votes', to: 'votes#create', as: 'vote'
delete '/reviews/:id/votes', to: 'votes#destroy', as: 'unvote'
end
| 27.32 | 64 | 0.674963 |
acc3b679cff44c4e88252a6806b5e50028427cb9 | 124 | module SendgridThreads
class Exception < StandardError
def initialize(message)
super(message)
end
end
end
| 15.5 | 33 | 0.717742 |
ab002a840e5499006aeff47a8b1801cf5de87b35 | 322 | require File.dirname(__FILE__) + "/test_helper"
class MoneyTest < Test::Unit::TestCase
should "parse '-14.24 EUR' as 14.24 EUR" do
assert_equal Money.new(-1424, "EUR"), "-14.24 EUR".to_money
end
should "parse '14.24 CAD' as 14.24 CAD" do
assert_equal Money.new(1424, "CAD"), "14.24 CAD".to_money
end
end
| 26.833333 | 63 | 0.677019 |
1c1d0aee176ae5d3c1a29d0544bf309880d5edee | 1,821 | require 'spec_helper'
describe SlimLint::Runner do
let(:options) { {} }
let(:runner) { described_class.new }
before do
runner.stub(:extract_applicable_files).and_return(files)
end
describe '#run' do
let(:files) { %w[file1.slim file2.slim] }
let(:mock_linter) { double('linter', lints: [], name: 'Blah') }
let(:options) do
{
files: files,
}
end
subject { runner.run(options) }
before do
runner.stub(:collect_lints).and_return([])
end
it 'searches for lints in each file' do
runner.should_receive(:collect_lints).exactly(files.size).times
subject
end
context 'when :config_file option is specified' do
let(:options) { { config_file: 'some-config.yml' } }
let(:config) { double('config') }
it 'loads that specified configuration file' do
config.stub(:for_linter).and_return('enabled' => true)
SlimLint::ConfigurationLoader.should_receive(:load_file)
.with('some-config.yml')
.and_return(config)
subject
end
end
context 'when `exclude` global config option specifies a list of patterns' do
let(:options) { { config: config, files: files } }
let(:config) { SlimLint::Configuration.new(config_hash) }
let(:config_hash) { { 'exclude' => 'exclude-this-file.slim' } }
before do
runner.stub(:extract_applicable_files).and_call_original
end
it 'passes the global exclude patterns to the FileFinder' do
SlimLint::FileFinder.any_instance
.should_receive(:find)
.with(files, ['exclude-this-file.slim'])
.and_return([])
subject
end
end
end
end
| 28.015385 | 81 | 0.587589 |
4a1fe95e0fd22a0b9a61105d6d2803e926e515a5 | 5,950 | Hadean::Application.configure do
# Rails 4
config.eager_load = true
config.assets.js_compressor = :uglifier
# Settings specified here will take precedence over those in config/environment.rb
config.force_ssl = true
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
config.cache_classes = true
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# config.assets.precompile += %w( *.css *.js )
# Add the fonts path
config.assets.paths << "#{Rails.root}/app/assets/fonts"
# Precompile additional assets
config.assets.precompile += %w( .svg .eot .woff .ttf )
config.assets.precompile += %w( *.js )
config.assets.precompile += [ 'admin.css',
'admin/app.css',
'admin/cart.css',
'admin/foundation.css',
'admin/normalize.css',
'admin/help.css',
'admin/ie.css',
'autocomplete.css',
'application.css',
'chosen.css',
'foundation.css',
'foundation_and_overrides.css',
'home_page.css',
'ie.css',
'ie6.css',
'login.css',
'markdown.css',
'myaccount.css',
'normalize.css',
'pikachoose_product.css',
'product_page.css',
'products_page.css',
'shopping_cart_page.css',
'signup.css',
'site/app.css',
'sprite.css',
'tables.css',
'cupertino/jquery-ui-1.8.12.custom.css',# in vendor
'modstyles.css', # in vendor
'scaffold.css' # in vendor
]
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
if ENV['FOG_DIRECTORY'].present?
config.action_controller.asset_host = "https://#{ENV['FOG_DIRECTORY']}.s3.amazonaws.com"
end
# Specifies the header that your server uses for sending files
config.action_dispatch.x_sendfile_header = "X-Sendfile"
# For nginx:
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
# If you have no front-end server that supports something like X-Sendfile,
# just comment this out and Rails will serve the files
config.cache_store = :memory_store
#config.cache_store = :dalli_store
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Disable Rails's static asset server
# In production, Apache or nginx will already do this
config.serve_static_assets = true
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
config.action_mailer.default_url_options = { :host => 'ror-e.herokuapp.com' }
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
config.after_initialize do
#Formtastic::SemanticFormBuilder.send(:include, Formtastic::DatePicker)
#Formtastic::SemanticFormBuilder.send(:include, Formtastic::FuturePicker)
#Formtastic::SemanticFormBuilder.send(:include, Formtastic::YearPicker)
ActiveMerchant::Billing::Base.mode = :test
#::GATEWAY = ActiveMerchant::Billing::PaypalGateway.new(
# :login => Settings.paypal.login,
# :password => Settings.paypal.password,
# :signature => Settings.paypal.signature
#)
::GATEWAY = ActiveMerchant::Billing::AuthorizeNetGateway.new(
:login => Settings.authnet.login,
:password => Settings.authnet.password,
:test => true
)
::CIM_GATEWAY = ActiveMerchant::Billing::AuthorizeNetCimGateway.new(
:login => Settings.authnet.login,
:password => Settings.authnet.password,
:test => true
)
Paperclip::Attachment.default_options[:storage] = :s3
#::GATEWAY = ActiveMerchant::Billing::BraintreeGateway.new(
# :login => Settings.braintree.login,
# :password => Settings.braintree.password
#)
end
PAPERCLIP_STORAGE_OPTS = { :styles => {:mini => '48x48>',
:small => '100x100>',
:medium => '200x200>',
:product => '320x320>',
:large => '600x600>' },
:default_style => :product,
:url => "/assets/products/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/products/:id/:style/:basename.:extension" }
end
| 39.403974 | 109 | 0.568571 |
628b4293f36417597a018d964e310733ceb0e400 | 159 | module AdaptivePayments
class FundingTypeList < JsonModel
attribute :funding_type_info, NodeList[FundingTypeInfo], :param => "fundingTypeInfo"
end
end
| 26.5 | 88 | 0.792453 |
1c7b9be7a8a57b893a17752a4512751c86ff4976 | 1,325 | ##
# @api REST
# Describes an SSH Key associated with a user
# @see RestUser
#
# Example:
# ```
# <key>
# <name>default</name>
# <content>AAAAB3Nz...SeRRcMw==</content>
# <type>ssh-rsa</type>
# <links>
# ...
# </links>
# </key>
# ```
#
# @!attribute [r] name
# @return [String] Name of the ssh key
# @!attribute [r] content
# @return [String] Content of the SSH public key
# @!attribute [r] type
# @return [String] Type of the ssh-key. Eg: ssh-rsa
class RestKey < OpenShift::Model
attr_accessor :name, :content, :type, :links
def initialize(key, url, nolinks=false)
self.name= key.name
self.content = key.content
self.type = key.type || SshKey::DEFAULT_SSH_KEY_TYPE
self.links = {
"GET" => Link.new("Get SSH key", "GET", URI::join(url, "user/keys/#{name}")),
"UPDATE" => Link.new("Update SSH key", "PUT", URI::join(url, "user/keys/#{name}"), [
Param.new("type", "string", "Type of Key", SshKey.get_valid_ssh_key_types),
Param.new("content", "string", "The key portion of an rsa key (excluding ssh key type and comment)"),
]),
"DELETE" => Link.new("Delete SSH key", "DELETE", URI::join(url, "user/keys/#{name}"))
} unless nolinks
end
def to_xml(options={})
options[:tag_name] = "key"
super(options)
end
end
| 28.191489 | 109 | 0.602264 |
031cd25a10d1856bd97be096321aa1959bc1ad6d | 4,713 | # frozen_string_literal: true
RSpec.describe SqlAttributes do
let!(:invoice) { Invoice.create!(number: '2020-0042', reference: 'My cool new course') }
let!(:invoice_lines) do
[
invoice.invoice_lines.create!(name: 'Introduction', units: 1, unit_price: 52.25),
invoice.invoice_lines.create!(name: 'Books', units: 3, unit_price: 1.99)
]
end
let!(:payments) do
[
invoice.payments.create!(amount: 10.25),
invoice.payments.create!(amount: 10)
]
end
it 'has a version number' do
expect(described_class::VERSION).not_to be nil
end
describe '#sql_attributes' do
it 'returns all defined SQL attributes with their squished subquery' do
expect(Invoice.sql_attributes.symbolize_keys).to eq(
title: "number || ' | ' || reference",
total_amount: 'SELECT SUM(units * unit_price) FROM invoice_lines WHERE invoice_lines.invoice_id = invoices.id',
total_paid: 'SELECT SUM(amount) FROM payments WHERE payments.invoice_id = invoices.id'
)
end
it 'can also be fetched by string' do
expect(Invoice.sql_attributes).to have_key(:title)
expect(Invoice.sql_attributes).to have_key('title')
expect(Invoice.sql_attributes).to have_key(:total_paid)
expect(Invoice.sql_attributes).to have_key('total_paid')
end
end
describe '#with_<NAME> scopes' do
it 'loads the virtual string concatenated attribute' do
expect(Invoice.with_title.find(invoice.id).title).to eq '2020-0042 | My cool new course'
end
it 'loads the virtual subquery attibute' do
expect(Invoice.with_total_amount.find(invoice.id).total_amount).to eq 58.22
end
it 'does not load other attributes' do
expect do
Invoice.with_title.find(invoice.id).total_amount
end.to raise_error SqlAttributes::NotLoaded
end
end
describe '#with_sql_attributes' do
it 'loads the attribute if a single string is provided' do
expect(Invoice.with_sql_attributes('title').find(invoice.id).title).to eq '2020-0042 | My cool new course'
end
it 'loads the attribute if a single symbol is provided' do
expect(Invoice.with_sql_attributes(:title).find(invoice.id).title).to eq '2020-0042 | My cool new course'
end
it 'does not load other attributes if single attribute is provided' do
expect do
Invoice.with_sql_attributes(:title).find(invoice.id).total_amount
end.to raise_error SqlAttributes::NotLoaded
end
it 'loads both attributes if two arguments are provided' do
invoice_with_attributes = Invoice.with_sql_attributes('total_amount', :title).find(invoice.id)
expect(invoice_with_attributes.title).to eq '2020-0042 | My cool new course'
expect(invoice_with_attributes.total_amount).to eq 58.22
expect { invoice_with_attributes.total_paid }.to raise_error SqlAttributes::NotLoaded
end
it 'loads all attributes if no argument provided' do
invoice_with_attributes = Invoice.with_sql_attributes.find(invoice.id)
expect(invoice_with_attributes.title).to eq '2020-0042 | My cool new course'
expect(invoice_with_attributes.total_amount).to eq 58.22
expect(invoice_with_attributes.total_paid).to eq 20.25
end
it 'loads no attributes if argument is nil' do
invoice_with_attributes = Invoice.with_sql_attributes(nil).find(invoice.id)
expect { invoice_with_attributes.title }.to raise_error SqlAttributes::NotLoaded
expect { invoice_with_attributes.total_amount }.to raise_error SqlAttributes::NotLoaded
expect { invoice_with_attributes.total_paid }.to raise_error SqlAttributes::NotLoaded
end
it 'loads no attributes if argument is empty array' do
invoice_with_attributes = Invoice.with_sql_attributes([]).find(invoice.id)
expect { invoice_with_attributes.title }.to raise_error SqlAttributes::NotLoaded
expect { invoice_with_attributes.total_amount }.to raise_error SqlAttributes::NotLoaded
expect { invoice_with_attributes.total_paid }.to raise_error SqlAttributes::NotLoaded
end
it 'loads both attributes if two attributes are provided in an array' do
invoice_with_attributes = Invoice.with_sql_attributes(['total_amount', :title]).find(invoice.id)
expect(invoice_with_attributes.title).to eq '2020-0042 | My cool new course'
expect(invoice_with_attributes.total_amount).to eq 58.22
expect { invoice_with_attributes.total_paid }.to raise_error SqlAttributes::NotLoaded
end
it 'raises an error if attribute is unknown' do
expect do
Invoice.with_sql_attributes(:unknown_attribute).find(invoice.id)
end.to raise_error SqlAttributes::NotDefined
end
end
end
| 42.080357 | 119 | 0.728835 |
33eb1235fcaf6952221c66cb37739f536c48cbf2 | 1,214 | require_relative "lib/ahoy/version"
Gem::Specification.new do |spec|
spec.name = "ahoy_matey"
spec.version = Ahoy::VERSION
spec.summary = "Simple, powerful, first-party analytics for Rails"
spec.homepage = "https://github.com/ankane/ahoy"
spec.license = "MIT"
spec.author = "Andrew Kane"
spec.email = "[email protected]"
spec.files = Dir["*.{md,txt}", "{app,config,lib,vendor}/**/*"]
spec.require_path = "lib"
spec.required_ruby_version = ">= 2.4"
spec.add_dependency "activesupport", ">= 5"
spec.add_dependency "geocoder", ">= 1.4.5"
spec.add_dependency "safely_block", ">= 0.2.1"
spec.add_dependency "device_detector"
spec.add_development_dependency "bundler"
spec.add_development_dependency "rake"
spec.add_development_dependency "minitest"
spec.add_development_dependency "combustion"
spec.add_development_dependency "rails"
spec.add_development_dependency "sqlite3"
spec.add_development_dependency "pg"
spec.add_development_dependency "mysql2"
spec.add_development_dependency "mongoid"
spec.add_development_dependency "browser", "~> 2.0"
spec.add_development_dependency "user_agent_parser"
end
| 34.685714 | 74 | 0.714168 |
085ab1e21a08c49798fdf707e7b497a6b3ed4457 | 55,776 | # Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module LoggingV2beta1
# Result returned from ListLogMetrics.
class ListLogMetricsResponse
include Google::Apis::Core::Hashable
# A list of logs-based metrics.
# Corresponds to the JSON property `metrics`
# @return [Array<Google::Apis::LoggingV2beta1::LogMetric>]
attr_accessor :metrics
# If there might be more results than appear in this response, then
# nextPageToken is included. To get the next set of results, call this method
# again using the value of nextPageToken as pageToken.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@metrics = args[:metrics] if args.key?(:metrics)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
end
end
# A generic empty message that you can re-use to avoid defining duplicated empty
# messages in your APIs. A typical example is to use it as the request or the
# response type of an API method. For instance:
# service Foo `
# rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
# `
# The JSON representation for Empty is empty JSON object ``.
class Empty
include Google::Apis::Core::Hashable
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
end
end
# An individual entry in a log.
class LogEntry
include Google::Apis::Core::Hashable
# Optional. The time the event described by the log entry occurred. If omitted,
# Stackdriver Logging will use the time the log entry is received.
# Corresponds to the JSON property `timestamp`
# @return [String]
attr_accessor :timestamp
# Required. The resource name of the log to which this log entry belongs:
# "projects/[PROJECT_ID]/logs/[LOG_ID]"
# "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]"
# [LOG_ID] must be URL-encoded within log_name. Example: "organizations/
# 1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity". [LOG_ID] must
# be less than 512 characters long and can only include the following characters:
# upper and lower case alphanumeric characters, forward-slash, underscore,
# hyphen, and period.For backward compatibility, if log_name begins with a
# forward-slash, such as /projects/..., then the log entry is ingested as usual
# but the forward-slash is removed. Listing the log entry will not show the
# leading slash and filtering for a log name with a leading slash will never
# return any results.
# Corresponds to the JSON property `logName`
# @return [String]
attr_accessor :log_name
# A common proto for logging HTTP requests. Only contains semantics defined by
# the HTTP specification. Product-specific logging information MUST be defined
# in a separate message.
# Corresponds to the JSON property `httpRequest`
# @return [Google::Apis::LoggingV2beta1::HttpRequest]
attr_accessor :http_request
# An object representing a resource that can be used for monitoring, logging,
# billing, or other purposes. Examples include virtual machine instances,
# databases, and storage devices such as disks. The type field identifies a
# MonitoredResourceDescriptor object that describes the resource's schema.
# Information in the labels field identifies the actual resource and its
# attributes according to the schema. For example, a particular Compute Engine
# VM instance could be represented by the following object, because the
# MonitoredResourceDescriptor for "gce_instance" has labels "instance_id" and "
# zone":
# ` "type": "gce_instance",
# "labels": ` "instance_id": "12345678901234",
# "zone": "us-central1-a" ``
# Corresponds to the JSON property `resource`
# @return [Google::Apis::LoggingV2beta1::MonitoredResource]
attr_accessor :resource
# The log entry payload, represented as a structure that is expressed as a JSON
# object.
# Corresponds to the JSON property `jsonPayload`
# @return [Hash<String,Object>]
attr_accessor :json_payload
# Optional. A unique ID for the log entry. If you provide this field, the
# logging service considers other log entries in the same project with the same
# ID as duplicates which can be removed. If omitted, Stackdriver Logging will
# generate a unique ID for this log entry.
# Corresponds to the JSON property `insertId`
# @return [String]
attr_accessor :insert_id
# Additional information about a potentially long-running operation with which a
# log entry is associated.
# Corresponds to the JSON property `operation`
# @return [Google::Apis::LoggingV2beta1::LogEntryOperation]
attr_accessor :operation
# The log entry payload, represented as a Unicode string (UTF-8).
# Corresponds to the JSON property `textPayload`
# @return [String]
attr_accessor :text_payload
# The log entry payload, represented as a protocol buffer. Some Google Cloud
# Platform services use this field for their log entry payloads.
# Corresponds to the JSON property `protoPayload`
# @return [Hash<String,Object>]
attr_accessor :proto_payload
# Optional. Resource name of the trace associated with the log entry, if any. If
# it contains a relative resource name, the name is assumed to be relative to //
# tracing.googleapis.com. Example: projects/my-projectid/traces/
# 06796866738c859f2f19b7cfb3214824
# Corresponds to the JSON property `trace`
# @return [String]
attr_accessor :trace
# Optional. A set of user-defined (key, value) data that provides additional
# information about the log entry.
# Corresponds to the JSON property `labels`
# @return [Hash<String,String>]
attr_accessor :labels
# Optional. The severity of the log entry. The default value is LogSeverity.
# DEFAULT.
# Corresponds to the JSON property `severity`
# @return [String]
attr_accessor :severity
# Additional information about the source code location that produced the log
# entry.
# Corresponds to the JSON property `sourceLocation`
# @return [Google::Apis::LoggingV2beta1::LogEntrySourceLocation]
attr_accessor :source_location
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@timestamp = args[:timestamp] if args.key?(:timestamp)
@log_name = args[:log_name] if args.key?(:log_name)
@http_request = args[:http_request] if args.key?(:http_request)
@resource = args[:resource] if args.key?(:resource)
@json_payload = args[:json_payload] if args.key?(:json_payload)
@insert_id = args[:insert_id] if args.key?(:insert_id)
@operation = args[:operation] if args.key?(:operation)
@text_payload = args[:text_payload] if args.key?(:text_payload)
@proto_payload = args[:proto_payload] if args.key?(:proto_payload)
@trace = args[:trace] if args.key?(:trace)
@labels = args[:labels] if args.key?(:labels)
@severity = args[:severity] if args.key?(:severity)
@source_location = args[:source_location] if args.key?(:source_location)
end
end
# Specifies a location in a source code file.
class SourceLocation
include Google::Apis::Core::Hashable
# Line within the source file.
# Corresponds to the JSON property `line`
# @return [String]
attr_accessor :line
# Source file name. Depending on the runtime environment, this might be a simple
# name or a fully-qualified name.
# Corresponds to the JSON property `file`
# @return [String]
attr_accessor :file
# Human-readable name of the function or method being invoked, with optional
# context such as the class or package name. This information is used in
# contexts such as the logs viewer, where a file and line number are less
# meaningful. The format can vary by language. For example: qual.if.ied.Class.
# method (Java), dir/package.func (Go), function (Python).
# Corresponds to the JSON property `functionName`
# @return [String]
attr_accessor :function_name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@line = args[:line] if args.key?(:line)
@file = args[:file] if args.key?(:file)
@function_name = args[:function_name] if args.key?(:function_name)
end
end
# The parameters to ListLogEntries.
class ListLogEntriesRequest
include Google::Apis::Core::Hashable
# Deprecated. Use resource_names instead. One or more project identifiers or
# project numbers from which to retrieve log entries. Example: "my-project-1A".
# If present, these project identifiers are converted to resource name format
# and added to the list of resources in resource_names.
# Corresponds to the JSON property `projectIds`
# @return [Array<String>]
attr_accessor :project_ids
# Optional. A filter that chooses which log entries to return. See Advanced Logs
# Filters. Only log entries that match the filter are returned. An empty filter
# matches all log entries in the resources listed in resource_names. Referencing
# a parent resource that is not listed in resource_names will cause the filter
# to return no results. The maximum length of the filter is 20000 characters.
# Corresponds to the JSON property `filter`
# @return [String]
attr_accessor :filter
# Optional. If present, then retrieve the next batch of results from the
# preceding call to this method. pageToken must be the value of nextPageToken
# from the previous response. The values of other method parameters should be
# identical to those in the previous call.
# Corresponds to the JSON property `pageToken`
# @return [String]
attr_accessor :page_token
# Optional. The maximum number of results to return from this request. Non-
# positive values are ignored. The presence of nextPageToken in the response
# indicates that more results might be available.
# Corresponds to the JSON property `pageSize`
# @return [Fixnum]
attr_accessor :page_size
# Optional. How the results should be sorted. Presently, the only permitted
# values are "timestamp asc" (default) and "timestamp desc". The first option
# returns entries in order of increasing values of LogEntry.timestamp (oldest
# first), and the second option returns entries in order of decreasing
# timestamps (newest first). Entries with equal timestamps are returned in order
# of LogEntry.insertId.
# Corresponds to the JSON property `orderBy`
# @return [String]
attr_accessor :order_by
# Required. Names of one or more resources from which to retrieve log entries:
# "projects/[PROJECT_ID]"
# "organizations/[ORGANIZATION_ID]"
# Projects listed in the project_ids field are added to this list.
# Corresponds to the JSON property `resourceNames`
# @return [Array<String>]
attr_accessor :resource_names
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@project_ids = args[:project_ids] if args.key?(:project_ids)
@filter = args[:filter] if args.key?(:filter)
@page_token = args[:page_token] if args.key?(:page_token)
@page_size = args[:page_size] if args.key?(:page_size)
@order_by = args[:order_by] if args.key?(:order_by)
@resource_names = args[:resource_names] if args.key?(:resource_names)
end
end
# Complete log information about a single HTTP request to an App Engine
# application.
class RequestLog
include Google::Apis::Core::Hashable
# The logged-in user who made the request.Most likely, this is the part of the
# user's email before the @ sign. The field value is the same for different
# requests from the same user, but different users can have similar names. This
# information is also available to the application via the App Engine Users API.
# This field will be populated starting with App Engine 1.9.21.
# Corresponds to the JSON property `nickname`
# @return [String]
attr_accessor :nickname
# HTTP response status code. Example: 200, 404.
# Corresponds to the JSON property `status`
# @return [Fixnum]
attr_accessor :status
# Contains the path and query portion of the URL that was requested. For example,
# if the URL was "http://example.com/app?name=val", the resource would be "/app?
# name=val". The fragment identifier, which is identified by the # character, is
# not included.
# Corresponds to the JSON property `resource`
# @return [String]
attr_accessor :resource
# Time this request spent in the pending request queue.
# Corresponds to the JSON property `pendingTime`
# @return [String]
attr_accessor :pending_time
# Task name of the request, in the case of an offline request.
# Corresponds to the JSON property `taskName`
# @return [String]
attr_accessor :task_name
# File or class that handled the request.
# Corresponds to the JSON property `urlMapEntry`
# @return [String]
attr_accessor :url_map_entry
# If the instance processing this request belongs to a manually scaled module,
# then this is the 0-based index of the instance. Otherwise, this value is -1.
# Corresponds to the JSON property `instanceIndex`
# @return [Fixnum]
attr_accessor :instance_index
# Internet host and port number of the resource being requested.
# Corresponds to the JSON property `host`
# @return [String]
attr_accessor :host
# Whether this request is finished or active.
# Corresponds to the JSON property `finished`
# @return [Boolean]
attr_accessor :finished
alias_method :finished?, :finished
# HTTP version of request. Example: "HTTP/1.1".
# Corresponds to the JSON property `httpVersion`
# @return [String]
attr_accessor :http_version
# Time when the request started.
# Corresponds to the JSON property `startTime`
# @return [String]
attr_accessor :start_time
# Latency of the request.
# Corresponds to the JSON property `latency`
# @return [String]
attr_accessor :latency
# Origin IP address.
# Corresponds to the JSON property `ip`
# @return [String]
attr_accessor :ip
# Application that handled this request.
# Corresponds to the JSON property `appId`
# @return [String]
attr_accessor :app_id
# App Engine release version.
# Corresponds to the JSON property `appEngineRelease`
# @return [String]
attr_accessor :app_engine_release
# Request method. Example: "GET", "HEAD", "PUT", "POST", "DELETE".
# Corresponds to the JSON property `method`
# @return [String]
attr_accessor :method_prop
# An indication of the relative cost of serving this request.
# Corresponds to the JSON property `cost`
# @return [Float]
attr_accessor :cost
# An identifier for the instance that handled the request.
# Corresponds to the JSON property `instanceId`
# @return [String]
attr_accessor :instance_id
# Number of CPU megacycles used to process request.
# Corresponds to the JSON property `megaCycles`
# @return [String]
attr_accessor :mega_cycles
# Whether this is the first RequestLog entry for this request. If an active
# request has several RequestLog entries written to Stackdriver Logging, then
# this field will be set for one of them.
# Corresponds to the JSON property `first`
# @return [Boolean]
attr_accessor :first
alias_method :first?, :first
# Version of the application that handled this request.
# Corresponds to the JSON property `versionId`
# @return [String]
attr_accessor :version_id
# Module of the application that handled this request.
# Corresponds to the JSON property `moduleId`
# @return [String]
attr_accessor :module_id
# Time when the request finished.
# Corresponds to the JSON property `endTime`
# @return [String]
attr_accessor :end_time
# User agent that made the request.
# Corresponds to the JSON property `userAgent`
# @return [String]
attr_accessor :user_agent
# Whether this was a loading request for the instance.
# Corresponds to the JSON property `wasLoadingRequest`
# @return [Boolean]
attr_accessor :was_loading_request
alias_method :was_loading_request?, :was_loading_request
# Source code for the application that handled this request. There can be more
# than one source reference per deployed application if source code is
# distributed among multiple repositories.
# Corresponds to the JSON property `sourceReference`
# @return [Array<Google::Apis::LoggingV2beta1::SourceReference>]
attr_accessor :source_reference
# Size in bytes sent back to client by request.
# Corresponds to the JSON property `responseSize`
# @return [String]
attr_accessor :response_size
# Stackdriver Trace identifier for this request.
# Corresponds to the JSON property `traceId`
# @return [String]
attr_accessor :trace_id
# A list of log lines emitted by the application while serving this request.
# Corresponds to the JSON property `line`
# @return [Array<Google::Apis::LoggingV2beta1::LogLine>]
attr_accessor :line
# Queue name of the request, in the case of an offline request.
# Corresponds to the JSON property `taskQueueName`
# @return [String]
attr_accessor :task_queue_name
# Referrer URL of request.
# Corresponds to the JSON property `referrer`
# @return [String]
attr_accessor :referrer
# Globally unique identifier for a request, which is based on the request start
# time. Request IDs for requests which started later will compare greater as
# strings than those for requests which started earlier.
# Corresponds to the JSON property `requestId`
# @return [String]
attr_accessor :request_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@nickname = args[:nickname] if args.key?(:nickname)
@status = args[:status] if args.key?(:status)
@resource = args[:resource] if args.key?(:resource)
@pending_time = args[:pending_time] if args.key?(:pending_time)
@task_name = args[:task_name] if args.key?(:task_name)
@url_map_entry = args[:url_map_entry] if args.key?(:url_map_entry)
@instance_index = args[:instance_index] if args.key?(:instance_index)
@host = args[:host] if args.key?(:host)
@finished = args[:finished] if args.key?(:finished)
@http_version = args[:http_version] if args.key?(:http_version)
@start_time = args[:start_time] if args.key?(:start_time)
@latency = args[:latency] if args.key?(:latency)
@ip = args[:ip] if args.key?(:ip)
@app_id = args[:app_id] if args.key?(:app_id)
@app_engine_release = args[:app_engine_release] if args.key?(:app_engine_release)
@method_prop = args[:method_prop] if args.key?(:method_prop)
@cost = args[:cost] if args.key?(:cost)
@instance_id = args[:instance_id] if args.key?(:instance_id)
@mega_cycles = args[:mega_cycles] if args.key?(:mega_cycles)
@first = args[:first] if args.key?(:first)
@version_id = args[:version_id] if args.key?(:version_id)
@module_id = args[:module_id] if args.key?(:module_id)
@end_time = args[:end_time] if args.key?(:end_time)
@user_agent = args[:user_agent] if args.key?(:user_agent)
@was_loading_request = args[:was_loading_request] if args.key?(:was_loading_request)
@source_reference = args[:source_reference] if args.key?(:source_reference)
@response_size = args[:response_size] if args.key?(:response_size)
@trace_id = args[:trace_id] if args.key?(:trace_id)
@line = args[:line] if args.key?(:line)
@task_queue_name = args[:task_queue_name] if args.key?(:task_queue_name)
@referrer = args[:referrer] if args.key?(:referrer)
@request_id = args[:request_id] if args.key?(:request_id)
end
end
# Result returned from ListMonitoredResourceDescriptors.
class ListMonitoredResourceDescriptorsResponse
include Google::Apis::Core::Hashable
# If there might be more results than those appearing in this response, then
# nextPageToken is included. To get the next set of results, call this method
# again using the value of nextPageToken as pageToken.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
# A list of resource descriptors.
# Corresponds to the JSON property `resourceDescriptors`
# @return [Array<Google::Apis::LoggingV2beta1::MonitoredResourceDescriptor>]
attr_accessor :resource_descriptors
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
@resource_descriptors = args[:resource_descriptors] if args.key?(:resource_descriptors)
end
end
# A reference to a particular snapshot of the source tree used to build and
# deploy an application.
class SourceReference
include Google::Apis::Core::Hashable
# Optional. A URI string identifying the repository. Example: "https://github.
# com/GoogleCloudPlatform/kubernetes.git"
# Corresponds to the JSON property `repository`
# @return [String]
attr_accessor :repository
# The canonical and persistent identifier of the deployed revision. Example (git)
# : "0035781c50ec7aa23385dc841529ce8a4b70db1b"
# Corresponds to the JSON property `revisionId`
# @return [String]
attr_accessor :revision_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@repository = args[:repository] if args.key?(:repository)
@revision_id = args[:revision_id] if args.key?(:revision_id)
end
end
# Describes a logs-based metric. The value of the metric is the number of log
# entries that match a logs filter in a given time interval.
class LogMetric
include Google::Apis::Core::Hashable
# Required. The client-assigned metric identifier. Examples: "error_count", "
# nginx/requests".Metric identifiers are limited to 100 characters and can
# include only the following characters: A-Z, a-z, 0-9, and the special
# characters _-.,+!*',()%/. The forward-slash character (/) denotes a hierarchy
# of name pieces, and it cannot be the first character of the name.The metric
# identifier in this field must not be URL-encoded (https://en.wikipedia.org/
# wiki/Percent-encoding). However, when the metric identifier appears as the [
# METRIC_ID] part of a metric_name API parameter, then the metric identifier
# must be URL-encoded. Example: "projects/my-project/metrics/nginx%2Frequests".
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Optional. A description of this metric, which is used in documentation.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# Output only. The API version that created or updated this metric. The version
# also dictates the syntax of the filter expression. When a value for this field
# is missing, the default value of V2 should be assumed.
# Corresponds to the JSON property `version`
# @return [String]
attr_accessor :version
# Required. An advanced logs filter which is used to match log entries. Example:
# "resource.type=gae_app AND severity>=ERROR"
# The maximum length of the filter is 20000 characters.
# Corresponds to the JSON property `filter`
# @return [String]
attr_accessor :filter
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@name = args[:name] if args.key?(:name)
@description = args[:description] if args.key?(:description)
@version = args[:version] if args.key?(:version)
@filter = args[:filter] if args.key?(:filter)
end
end
# Additional information about a potentially long-running operation with which a
# log entry is associated.
class LogEntryOperation
include Google::Apis::Core::Hashable
# Optional. An arbitrary operation identifier. Log entries with the same
# identifier are assumed to be part of the same operation.
# Corresponds to the JSON property `id`
# @return [String]
attr_accessor :id
# Optional. An arbitrary producer identifier. The combination of id and producer
# must be globally unique. Examples for producer: "MyDivision.MyBigCompany.com",
# "github.com/MyProject/MyApplication".
# Corresponds to the JSON property `producer`
# @return [String]
attr_accessor :producer
# Optional. Set this to True if this is the first log entry in the operation.
# Corresponds to the JSON property `first`
# @return [Boolean]
attr_accessor :first
alias_method :first?, :first
# Optional. Set this to True if this is the last log entry in the operation.
# Corresponds to the JSON property `last`
# @return [Boolean]
attr_accessor :last
alias_method :last?, :last
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@id = args[:id] if args.key?(:id)
@producer = args[:producer] if args.key?(:producer)
@first = args[:first] if args.key?(:first)
@last = args[:last] if args.key?(:last)
end
end
# Result returned from WriteLogEntries. empty
class WriteLogEntriesResponse
include Google::Apis::Core::Hashable
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
end
end
# An object representing a resource that can be used for monitoring, logging,
# billing, or other purposes. Examples include virtual machine instances,
# databases, and storage devices such as disks. The type field identifies a
# MonitoredResourceDescriptor object that describes the resource's schema.
# Information in the labels field identifies the actual resource and its
# attributes according to the schema. For example, a particular Compute Engine
# VM instance could be represented by the following object, because the
# MonitoredResourceDescriptor for "gce_instance" has labels "instance_id" and "
# zone":
# ` "type": "gce_instance",
# "labels": ` "instance_id": "12345678901234",
# "zone": "us-central1-a" ``
class MonitoredResource
include Google::Apis::Core::Hashable
# Required. Values for all of the labels listed in the associated monitored
# resource descriptor. For example, Cloud SQL databases use the labels "
# database_id" and "zone".
# Corresponds to the JSON property `labels`
# @return [Hash<String,String>]
attr_accessor :labels
# Required. The monitored resource type. This field must match the type field of
# a MonitoredResourceDescriptor object. For example, the type of a Cloud SQL
# database is "cloudsql_database".
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@labels = args[:labels] if args.key?(:labels)
@type = args[:type] if args.key?(:type)
end
end
# Describes a sink used to export log entries to one of the following
# destinations in any project: a Cloud Storage bucket, a BigQuery dataset, or a
# Cloud Pub/Sub topic. A logs filter controls which log entries are exported.
# The sink must be created within a project or organization.
class LogSink
include Google::Apis::Core::Hashable
# Optional. The log entry format to use for this sink's exported log entries.
# The v2 format is used by default. The v1 format is deprecated and should be
# used only as part of a migration effort to v2. See Migration to the v2 API.
# Corresponds to the JSON property `outputVersionFormat`
# @return [String]
attr_accessor :output_version_format
# Required. The client-assigned sink identifier, unique within the project.
# Example: "my-syslog-errors-to-pubsub". Sink identifiers are limited to 100
# characters and can include only the following characters: upper and lower-case
# alphanumeric characters, underscores, hyphens, and periods.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Required. The export destination:
# "storage.googleapis.com/[GCS_BUCKET]"
# "bigquery.googleapis.com/projects/[PROJECT_ID]/datasets/[DATASET]"
# "pubsub.googleapis.com/projects/[PROJECT_ID]/topics/[TOPIC_ID]"
# The sink's writer_identity, set when the sink is created, must have permission
# to write to the destination or else the log entries are not exported. For more
# information, see Exporting Logs With Sinks.
# Corresponds to the JSON property `destination`
# @return [String]
attr_accessor :destination
# Optional. An advanced logs filter. The only exported log entries are those
# that are in the resource owning the sink and that match the filter. The filter
# must use the log entry format specified by the output_version_format parameter.
# For example, in the v2 format:
# logName="projects/[PROJECT_ID]/logs/[LOG_ID]" AND severity>=ERROR
# Corresponds to the JSON property `filter`
# @return [String]
attr_accessor :filter
# Optional. The time at which this sink will stop exporting log entries. Log
# entries are exported only if their timestamp is earlier than the end time. If
# this field is not supplied, there is no end time. If both a start time and an
# end time are provided, then the end time must be later than the start time.
# Corresponds to the JSON property `endTime`
# @return [String]
attr_accessor :end_time
# Optional. The time at which this sink will begin exporting log entries. Log
# entries are exported only if their timestamp is not earlier than the start
# time. The default value of this field is the time the sink is created or
# updated.
# Corresponds to the JSON property `startTime`
# @return [String]
attr_accessor :start_time
# Output only. An IAM identity—a service account or group—under
# which Stackdriver Logging writes the exported log entries to the sink's
# destination. This field is set by sinks.create and sinks.update, based on the
# setting of unique_writer_identity in those methods.Until you grant this
# identity write-access to the destination, log entry exports from this sink
# will fail. For more information, see Granting access for a resource. Consult
# the destination service's documentation to determine the appropriate IAM roles
# to assign to the identity.
# Corresponds to the JSON property `writerIdentity`
# @return [String]
attr_accessor :writer_identity
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@output_version_format = args[:output_version_format] if args.key?(:output_version_format)
@name = args[:name] if args.key?(:name)
@destination = args[:destination] if args.key?(:destination)
@filter = args[:filter] if args.key?(:filter)
@end_time = args[:end_time] if args.key?(:end_time)
@start_time = args[:start_time] if args.key?(:start_time)
@writer_identity = args[:writer_identity] if args.key?(:writer_identity)
end
end
# The parameters to WriteLogEntries.
class WriteLogEntriesRequest
include Google::Apis::Core::Hashable
# Optional. A default log resource name that is assigned to all log entries in
# entries that do not specify a value for log_name:
# "projects/[PROJECT_ID]/logs/[LOG_ID]"
# "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]"
# [LOG_ID] must be URL-encoded. For example, "projects/my-project-id/logs/syslog"
# or "organizations/1234567890/logs/cloudresourcemanager.googleapis.com%
# 2Factivity". For more information about log names, see LogEntry.
# Corresponds to the JSON property `logName`
# @return [String]
attr_accessor :log_name
# Required. The log entries to write. Values supplied for the fields log_name,
# resource, and labels in this entries.write request are added to those log
# entries that do not provide their own values for the fields.To improve
# throughput and to avoid exceeding the quota limit for calls to entries.write,
# you should write multiple log entries at once rather than calling this method
# for each individual log entry.
# Corresponds to the JSON property `entries`
# @return [Array<Google::Apis::LoggingV2beta1::LogEntry>]
attr_accessor :entries
# Optional. Whether valid entries should be written even if some other entries
# fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any entry is not
# written, the response status will be the error associated with one of the
# failed entries and include error details in the form of
# WriteLogEntriesPartialErrors.
# Corresponds to the JSON property `partialSuccess`
# @return [Boolean]
attr_accessor :partial_success
alias_method :partial_success?, :partial_success
# Optional. Default labels that are added to the labels field of all log entries
# in entries. If a log entry already has a label with the same key as a label in
# this parameter, then the log entry's label is not changed. See LogEntry.
# Corresponds to the JSON property `labels`
# @return [Hash<String,String>]
attr_accessor :labels
# An object representing a resource that can be used for monitoring, logging,
# billing, or other purposes. Examples include virtual machine instances,
# databases, and storage devices such as disks. The type field identifies a
# MonitoredResourceDescriptor object that describes the resource's schema.
# Information in the labels field identifies the actual resource and its
# attributes according to the schema. For example, a particular Compute Engine
# VM instance could be represented by the following object, because the
# MonitoredResourceDescriptor for "gce_instance" has labels "instance_id" and "
# zone":
# ` "type": "gce_instance",
# "labels": ` "instance_id": "12345678901234",
# "zone": "us-central1-a" ``
# Corresponds to the JSON property `resource`
# @return [Google::Apis::LoggingV2beta1::MonitoredResource]
attr_accessor :resource
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@log_name = args[:log_name] if args.key?(:log_name)
@entries = args[:entries] if args.key?(:entries)
@partial_success = args[:partial_success] if args.key?(:partial_success)
@labels = args[:labels] if args.key?(:labels)
@resource = args[:resource] if args.key?(:resource)
end
end
# Result returned from ListLogs.
class ListLogsResponse
include Google::Apis::Core::Hashable
# A list of log names. For example, "projects/my-project/syslog" or "
# organizations/123/cloudresourcemanager.googleapis.com%2Factivity".
# Corresponds to the JSON property `logNames`
# @return [Array<String>]
attr_accessor :log_names
# If there might be more results than those appearing in this response, then
# nextPageToken is included. To get the next set of results, call this method
# again using the value of nextPageToken as pageToken.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@log_names = args[:log_names] if args.key?(:log_names)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
end
end
# Result returned from ListSinks.
class ListSinksResponse
include Google::Apis::Core::Hashable
# A list of sinks.
# Corresponds to the JSON property `sinks`
# @return [Array<Google::Apis::LoggingV2beta1::LogSink>]
attr_accessor :sinks
# If there might be more results than appear in this response, then
# nextPageToken is included. To get the next set of results, call the same
# method again using the value of nextPageToken as pageToken.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@sinks = args[:sinks] if args.key?(:sinks)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
end
end
# A common proto for logging HTTP requests. Only contains semantics defined by
# the HTTP specification. Product-specific logging information MUST be defined
# in a separate message.
class HttpRequest
include Google::Apis::Core::Hashable
# The size of the HTTP request message in bytes, including the request headers
# and the request body.
# Corresponds to the JSON property `requestSize`
# @return [String]
attr_accessor :request_size
# The size of the HTTP response message sent back to the client, in bytes,
# including the response headers and the response body.
# Corresponds to the JSON property `responseSize`
# @return [String]
attr_accessor :response_size
# The scheme (http, https), the host name, the path and the query portion of the
# URL that was requested. Example: "http://example.com/some/info?color=red".
# Corresponds to the JSON property `requestUrl`
# @return [String]
attr_accessor :request_url
# The IP address (IPv4 or IPv6) of the client that issued the HTTP request.
# Examples: "192.168.1.1", "FE80::0202:B3FF:FE1E:8329".
# Corresponds to the JSON property `remoteIp`
# @return [String]
attr_accessor :remote_ip
# The IP address (IPv4 or IPv6) of the origin server that the request was sent
# to.
# Corresponds to the JSON property `serverIp`
# @return [String]
attr_accessor :server_ip
# Whether or not a cache lookup was attempted.
# Corresponds to the JSON property `cacheLookup`
# @return [Boolean]
attr_accessor :cache_lookup
alias_method :cache_lookup?, :cache_lookup
# Whether or not an entity was served from cache (with or without validation).
# Corresponds to the JSON property `cacheHit`
# @return [Boolean]
attr_accessor :cache_hit
alias_method :cache_hit?, :cache_hit
# Whether or not the response was validated with the origin server before being
# served from cache. This field is only meaningful if cache_hit is True.
# Corresponds to the JSON property `cacheValidatedWithOriginServer`
# @return [Boolean]
attr_accessor :cache_validated_with_origin_server
alias_method :cache_validated_with_origin_server?, :cache_validated_with_origin_server
# The response code indicating the status of response. Examples: 200, 404.
# Corresponds to the JSON property `status`
# @return [Fixnum]
attr_accessor :status
# The referer URL of the request, as defined in HTTP/1.1 Header Field
# Definitions (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
# Corresponds to the JSON property `referer`
# @return [String]
attr_accessor :referer
# The request processing latency on the server, from the time the request was
# received until the response was sent.
# Corresponds to the JSON property `latency`
# @return [String]
attr_accessor :latency
# The user agent sent by the client. Example: "Mozilla/4.0 (compatible; MSIE 6.0;
# Windows 98; Q312461; .NET CLR 1.0.3705)".
# Corresponds to the JSON property `userAgent`
# @return [String]
attr_accessor :user_agent
# The number of HTTP response bytes inserted into cache. Set only when a cache
# fill was attempted.
# Corresponds to the JSON property `cacheFillBytes`
# @return [String]
attr_accessor :cache_fill_bytes
# The request method. Examples: "GET", "HEAD", "PUT", "POST".
# Corresponds to the JSON property `requestMethod`
# @return [String]
attr_accessor :request_method
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@request_size = args[:request_size] if args.key?(:request_size)
@response_size = args[:response_size] if args.key?(:response_size)
@request_url = args[:request_url] if args.key?(:request_url)
@remote_ip = args[:remote_ip] if args.key?(:remote_ip)
@server_ip = args[:server_ip] if args.key?(:server_ip)
@cache_lookup = args[:cache_lookup] if args.key?(:cache_lookup)
@cache_hit = args[:cache_hit] if args.key?(:cache_hit)
@cache_validated_with_origin_server = args[:cache_validated_with_origin_server] if args.key?(:cache_validated_with_origin_server)
@status = args[:status] if args.key?(:status)
@referer = args[:referer] if args.key?(:referer)
@latency = args[:latency] if args.key?(:latency)
@user_agent = args[:user_agent] if args.key?(:user_agent)
@cache_fill_bytes = args[:cache_fill_bytes] if args.key?(:cache_fill_bytes)
@request_method = args[:request_method] if args.key?(:request_method)
end
end
# A description of a label.
class LabelDescriptor
include Google::Apis::Core::Hashable
# A human-readable description for the label.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The type of data that can be assigned to the label.
# Corresponds to the JSON property `valueType`
# @return [String]
attr_accessor :value_type
# The label key.
# Corresponds to the JSON property `key`
# @return [String]
attr_accessor :key
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@value_type = args[:value_type] if args.key?(:value_type)
@key = args[:key] if args.key?(:key)
end
end
# An object that describes the schema of a MonitoredResource object using a type
# name and a set of labels. For example, the monitored resource descriptor for
# Google Compute Engine VM instances has a type of "gce_instance" and specifies
# the use of the labels "instance_id" and "zone" to identify particular VM
# instances.Different APIs can support different monitored resource types. APIs
# generally provide a list method that returns the monitored resource
# descriptors used by the API.
class MonitoredResourceDescriptor
include Google::Apis::Core::Hashable
# Required. The monitored resource type. For example, the type "
# cloudsql_database" represents databases in Google Cloud SQL. The maximum
# length of this value is 256 characters.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
# Required. A set of labels used to describe instances of this monitored
# resource type. For example, an individual Google Cloud SQL database is
# identified by values for the labels "database_id" and "zone".
# Corresponds to the JSON property `labels`
# @return [Array<Google::Apis::LoggingV2beta1::LabelDescriptor>]
attr_accessor :labels
# Optional. The resource name of the monitored resource descriptor: "projects/`
# project_id`/monitoredResourceDescriptors/`type`" where `type` is the value of
# the type field in this object and `project_id` is a project ID that provides
# API-specific context for accessing the type. APIs that do not use project
# information can use the resource name format "monitoredResourceDescriptors/`
# type`".
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Optional. A concise name for the monitored resource type that might be
# displayed in user interfaces. It should be a Title Cased Noun Phrase, without
# any article or other determiners. For example, "Google Cloud SQL Database".
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# Optional. A detailed description of the monitored resource type that might be
# used in documentation.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@type = args[:type] if args.key?(:type)
@labels = args[:labels] if args.key?(:labels)
@name = args[:name] if args.key?(:name)
@display_name = args[:display_name] if args.key?(:display_name)
@description = args[:description] if args.key?(:description)
end
end
# Additional information about the source code location that produced the log
# entry.
class LogEntrySourceLocation
include Google::Apis::Core::Hashable
# Optional. Source file name. Depending on the runtime environment, this might
# be a simple name or a fully-qualified name.
# Corresponds to the JSON property `file`
# @return [String]
attr_accessor :file
# Optional. Human-readable name of the function or method being invoked, with
# optional context such as the class or package name. This information may be
# used in contexts such as the logs viewer, where a file and line number are
# less meaningful. The format can vary by language. For example: qual.if.ied.
# Class.method (Java), dir/package.func (Go), function (Python).
# Corresponds to the JSON property `function`
# @return [String]
attr_accessor :function
# Optional. Line within the source file. 1-based; 0 indicates no line number
# available.
# Corresponds to the JSON property `line`
# @return [String]
attr_accessor :line
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@file = args[:file] if args.key?(:file)
@function = args[:function] if args.key?(:function)
@line = args[:line] if args.key?(:line)
end
end
# Result returned from ListLogEntries.
class ListLogEntriesResponse
include Google::Apis::Core::Hashable
# A list of log entries.
# Corresponds to the JSON property `entries`
# @return [Array<Google::Apis::LoggingV2beta1::LogEntry>]
attr_accessor :entries
# If there might be more results than those appearing in this response, then
# nextPageToken is included. To get the next set of results, call this method
# again using the value of nextPageToken as pageToken.If a value for
# next_page_token appears and the entries field is empty, it means that the
# search found no log entries so far but it did not have time to search all the
# possible log entries. Retry the method with this value for page_token to
# continue the search. Alternatively, consider speeding up the search by
# changing your filter to specify a single log name or resource type, or to
# narrow the time range of the search.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@entries = args[:entries] if args.key?(:entries)
@next_page_token = args[:next_page_token] if args.key?(:next_page_token)
end
end
# Application log line emitted while processing a request.
class LogLine
include Google::Apis::Core::Hashable
# Severity of this log entry.
# Corresponds to the JSON property `severity`
# @return [String]
attr_accessor :severity
# App-provided log message.
# Corresponds to the JSON property `logMessage`
# @return [String]
attr_accessor :log_message
# Specifies a location in a source code file.
# Corresponds to the JSON property `sourceLocation`
# @return [Google::Apis::LoggingV2beta1::SourceLocation]
attr_accessor :source_location
# Approximate time when this log entry was made.
# Corresponds to the JSON property `time`
# @return [String]
attr_accessor :time
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@severity = args[:severity] if args.key?(:severity)
@log_message = args[:log_message] if args.key?(:log_message)
@source_location = args[:source_location] if args.key?(:source_location)
@time = args[:time] if args.key?(:time)
end
end
end
end
end
| 44.443028 | 139 | 0.637945 |
39ebd49dc52db28ccf9922abba79cc16976e1d76 | 1,379 | require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Budgie
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| 39.4 | 99 | 0.751269 |
1178615f3f54c574d39682db9aab6bd4bbe5800d | 119 | class AddAvatarColumnsToUsers < ActiveRecord::Migration[5.2]
def change
add_attachment :users, :avatar
end
end
| 19.833333 | 60 | 0.764706 |
b922b66e95008ab354c06a596b03a204d3c11218 | 411 | cask 'vuescan' do
version '9.5.64'
sha256 :no_check # required as upstream package is updated in-place
url "https://www.hamrick.com/files/vuex64#{version.major_minor.no_dots}.dmg"
appcast 'https://www.hamrick.com/old-versions.html',
checkpoint: 'd6e88549f481993c8bfe21a551c5a19e7d6fe83a7a0b5010ee5b3ff99ef49ca4'
name 'VueScan'
homepage 'https://www.hamrick.com/'
app 'VueScan.app'
end
| 31.615385 | 88 | 0.744526 |
91f5c68304d6c23a92e6544bf9a1ccb295aad932 | 167 | class NewsItem < ApplicationRecord
validates :body, presence: true, allow_blank: false
validates :title, presence: true, allow_blank: false
belongs_to :user
end
| 27.833333 | 54 | 0.778443 |
f879406ad2e646b730abcbaf2361cb07f06e044b | 26,677 | # encoding: utf-8
require 'base64'
# The module name doesn't matter, just make sure at the end to 'extend' it
# because it will be 'eval'ed by the initialize method of the XhtmlReportGenerator::Generator class.
module Custom
# creates the basic page layout and sets the current Element to the main content area (middle div)
# @example The middle div is matched by the following xPath
# //body/div[@id='middle']
# @param title [String] the title of the document
# @param layout [Fixnum] one of 0,1,2,3 where 0 means minimal layout without left and right table of contents,
# 1 means only left toc, 2 means only right toc, and 3 means full layout with left and right toc.
def create_layout(title, layout=3)
raise "invalid layout selector, choose from 0..3" if (layout < 0) || (layout > 3)
@body = @document.elements["//body"]
# only add the layout if it is not already there
if !@layout
head = @body.add_element("div", {"class" => "head", "id" => "head"})
head.add_element("button", {"id" => "pre_toggle_linewrap"}).add_text("Toggle Linewrap")
if (layout & 0x1) != 0
div = @body.add_element("div", {"class" => "lefttoc split split-horizontal", "id" => "ltoc"})
div.add_text("Table of Contents")
div.add_element("br")
end
@div_middle = @body.add_element("div", {"class" => "middle split split-horizontal", "id" => "middle"})
if (layout & 0x2) != 0
div = @body.add_element("div", {"class" => "righttoc split split-horizontal", "id" => "rtoc"})
div.add_text("Quick Links")
div.add_element("br");div.add_element("br")
end
@body.add_element("p", {"class" => "#{layout}", "id" => "layout"}).add_text("this text should be hidden")
@layout = true
end
@current = @document.elements["//body/div[@id='middle']"]
set_title(title)
end
# sets the title of the document in the <head> section as well as in the layout header div
# create_layout must be called before!
# @param title [String] the text which will be insertead
def set_title(title)
if !@layout
raise "call create_layout first"
end
pagetitle = @document.elements["//head/title"]
pagetitle.text = title
div = @document.elements["//body/div[@id='head']"]
div.text = title
end
# returns the title text of the report
# @return [String] The title of the report
def get_title()
pagetitle = @document.elements["//head/title"]
return pagetitle.text
end
# set the current element to the element or first element matched by the xpath expression.
# The current element is the one which can be modified through highlighting.
# @param xpath [REXML::Element|String] the element or an xpath string
def set_current!(xpath)
if xpath.is_a?(REXML::Element)
@current = xpath
elsif xpath.is_a?(String)
@current = @document.elements[xpath]
else
raise "xpath is neither a String nor a REXML::Element"
end
end
# returns the current xml element
# @return [REXML::Element] the xml element after which the following elements will be added
def get_current()
return @current
end
# returns the plain text without any xml tags of the specified element and all its children
# @param el [REXML::Element] The element from which to fetch the text children. Defaults to @current
# @param recursive [Boolean] whether or not to recurse into the children of the given "el"
# @return [String] text contents of xml node
def get_element_text(el = @current, recursive = true)
out = ""
el.to_a.each { |child|
if child.is_a?(REXML::Text)
out << child.value()
else
if recursive
out << get_element_text(child, true)
end
end
}
return out
end
# @param elem [REXML::Element]
# @return [String]
def element_to_string(elem)
f = REXML::Formatters::Transitive.new(0) # use Transitive to preserve source formatting (e.g. <pre> tags)
out = ""
f.write(elem, out)
return out
end
# @see #code
# Instead of adding content to the report, this method returns the produced html code as a string.
# This can be used to insert code into #custom_table (with the option data_is_xhtml: true)
# @return [String] the code including <pre> tags as a string
def get_code_html(attrs={}, &block)
temp = REXML::Element.new("pre")
temp.add_attributes(attrs)
raise "Block argument is mandatory" unless block_given?
text = encoding_fixer(block.call())
temp.add_text(text)
element_to_string(temp)
end
# Appends a <pre> node after the @current node
# @param attrs [Hash] attributes for the <pre> element. The following classes can be passed as attributes and are predefined with a different
# background for your convenience !{"class" => "code0"} (light-blue), !{"class" => "code1"} (red-brown),
# !{"class" => "code2"} (light-green), !{"class" => "code3"} (light-yellow). You may also specify your own background
# as follows: !{"style" => "background: #FF00FF;"}.
# @yieldreturn [String] the text to be added to the <pre> element
# @return [REXML::Element] the Element which was just added
def code(attrs={}, &block)
temp = REXML::Element.new("pre")
temp.add_attributes(attrs)
@div_middle.insert_after(@current, temp)
@current = temp
raise "Block argument is mandatory" unless block_given?
text = encoding_fixer(block.call())
@current.add_text(text)
return @current
end
# @see #content
# Instead of adding content to the report, this method returns the produced html code as a string.
# This can be used to insert code into #custom_table (with the option data_is_xhtml: true)
# @return [String] the code including <pre> tags as a string
def get_content_html(attrs={}, &block)
temp = REXML::Element.new("p")
temp.add_attributes(attrs)
raise "Block argument is mandatory" unless block_given?
text = encoding_fixer(block.call())
temp.add_text(text)
element_to_string(temp)
end
# Appends a <p> node after the @current node
# @param attrs [Hash] attributes for the <p> element
# @yieldreturn [String] the text to be added to the <p> element
# @return [REXML::Element] the Element which was just added
def content(attrs={}, &block)
temp = REXML::Element.new("p")
temp.add_attributes(attrs)
@div_middle.insert_after(@current, temp)
@current = temp
raise "Block argument is mandatory" unless block_given?
text = encoding_fixer(block.call())
@current.add_text(text)
return @current
end
# insert arbitrary xml code after the @current element in the content pane (div middle)
# @param text [String] valid xhtml code which is included into the document
# @return [REXML::Element] the Element which was just added
def html(text)
# we need to create a new document with a pseudo root becaus having multiple nodes at top
# level is not valid xml
doc = REXML::Document.new("<root>"+text+"</root>")
# then we move all children of root to the actual div middle element and insert after current
for i in doc.root.to_a do
@div_middle.insert_after(@current, i)
@current = i
end
return @current
end
# @see #link
# Instead of adding content to the report, this method returns the produced html code as a string.
# This can be used to insert code into #custom_table (with the option data_is_xhtml: true)
# @return [String] the code including <pre> tags as a string
def get_link_html(href, attrs={}, &block)
temp = REXML::Element.new("a")
attrs.merge!({"href" => href})
temp.add_attributes(attrs)
raise "Block argument is mandatory" unless block_given?
text = encoding_fixer(block.call())
temp.add_text(text)
element_to_string(temp)
end
# Appends a <a href = > node after the @current nodes
# @param href [String] this is the
# @param attrs [Hash] attributes for the <a> element
# @yieldreturn [String] the text to be added to the <a> element
# @return [REXML::Element] the Element which was just added
def link(href, attrs={}, &block)
temp = REXML::Element.new("a")
attrs.merge!({"href" => href})
temp.add_attributes(attrs)
@div_middle.insert_after(@current, temp)
@current = temp
raise "Block argument is mandatory" unless block_given?
text = encoding_fixer(block.call())
@current.add_text(text)
return @current
end
# @see #image
# Instead of adding content to the report, this method returns the produced html code as a string.
# This can be used to insert code into #custom_table (with the option data_is_xhtml: true)
# @return [String] the code including <pre> tags as a string
def get_image_html(path, attributes = {})
# read image as binary and do a base64 encoding
binary_data = Base64.strict_encode64(IO.binread(path))
type = File.extname(path).gsub('.', '')
# create the element
temp = REXML::Element.new("img")
# add the picture
temp.add_attribute("src","data:image/#{type};base64,#{binary_data}")
temp.add_attributes(attributes)
element_to_string(temp)
end
# @param path [String] absolute or relative path to the image that should be inserted into the report
# @param attributes [Hash] attributes for the <img> element, any valid html attributes can be specified
# you may specify attributes such "alt", "height", "width"
# @option attrs [String] "class" by default every heading is added to the left table of contents (toc)
def image(path, attributes = {})
# read image as binary and do a base64 encoding
binary_data = Base64.strict_encode64(IO.binread(path))
type = File.extname(path).gsub('.', '')
# create the element
temp = REXML::Element.new("img")
# add the picture
temp.add_attribute("src","data:image/#{type};base64,#{binary_data}")
temp.add_attributes(attributes)
@div_middle.insert_after(@current, temp)
@current = temp
return @current
end
# Scans all REXML::Text children of an REXML::Element for any occurrences of regex.
# The text will be matched as one, not line by line as you might think.
# If you want to write a regexp matching multiple lines keep in mind that the dot "." by default doesn't
# match newline characters. Consider using the "m" option (e.g. /regex/m ) which makes dot match newlines
# or match newlines explicitly.
# highlight_captures then puts a <span> </span> tag around all captures of the regex
# NOTE: nested captures are not supported and don't make sense in this context!!
# @param regex [Regexp] a regular expression that will be matched
# @param color [String] either one of "y", "r", "g", "b" (yellow, red, green, blue) or a valid html color code (e.g. "#80BFFF")
# @param el [REXML::Element] the Element (scope) which will be searched for pattern matches, by default the last inserted element will be scanned
# @return [Fixnum] the number of highlighted captures
def highlight_captures(regex, color="y", el = @current)
# get all children of the current node
arr = el.to_a()
num_matches = 0
# first we have to detach all children from parent, otherwise we can cause ordering issues
arr.each {|i| i.remove() }
# depth first recursion into grand-children
for i in arr do
if i.is_a?(REXML::Text)
# in general a text looks as follows:
# .*(matchstring|.*)*
# We get an array of [[start,length], [start,length], ...] for all our regex SUB-matches
positions = i.value().enum_for(:scan, regex).flat_map {
# Regexp.last_match is a MatchData object, the index 0 is the entire match, 1 to n are captures
array = Array.new
for k in 1..Regexp.last_match.length - 1 do
array.push([Regexp.last_match.begin(k),
Regexp.last_match.end(k)-Regexp.last_match.begin(k)])
end
# return the array for the flat_map
array
}
num_matches += positions.length
if ["y","r","g","b"].include?(color)
attr = {"class" => color}
elsif color.match(/^#[A-Fa-f0-9]{6}$/)
attr = {"style" => "background: #{color};"}
else
raise "invalid color: #{color}"
end
replace_text_with_elements(el, i, "span", attr, positions)
else
# for non-text nodes we recurse into it and finally reattach to our parent to preserve ordering
num_matches += highlight_captures(regex, color, i)
el.add(i)
end # if i.is_a?(REXML::Text)
end # for i in arr do
return num_matches
end
# Scans all REXML::Text children of an REXML::Element for any occurrences of regex.
# The text will be matched as one, not line by line as you might think.
# If you want to write a regexp matching multiple lines keep in mind that the dot "." by default doesn't
# match newline characters. Consider using the "m" option (e.g. /regex/m ) which makes dot match newlines
# or match newlines explicitly.
# highlight then puts a <span> </span> tag around all matches of regex
# @param regex [Regexp] a regular expression that will be matched
# @param color [String] either one of "y", "r", "g", "b" (yellow, red, green, blue) or a valid html color code (e.g. "#80BFFF")
# @param el [REXML::Element] the Element (scope) which will be searched for pattern matches
# @return [Fixnum] the number of highlighted captures
def highlight(regex, color="y", el = @current)
# get all children of the current node
arr = el.to_a()
num_matches = 0
#puts arr.inspect
# first we have to detach all children from parent, otherwise we can cause ordering issues
arr.each {|i| i.remove() }
# depth first recursion into grand-children
for i in arr do
#puts i.class.to_s()
if i.is_a?(REXML::Text)
# in general a text looks as follows:
# .*(matchstring|.*)*
# We get an array of [[start,length], [start,length], ...] for all our regex matches
positions = i.value().enum_for(:scan, regex).map {
[Regexp.last_match.begin(0),
Regexp.last_match.end(0)-Regexp.last_match.begin(0)]
}
num_matches += positions.length
if ["y","r","g","b"].include?(color)
attr = {"class" => color}
elsif color.match(/^#[A-Fa-f0-9]{6}$/)
attr = {"style" => "background: #{color};"}
else
raise "invalid color: #{color}"
end
replace_text_with_elements(el, i, "span", attr, positions)
else
# for non-text nodes we recurse into it and finally reattach to our parent to preserve ordering
# puts "recurse"
num_matches += highlight(regex, color, i)
el.add(i)
end # if i.is_a?(REXML::Text)
end # for i in arr do
return num_matches
end
# creates a html table from two dimensional array of the form Array [row] [col]
# @param table_data [Array<Array>] of the form Array [row] [col] containing all data, the '.to_s' method will be called on each element,
# @param headers [Number] either of 0, 1, 2, 3. Where 0 is no headers (<th>) at all, 1 is only the first row,
# 2 is only the first column and 3 is both, first row and first column as <th> elements. Every other number
# is equivalent to the bitwise AND of the two least significant bits with 1, 2 or 3
# @return [REXML::Element] the Element which was just added
def table(table_data, headers=0, table_attrs={}, tr_attrs={}, th_attrs={}, td_attrs={})
opts = {
headers: headers,
data_is_xhtml: false,
table_attrs: table_attrs,
th_attrs: th_attrs,
tr_attrs: tr_attrs,
td_attrs: td_attrs,
}
custom_table(table_data, opts)
end
# creates a html table from two dimensional array of the form Array [row] [col]
# @param table_data [Array<Array>] of the form Array [row] [col] containing all data, the '.to_s' method will be called on each element,
# @option opts [Number] :headers either of 0, 1, 2, 3. Where 0 is no headers (<th>) at all, 1 is only the first row,
# 2 is only the first column and 3 is both, first row and first column as <th> elements. Every other number
# is equivalent to the bitwise AND of the two least significant bits with 1, 2 or 3
# @option opts [Boolean] :data_is_xhtml defaults to false, if true table_data is inserted as xhtml without any sanitation or escaping.
# This way a table can be used for custom layouts.
# @option opts [Hash] :table_attrs html attributes for the <table> tag
# @option opts [Hash] :th_attrs html attributes for the <th> tag
# @option opts [Hash] :tr_attrs html attributes for the <tr> tag
# @option opts [Hash] :td_attrs html attributes for the <td> tag
# @option opts [Array<Hash>] :special Array of hashes for custom attributes on specific cells (<td> only) of the table
# @example Example of the :special attributes
# opts[:special] = [
# {
# col_title: 'rx_DroppedFrameCount', # string or regexp or nil # if neither title nor index are present, the condition is evaluated for all <td> cells
# col_index: 5..7, # Fixnum, Range or nil # index has precedence over title
# row_title: 'D_0_BE_iMix', # string or regexp or nil
# row_index: 6, # Fixnum, Range or nil
# condition: Proc.new { |e| Integer(e) != 0 }, # a proc
# attributes: {"style" => "background-color: #DB7093;"},
# },
# ]
# @return [REXML::Element] the Element which was just added
def custom_table(table_data, opts = {})
defaults = {
headers: 0,
data_is_xhtml: false,
table_attrs: {},
th_attrs: {},
tr_attrs: {},
td_attrs: {},
special: [],
}
o = defaults.merge(opts)
temp = REXML::Element.new("table")
temp.add_attributes(o[:table_attrs])
row_titles = table_data.collect{|row| row[0].to_s}
col_titles = table_data[0].collect{|title| title.to_s}
for i in 0..table_data.length-1 do # row
row = temp.add_element("tr", o[:tr_attrs])
for j in 0..table_data[i].length-1 do # column
if (i == 0 && (0x1 & o[:headers])==0x1)
col = row.add_element("th", o[:th_attrs])
elsif (j == 0 && (0x2 & o[:headers])==0x2)
col = row.add_element("th", o[:th_attrs])
elsif ((i == 0 || j ==0) && (0x3 & o[:headers])==0x3)
col = row.add_element("th", o[:th_attrs])
else
# we need to deepcopy the attributes
_td_attrs = Marshal.load(Marshal.dump(o[:td_attrs]))
# check all special criteria
o[:special].each do |h|
# check if the current cell is a candidate for special
if !h[:col_index].nil?
if h[:col_index].is_a?(Range)
next if (!h[:col_index].include?(j)) # skip if not in range
elsif h[:col_index].is_a?(Integer)
next if (h[:col_index] != j) # skip if not at index
end
elsif !h[:col_title].nil?
next if !col_titles[j].match(h[:col_title])
end
# check if the current cell is a candidate for special
if !h[:row_index].nil?
if h[:row_index].is_a?(Range)
next if (!h[:row_index].include?(i)) # skip if not in range
elsif h[:row_index].is_a?(Integer)
next if (h[:row_index] != i) # skip if not at index
end
elsif !h[:row_title].nil?
next if !row_titles[i].match(h[:row_title])
end
# here we are a candidate for special, so we check if we meet the condition
# puts h[:attributes].inspect
# puts "cell value row #{i} col #{j}: #{table_data[i][j]}"
# puts h[:condition].call(table_data[i][j]).inspect
if h[:condition].call(table_data[i][j])
h[:attributes].each { |attr, val|
# debug, verify deepcopy
# puts "objects are equal: #{_td_attrs[attr].equal?(o[:td_attrs][attr])}"
if !_td_attrs[attr].nil?
# assume the existing attribute is a string (other types don't make much sense for html)
_td_attrs[attr] << val
else
# create the attribute if it is not already there
_td_attrs[attr] = val
end
}
end
end
col = row.add_element("td", _td_attrs)
end
if o[:data_is_xhtml]
# we need to create a new document with a pseudo root because having multiple nodes at top
# level is not valid xml
doc = REXML::Document.new("<root>" + table_data[i][j].to_s + "</root>")
# then we move all children of root to the actual div middle element and insert after current
for elem in doc.root.to_a do
if elem.is_a?(REXML::Text)
# due to reasons unclear to me, text needs special treatment
col.add_text(elem)
else
col.add_element(elem) # add the td element
end
end
else
col.add_text(table_data[i][j].to_s)
end
end # for j in 0..table_data[i].length-1 do # column
end # for i in 0..table_data.length-1 do # row
@div_middle.insert_after(@current, temp)
@current = temp
return @current
end
# Appends a new heading element to body, and sets current to this new heading
# @param tag_type [String] specifiy "h1", "h2", "h3" for the heading, defaults to "h1"
# @param attrs [Hash] attributes for the <h#> element, any valid html attributes can be specified
# @option attrs [String] "class" by default every heading is added to the left table of contents (toc)
# use the class "onlyrtoc" or "bothtoc" to add a heading only to the right toc or to both tocs respectively
# @yieldreturn [String] the text to be added to the <h#> element
# @return [REXML::Element] the Element which was just added
def heading(tag_type="h1", attrs={}, &block)
temp = REXML::Element.new(tag_type)
temp.add_attributes(attrs)
@div_middle.insert_after(@current, temp)
@current = temp
raise "Block argument is mandatory" unless block_given?
text = encoding_fixer(block.call())
@current.text = text
return @current
end
# Inserts a new heading element at the very beginning of the middle div section, and points @current to this heading
# @param tag_type [String] specifiy "h1", "h2", "h3" for the heading, defaults to "h1"
# @param attrs [Hash] attributes for the <h#> element, any valid html attributes can be specified
# @option attrs [String] "class" by default every heading is added to the left table of contents (toc)
# use the class "onlyrtoc" or "bothtoc" to add a heading only to the right toc or to both tocs respectively
# @yieldreturn [String] the text to be added to the <h#> element
# @return [REXML::Element] the Element which was just added
def heading_top(tag_type="h1", attrs={}, &block)
temp = REXML::Element.new(tag_type)
temp.add_attributes(attrs)
# check if there are any child elements
if @div_middle.has_elements?()
# insert before the first child of div middle
@div_middle.insert_before("//div[@id='middle']/*[1]", temp)
else
# middle is empty, just insert the heading
@div_middle.insert_after(@current, temp)
end
@current = temp
raise "Block argument is mandatory" unless block_given?
text = encoding_fixer(block.call())
@current.text = text
return @current
end
# Helper Method for the highlight methods. it will introduce specific xhtml tags around parts of a text child of an xml element.
# @example
# we have the following xml part
# <test>
# some arbitrary
# text child content
# </test>
# now we call replace_text_with_elements to place <span> around the word "arbitrary"
# =>
# <test>
# some <span>arbitrary</span>
# text child content
# </test>
# @param parent [REXML::Element] the parent to which "element" should be attached after parsing, e.g. <test>
# @param element [REXML::Element] the Text element, into which tags will be added at the specified indices of @index_length_array, e.g. the REXML::Text children of <test> in the example
# @param tagname [String] the tag that will be introduced as <tagname> at the indices specified
# @param attribs [Hash] Attributes that will be added to the inserted tag e.g. <tagname attrib="test">
# @param index_length_array [Array] Array of the form [[index, lenght], [index, lenght], ...] that specifies
# the start position and length of the substring around which the tags will be introduced
def replace_text_with_elements(parent, element, tagname, attribs, index_length_array)
last_end = 0
index = 0
#puts index_length_array.inspect
#puts element.inspect
for j in index_length_array do
# reattach normal (unmatched) text
if j[0] > last_end
# text = REXML::Text.new(element.value()[ last_end, j[0] - last_end ])
# parent.add_text(text)
# add text without creating a textnode, textnode screws up formatting (e.g. all whitespace are condensed into one)
parent.add_text( element.value()[ last_end, j[0] - last_end ] )
end
#create the tag node with attributes and add the text to it
tag = parent.add_element(REXML::Element.new(tagname), attribs)
tag.add_text(element.value()[ j[0], j[1] ])
last_end = j[0]+j[1]
# in the last round check for any remaining text
if index == index_length_array.length - 1
if last_end < element.value().length
# text = REXML::Text.new(element.value()[ last_end, element.value().length - last_end ])
# parent.add(text)
# add text without creating a textnode, textnode screws up formatting (e.g. all whitespace are condensed into one)
parent.add_text( element.value()[ last_end, element.value().length - last_end ] )
end
end
index += 1
end # for j in positions do
# don't forget to reattach the textnode if there are no regex matches at all
if index == 0
parent.add(element)
end
end
#private_instance_methods(:replace_text_with_elements)
end
extend Custom
#class Test
# include XhtmlReportGenerator::Custom
#
#end
#puts Test.new.header()
| 44.240464 | 187 | 0.647337 |
6a7b8cce3758308e10cfacb8efe07ed1a63f9feb | 3,253 | class User < ApplicationRecord
has_many :microposts, dependent: :destroy
has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_id",
dependent: :destroy
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
attr_accessor :remember_token, :activation_token, :reset_token
before_save :downcase_email
before_create :create_activation_digest
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
# 渡された文字列のハッシュ値を返す
def self.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# ランダムなトークンを返す
def User.new_token
SecureRandom.urlsafe_base64
end
# 永続セッションのためにユーザーをデータベースに記憶する
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
# トークンがダイジェストと一致したらtrueを返す
def authenticated?(attribute, token)
digest = send("#{attribute}_digest")
return false if digest.nil?
BCrypt::Password.new(digest).is_password?(token)
end
# ユーザーのログイン情報を破棄する
def forget
update_attribute(:remember_digest, nil)
end
# アカウントを有効にする
def activate
update_columns(activated: true, activated_at: Time.zone.now)
end
# 有効化用のメールを送信する
def send_activation_email
UserMailer.account_activation(self).deliver_now
end
# パスワード再設定の属性を設定する
def create_reset_digest
self.reset_token = User.new_token
update_columns(reset_digest: User.digest(reset_token), reset_sent_at: Time.zone.now)
end
# パスワード再設定のメールを送信する
def send_password_reset_email
UserMailer.password_reset(self).deliver_now
end
# パスワード再設定の期限が切れている場合はtrueを返す
def password_reset_expired?
reset_sent_at < 2.hours.ago
end
# ユーザーのステータスフィードを返す
def feed
following_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
Micropost.where("user_id IN (#{following_ids})
OR user_id = :user_id", user_id: id)
end
# ユーザーをフォローする
def follow(other_user)
following << other_user
end
# ユーザーをフォロー解除する
def unfollow(other_user)
active_relationships.find_by(followed_id: other_user.id).destroy
end
# 現在のユーザーがフォローしてたらtrueを返す
def following?(other_user)
following.include?(other_user)
end
private
# メールアドレスをすべて小文字にする
def downcase_email
self.email.downcase!
end
# 有効化トークンとダイジェストを作成および代入する
def create_activation_digest
self.activation_token = User.new_token
self.activation_digest = User.digest(activation_token)
end
end
| 29.844037 | 89 | 0.702429 |
339b14a8aaf0500f87a18351c7d2a0cd462c052f | 3,479 | require 'spec_helper'
RSpec.describe SearchResultPresenter do
subject(:presenter) { SearchResultPresenter.new(document) }
let(:document) {
double(
Document,
title: title,
path: link,
metadata: metadata,
summary: 'I am a document',
is_historic: false,
government_name: 'The Government!',
promoted: false,
promoted_summary: 'I am a document',
show_metadata: false,
)
}
let(:title) { 'Investigation into the distribution of road fuels in parts of Scotland' }
let(:link) { 'link-1' }
let(:metadata) {
[
{ id: 'case-state', name: 'Case state', value: 'Open', type: 'text' },
{ id: 'opened-date', name: 'Opened date', value: '2006-7-14', type: 'date' },
{ id: 'case-type', name: 'Case type', value: 'CA98 and civil cartels', type: 'text' },
]
}
describe "#to_hash" do
it "returns a hash" do
expect(subject.to_hash.is_a?(Hash)).to be_truthy
end
let(:formatted_metadata) {
[
{ id: 'case-state', label: "Case state", value: "Open", is_text: true, labels: nil },
{ label: "Opened date", is_date: true, machine_date: "2006-07-14", human_date: "14 July 2006" },
{ id: 'case-type', label: "Case type", value: "CA98 and civil cartels", is_text: true, labels: nil },
]
}
it "returns a hash of the data we need to show the document" do
hash = subject.to_hash
expect(hash[:title]).to eql(title)
expect(hash[:link]).to eql(link)
expect(hash[:metadata]).to eql(formatted_metadata)
end
end
describe '#metadata' do
it 'returns an array' do
expect(subject.metadata.is_a?(Array)).to be_truthy
end
it 'formats metadata' do
allow(presenter).to receive(:build_text_metadata).and_call_original
allow(presenter).to receive(:build_date_metadata).and_call_original
subject.metadata
expect(subject).to have_received(:build_date_metadata).with(
id: "opened-date",
name: "Opened date",
value: "2006-7-14",
type: "date"
)
expect(subject).to have_received(:build_text_metadata).with(
id: "case-state",
name: "Case state",
value: "Open",
type: "text"
)
expect(subject).to have_received(:build_text_metadata).with(
id: "case-state",
name: "Case state",
value: "Open",
type: "text"
)
end
end
describe '#build_text_metadata' do
let(:data) {
{ name: 'some name', value: 'some value' }
}
it 'returns a hash' do
expect(subject.build_text_metadata(data).is_a?(Hash)).to be_truthy
end
it 'sets the type to text' do
expect(subject.build_text_metadata(data).fetch(:is_text)).to be_truthy
end
end
describe '#build_date_metadata' do
let(:data) {
{ name: 'some name', value: raw_date }
}
let(:raw_date) { '2003-12-01' }
let(:formatted_date) { '1 December 2003' }
let(:iso_date) { '2003-12-01' }
it 'returns a hash' do
expect(subject.build_date_metadata(data).is_a?(Hash)).to be_truthy
end
it 'sets the type to date' do
expect(subject.build_date_metadata(data).fetch(:is_date)).to be_truthy
end
it 'formats the date' do
date_metadata = subject.build_date_metadata(data)
expect(date_metadata.fetch(:human_date)).to eql(formatted_date)
expect(date_metadata.fetch(:machine_date)).to eql(iso_date)
end
end
end
| 29.235294 | 109 | 0.620293 |
f8a473475a13b5e7b6332f5393aaa4dab2cfe47b | 908 | class Fonttools < Formula
include Language::Python::Virtualenv
desc "Library for manipulating fonts"
homepage "https://github.com/fonttools/fonttools"
url "https://github.com/fonttools/fonttools/releases/download/4.2.3/fonttools-4.2.3.zip"
sha256 "da069660a5074a538729aa908b25ceab5fb8bd39e0bf6c0c21b5e6405672c8c5"
head "https://github.com/fonttools/fonttools.git"
bottle do
cellar :any_skip_relocation
sha256 "689049352b7014537b3e0dd0acb4364a11eba2a1dfd245aabb3276eee26312b2" => :catalina
sha256 "c079ba0455423a2389a410e7307c2c945144e270211525cff83f6e2f94a628ff" => :mojave
sha256 "ea0006f665d8468a13dd71005cba0c127b9316bada39dc988f23540f89b44828" => :high_sierra
end
depends_on "[email protected]"
def install
virtualenv_install_with_resources
end
test do
cp "/System/Library/Fonts/ZapfDingbats.ttf", testpath
system bin/"ttx", "ZapfDingbats.ttf"
end
end
| 32.428571 | 93 | 0.790749 |
ff5ea98a0630cae27170af7e64ab52209c6180a1 | 713 | module ClearData
def self.clear_datasets
StashEngine::Identifier.all.each do |iden|
puts "Destroying #{iden.identifier}"
iden.destroy
end
clear_solr
end
def self.clear_solr
clear_solr_url = "#{Blacklight.connection_config[:url]}/update?stream.body" +
'=<delete><query>*:*</query></delete>&commit=true'
puts "Clearing solr with #{clear_solr_url}"
# the following, commented out, is a query test to see if SOLR blacklight is accessible
#response = HTTParty.get("#{Blacklight.connection_config[:url]}/select?q=*%3A*&wt=json&indent=true")
#puts response
# this one will actually clear things out
response = HTTParty.get(clear_solr_url)
end
end | 28.52 | 104 | 0.69425 |
ed42e91ff9a9f709eedac142b5ee725f828e32bc | 9,276 | # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
module OCI
module Errors
# Represents an error which was generated somewhere during the process of making a HTTP request to an
# OCI service. This error contains the raw request and also exposes some convenience properties such
# as the opc-request-id for the request. This error makes no guarantee or inference about whether the
# error was generated based on a response from an OCI service, whether there was a network issue etc.
#
# When used directly, the {#cause} of the error should be inspected for the original error which resulted
# in this one being thrown.
#
# Subclasses, such as {OCI::Errors::ServiceError} and {OCI::Errors::NetworkError}, may have stronger
# definitions around what circumstances caused the error to be thrown.
class HttpRequestBasedError < StandardError
# The request which was made
#
# @return [Net::HTTPRequest]
attr_reader :request_made
# The request ID from the opc-request-id header. This could be the request ID returned from the service
# or, if there was no opc-request-id in the response, it will be the opc-request-id set client-side by the
# caller or the SDK (if there was no explicit caller-provided opc-request-id)
#
# @return [String]
attr_reader :request_id
# The error message
#
# @return [String]
attr_reader :message
def initialize(message: nil, request_made: nil)
# We need to mask the message attribute here as otherwise we use StandardError's
# implementation, which calls to_s and so referencing "message" in our to_s in
# this class (and subclasses) would go into an infinite loop
@message = message
@request_made = request_made
@request_id = @request_made['opc-request-id'] unless @request_made.nil?
end
def to_s
"{ 'message': '#{message}', 'opc-request-id': '#{request_id}' }"
end
end
# The base error for all requests that return error responses from the service.
class ServiceError < HttpRequestBasedError
# HTTP status code (such as 200 or 404)
#
# @return [Integer]
attr_reader :status_code
# A service-specific error code
#
# @return [String]
attr_reader :service_code
def initialize(status_code, service_code, request_id, message, request_made: nil)
@message = if message.nil? || message.strip.empty?
"The service returned error code #{status_code}"
else
message.strip
end
super(message: @message, request_made: request_made)
@status_code = status_code
@service_code = service_code
@request_id = request_id
end
def to_s
"{ 'message': '#{message}', 'status': #{status_code}, " \
"'code': '#{service_code}', 'opc-request-id': '#{request_id}' }"
end
end
# The base error for issues which are likely to be network related, rather than an application
# issue. This is defined as:
#
# * Requests which were sent from the SDK but the outcome was not a response from an OCI service. Further examples of include:
# * Gateway timeouts
# * Read or connection timeouts
# * Any {Errno} exception which was generated by making the request
# * Requests which resulted in a HTTP 408 (timeout)
#
# The {#cause} of this error can be inspected to see if there was an original error which resulted in this one being thrown.
class NetworkError < HttpRequestBasedError
# Error code, which is mapped to Net::HTTPResponse's code.to_i or 0 if the issue was reported by an exception.
#
# @return [Integer]
attr_reader :code
# The response received for the request, if any
#
# @return [Net::HTTPResponse]
attr_reader :response_received
def initialize(message, code, request_made: nil, response_received: nil)
super(message: message, request_made: request_made)
@code = code
@response_received = response_received
# If we have a request ID from the response then use that, otherwise just take the one from the
# request (the superclass constructor sets the opc-request-id from the request by default)
response_req_id = @response_received['opc-request-id'] unless @response_received.nil?
@request_id = response_req_id unless response_req_id.nil?
end
def to_s
response_body = response_received.body unless response_received.nil?
"{ 'message': '#{message}', 'status': #{code}, " \
"'opc-request-id': '#{request_id}', 'response-body': '#{response_body}' }"
end
end
# The base error for issues related to parsing the response received from the service. The {#response_body}
# can be inspected for the data which failed to parse and the {#cause} of this error can be inspected for the
# underlying parsing error which occurred
class ResponseParsingError < HttpRequestBasedError
# The response received for the request, and whose body we failed to parse
#
# @return [Net::HTTPResponse]
attr_reader :response_received
def initialize(message: 'Failed to parse response', request_made:, response_received:)
raise 'A message must be provided' if message.nil? || message.strip.empty?
raise 'The request made must be provided' if request_made.nil?
raise 'The response received must be provided' if response_received.nil?
super(message: message, request_made: request_made)
@response_received = response_received
@request_id = @response_received['opc-request-id'] unless @response_received['opc-request-id'].nil?
end
# The response body which we failed to parse
#
# @return [String]
def response_body
response_received.body
end
# The status code of the response (e.g. 200)
#
# @return [Integer]
def status_code
response_received.code.to_i
end
def to_s
"{ 'message': '#{message}', 'status': #{status_code}, " \
"'opc-request-id': '#{request_id}', 'response-body': '#{response_body}' }"
end
end
# Raised when the maximum wait time is exceeded.
class MaximumWaitTimeExceededError < StandardError; end
# Raised when a work request returns as failed while waiting on completion.
class WorkRequestFailedError < StandardError
# The failed work request.
attr_reader :work_request
# The status associated with the failed work request.
attr_reader :status
def initialize(work_request, status)
# TODO: May also want to include error_details.
super "Work request failed. ID: #{work_request.id}, Status: #{status}"
@work_request = work_request
@status = status
end
end
# Raised when a work request returns as canceled while waiting on completion.
class WorkRequestCanceledError < StandardError
# The failed work request.
attr_reader :work_request
# The status associated with the failed work request.
attr_reader :status
def initialize(work_request, status)
super "Work request canceled. ID: #{work_request.id}, Status: #{status}"
@work_request = work_request
@status = status
end
end
# Raised when there is an error performing a multipart upload (either a new upload or resuming
# an existing upload).
class MultipartUploadError < StandardError
# An array containing the underlying errors which caused the failure
# @return [Array]
attr_reader :errors
# The ID of multipart upload against which the error occurred, if known. This may be useful for
# resuming uploads which failed because of intermittent issues (e.g. network connectivity or
# HTTP 5xx errors received from the service)
# @return [String]
attr_reader :upload_id
def initialize(message, errors = [], upload_id = nil)
super(message)
@errors = errors
@upload_id = upload_id
end
end
# This error is used by the CompositeOperation classes to flag when part of an operation succeeded. For
# example, creating a resource succeeded but waiting for it to move into a given state failed. This
# error will contain any results of the composite operation which are available.
#
# The {#cause} of the error should be inspected for the original error which resulted
# in this one being thrown.
class CompositeOperationError < StandardError
# An array containing any successful {OCI::Response} from the composite operation
# @return [Array<Response>]
attr_reader :partial_results
def initialize(partial_results:)
@partial_results = partial_results
end
end
end
end
| 40.330435 | 245 | 0.673458 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.