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
|
---|---|---|---|---|---|
e8fda51f4fdd3ce854e1ab0f6599d41cd8288cb0 | 849 | # LeetCode #15 - 3Sum
# https://leetcode.com/problems/3sum/
# By two pointers, repeated for each suffix, avoiding duplicates.
# @param {Integer[]} nums
# @return {Integer[][]}
def three_sum(nums)
nums.sort!
triplets = []
while nums.size > 2
first = nums.shift
pairs = two_sum(nums, -first)
triplets.concat(pairs.each { |pair| pair.unshift(first) })
nums.shift while nums.first == first
end
triplets
end
def two_sum(nums, target)
pairs = []
left = 0
right = nums.size - 1
while left < right
first = nums[left]
second = nums[right]
sum = first + second
pairs << [first, second] if sum == target
if sum <= target
left += 1 while left < right && nums[left] == first
end
if sum >= target
right -= 1 while left < right && nums[right] == second
end
end
pairs
end
| 18.456522 | 65 | 0.614841 |
2892569cc1e6c2574a76edad2feffbf832106bc1 | 695 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe Canto, type: :model do
let(:blank_instance) { described_class.new }
context 'with an attribute-less instance' do
it { expect(blank_instance).to_not be_valid }
end
describe '#destroy' do
let(:stanza) { Fabricate(:stanza) }
let(:canto) { Fabricate(:canto, stanzas: [stanza]) }
it 'also destroys the associated stanzas' do
expect(canto).to be_persisted
expect(stanza).to be_persisted
canto.destroy
expect(canto).to_not be_persisted
expect(stanza).to_not be_persisted
end
end
describe '#stanzas' do
it { expect(blank_instance.stanzas).to be_empty }
end
end
| 23.965517 | 56 | 0.697842 |
6111d23bab15db334ab9ea9185c5f2f18564474d | 2,038 | require 'mimetype_fu'
require 'mime-types'
require 'mime/types'
require 'rack/rewrite'
require 'rack/csrf'
require 'rack/session/moneta'
require 'rack/builder'
require 'rack/lint'
require 'dragonfly/middleware'
require_relative 'middlewares'
if ENV['PROFILER']
require 'mongo'
require 'rack-mini-profiler'
end
module Locomotive::Steam
module Server
class << self
def default_middlewares
server, configuration = self, self.configuration
-> (stack) {
use(Rack::Rewrite) { r301 %r{^/(.*)/$}, '/$1' }
use Middlewares::Favicon
if configuration.serve_assets
use ::Rack::Static, {
root: configuration.asset_path,
urls: ['/images', '/fonts', '/samples', '/sites']
}
use Middlewares::DynamicAssets, {
root: configuration.asset_path,
minify: configuration.minify_assets
}
end
use Dragonfly::Middleware, :steam
use Rack::Lint
use Rack::Session::Moneta, configuration.moneta
use Rack::MiniProfiler if ENV['PROFILER']
server.steam_middleware_stack.each { |k| use k }
}
end
def steam_middleware_stack
[
Middlewares::DefaultEnv,
Middlewares::Site,
Middlewares::Logging,
Middlewares::UrlRedirection,
Middlewares::Robots,
Middlewares::Timezone,
Middlewares::EntrySubmission,
Middlewares::Locale,
Middlewares::LocaleRedirection,
Middlewares::PrivateAccess,
Middlewares::Path,
Middlewares::Page,
Middlewares::Sitemap,
Middlewares::TemplatizedPage
]
end
def to_app
stack = configuration.middleware
Rack::Builder.new do
stack.inject(self)
run Middlewares::Renderer.new(nil)
end
end
def configuration
Locomotive::Steam.configuration
end
end
end
end
| 22.644444 | 63 | 0.58685 |
ff400008b044f62e40f57cf287347201c9bdbcb5 | 1,025 | require 'rails_helper'
RSpec.describe Store, type: :model do
it "has valid attributes" do
store = Store.create(name: "Guess", slug: "guess", status:"active")
expect(store.name).to eq("Guess")
expect(store.slug).to eq("guess")
expect(store.status).to eq("active")
end
it "has to have a name to be valid" do
store = build(:store, name: nil)
expect(store).to be_invalid
end
it "must have a unique name to be valid" do
store1 = create(:store, name: "Guess")
store2 = build(:store, name: "Guess")
expect(store2).to be_invalid
end
it "can generate a slug" do
store = Store.create(name: "Diesel")
expect(store.generate_slug).to eq("diesel")
end
it "can turn its slug to a param" do
store = Store.create(name: "Diesel")
expect(store.to_param).to eq("diesel")
end
describe "relationships" do
it {should have_many(:items)}
it {should have_many(:order_items)}
it {should have_many(:orders)}
it {should have_many(:users)}
end
end
| 25 | 71 | 0.653659 |
7a75a529168f40f566d1929e91ae7c389920c33d | 736 | module SmartAnswer
module Question
class Value < Base
def initialize(flow, name, options = {}, &block)
@parse = options[:parse]
super(flow, name, &block)
end
def parse_input(raw_input)
if Integer == @parse
begin
Integer(raw_input)
rescue TypeError, ArgumentError
raise InvalidResponse
end
elsif @parse == :to_i
raw_input.to_i
elsif Float == @parse
begin
Float(raw_input)
rescue TypeError, ArgumentError
raise InvalidResponse
end
elsif @parse == :to_f
raw_input.to_f
else
super
end
end
end
end
end
| 22.30303 | 54 | 0.527174 |
5d95cbef5e4288baa618ce74aed3266afab9ce72 | 325 | module Anilibria
module Api
module Types
Feed = DryTypes::Array.of(
DryTypes.Constructor(Types::Base) do |i|
case i.keys.first
when :title then Types::Title.new(i[:title])
when :youtube then Types::YouTube.new(i[:youtube])
end
end
)
end
end
end
| 21.666667 | 60 | 0.566154 |
330651a42c4a4aa440730ebb30123432649fba40 | 932 | first_lambda = lambda { puts "my first lambda"}
first_lambda.call
##################
first_lambda = -> { puts "my first lambda"}
first_lambda.call
###################
first_lambda = -> (names){ names.each { |name |puts name} }
names = ["joรฃo", "maria", "pedro"]
first_lambda.call(names)
####################
my_lambda = lambda do |numbers|
index = 0
puts 'Nรบmero atual + Prรณximo nรบmero'
numbers.each do |number|
return if numbers[index] == numbers.last
puts "(#{numbers[index]}) + (#{numbers[index + 1]})"
puts numbers[index] + numbers[index + 1]
index += 1
end
end
numbers = [1, 2, 3, 4]
my_lambda.call(numbers)
############################ Argumentos abaixo
def foo(first_lambda, second_lambda)
first_lambda.call
second_lambda.call
end
first_lambda = lambda { puts "my first lambda"}
second_lambda = lambda { puts "my second lambda"}
foo(first_lambda, second_lambda)
| 20.26087 | 59 | 0.607296 |
6a352facb1f89b691e656b55233c3da62f86f447 | 1,327 | # encoding: UTF-8
require_relative '../metadata/column'
module GoodData
module Model
##
# GoodData display form abstraction. Represents a default representation
# of an attribute column or an additional representation defined in a LABEL
# field
#
class Label < Column
attr_accessor :attribute
def type_prefix;
'label';
end
# def initialize(hash, schema)
def initialize(hash, attribute, schema)
super hash, schema
attribute = attribute.nil? ? schema.fields.find { |field| field.name === hash[:reference] } : attribute
@attribute = attribute
attribute.labels << self
end
def to_maql_create
'# LABEL FROM LABEL'
"ALTER ATTRIBUTE {#{@attribute.identifier}} ADD LABELS {#{identifier}}" \
+ " VISUAL (TITLE #{title.inspect}) AS {#{column}};\n"
end
def to_manifest_part(mode)
{
'populates' => [identifier],
'mode' => mode,
'columnName' => name
}
end
def column
"#{@attribute.table}.#{LABEL_COLUMN_PREFIX}#{name}"
end
alias :inspect_orig :inspect
def inspect
inspect_orig.sub(/>$/, " @attribute=#{@attribute.to_s.sub(/>$/, " @name=#{@attribute.name}")}>")
end
end
end
end
| 25.037736 | 111 | 0.584778 |
332d029114c010b9d73d7ed76a146d91b7f5f954 | 334 | class Restaurant < ActiveRecord::Base
validates_presence_of :cuisine, :location #:overall_rating
validates :name, presence: true, uniqueness: true #validates restaurant name to ensure uniqueness/prevent same restaurant from being persisted to database more than once.
has_many :reviews
has_many :users, through: :reviews
end
| 41.75 | 172 | 0.799401 |
2630a0f3a43e94db2ecdd9f6ed96553b9823316e | 13,611 | # encoding: utf-8
require "cases/helper"
require 'models/owner'
require 'tempfile'
require 'support/ddl_helper'
module ActiveRecord
module ConnectionAdapters
class SQLite3AdapterTest < ActiveRecord::TestCase
include DdlHelper
self.use_transactional_fixtures = false
class DualEncoding < ActiveRecord::Base
end
def setup
@conn = Base.sqlite3_connection database: ':memory:',
adapter: 'sqlite3',
timeout: 100
end
def test_bad_connection
assert_raise ActiveRecord::NoDatabaseError do
connection = ActiveRecord::Base.sqlite3_connection(adapter: "sqlite3", database: "/tmp/should/_not/_exist/-cinco-dog.db")
connection.exec_query('drop table if exists ex')
end
end
unless in_memory_db?
def test_connect_with_url
original_connection = ActiveRecord::Base.remove_connection
tf = Tempfile.open 'whatever'
url = "sqlite3:#{tf.path}"
ActiveRecord::Base.establish_connection(url)
assert ActiveRecord::Base.connection
ensure
tf.close
tf.unlink
ActiveRecord::Base.establish_connection(original_connection)
end
def test_connect_memory_with_url
original_connection = ActiveRecord::Base.remove_connection
url = "sqlite3::memory:"
ActiveRecord::Base.establish_connection(url)
assert ActiveRecord::Base.connection
ensure
ActiveRecord::Base.establish_connection(original_connection)
end
end
def test_valid_column
with_example_table do
column = @conn.columns('ex').find { |col| col.name == 'id' }
assert @conn.valid_type?(column.type)
end
end
# sqlite databases should be able to support any type and not
# just the ones mentioned in the native_database_types.
# Therefore test_invalid column should always return true
# even if the type is not valid.
def test_invalid_column
assert @conn.valid_type?(:foobar)
end
def test_column_types
owner = Owner.create!(name: "hello".encode('ascii-8bit'))
owner.reload
select = Owner.columns.map { |c| "typeof(#{c.name})" }.join ', '
result = Owner.connection.exec_query <<-esql
SELECT #{select}
FROM #{Owner.table_name}
WHERE #{Owner.primary_key} = #{owner.id}
esql
assert(!result.rows.first.include?("blob"), "should not store blobs")
ensure
owner.delete
end
def test_exec_insert
with_example_table do
column = @conn.columns('ex').find { |col| col.name == 'number' }
vals = [[column, 10]]
@conn.exec_insert('insert into ex (number) VALUES (?)', 'SQL', vals)
result = @conn.exec_query(
'select number from ex where number = ?', 'SQL', vals)
assert_equal 1, result.rows.length
assert_equal 10, result.rows.first.first
end
end
def test_primary_key_returns_nil_for_no_pk
with_example_table 'id int, data string' do
assert_nil @conn.primary_key('ex')
end
end
def test_connection_no_db
assert_raises(ArgumentError) do
Base.sqlite3_connection {}
end
end
def test_bad_timeout
assert_raises(TypeError) do
Base.sqlite3_connection database: ':memory:',
adapter: 'sqlite3',
timeout: 'usa'
end
end
# connection is OK with a nil timeout
def test_nil_timeout
conn = Base.sqlite3_connection database: ':memory:',
adapter: 'sqlite3',
timeout: nil
assert conn, 'made a connection'
end
def test_connect
assert @conn, 'should have connection'
end
# sqlite3 defaults to UTF-8 encoding
def test_encoding
assert_equal 'UTF-8', @conn.encoding
end
def test_bind_value_substitute
bind_param = @conn.substitute_at('foo', 0)
assert_equal Arel.sql('?'), bind_param
end
def test_exec_no_binds
with_example_table 'id int, data string' do
result = @conn.exec_query('SELECT id, data FROM ex')
assert_equal 0, result.rows.length
assert_equal 2, result.columns.length
assert_equal %w{ id data }, result.columns
@conn.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
result = @conn.exec_query('SELECT id, data FROM ex')
assert_equal 1, result.rows.length
assert_equal 2, result.columns.length
assert_equal [[1, 'foo']], result.rows
end
end
def test_exec_query_with_binds
with_example_table 'id int, data string' do
@conn.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
result = @conn.exec_query(
'SELECT id, data FROM ex WHERE id = ?', nil, [[nil, 1]])
assert_equal 1, result.rows.length
assert_equal 2, result.columns.length
assert_equal [[1, 'foo']], result.rows
end
end
def test_exec_query_typecasts_bind_vals
with_example_table 'id int, data string' do
@conn.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
column = @conn.columns('ex').find { |col| col.name == 'id' }
result = @conn.exec_query(
'SELECT id, data FROM ex WHERE id = ?', nil, [[column, '1-fuu']])
assert_equal 1, result.rows.length
assert_equal 2, result.columns.length
assert_equal [[1, 'foo']], result.rows
end
end
def test_quote_binary_column_escapes_it
DualEncoding.connection.execute(<<-eosql)
CREATE TABLE IF NOT EXISTS dual_encodings (
id integer PRIMARY KEY AUTOINCREMENT,
name varchar(255),
data binary
)
eosql
str = "\x80".force_encoding("ASCII-8BIT")
binary = DualEncoding.new name: 'ใใใ ใใพใ๏ผ', data: str
binary.save!
assert_equal str, binary.data
ensure
DualEncoding.connection.execute('DROP TABLE IF EXISTS dual_encodings')
end
def test_type_cast_should_not_mutate_encoding
name = 'hello'.force_encoding(Encoding::ASCII_8BIT)
Owner.create(name: name)
assert_equal Encoding::ASCII_8BIT, name.encoding
ensure
Owner.delete_all
end
def test_execute
with_example_table do
@conn.execute "INSERT INTO ex (number) VALUES (10)"
records = @conn.execute "SELECT * FROM ex"
assert_equal 1, records.length
record = records.first
assert_equal 10, record['number']
assert_equal 1, record['id']
end
end
def test_quote_string
assert_equal "''", @conn.quote_string("'")
end
def test_insert_sql
with_example_table do
2.times do |i|
rv = @conn.insert_sql "INSERT INTO ex (number) VALUES (#{i})"
assert_equal(i + 1, rv)
end
records = @conn.execute "SELECT * FROM ex"
assert_equal 2, records.length
end
end
def test_insert_sql_logged
with_example_table do
sql = "INSERT INTO ex (number) VALUES (10)"
name = "foo"
assert_logged [[sql, name, []]] do
@conn.insert_sql sql, name
end
end
end
def test_insert_id_value_returned
with_example_table do
sql = "INSERT INTO ex (number) VALUES (10)"
idval = 'vuvuzela'
id = @conn.insert_sql sql, nil, nil, idval
assert_equal idval, id
end
end
def test_select_rows
with_example_table do
2.times do |i|
@conn.create "INSERT INTO ex (number) VALUES (#{i})"
end
rows = @conn.select_rows 'select number, id from ex'
assert_equal [[0, 1], [1, 2]], rows
end
end
def test_select_rows_logged
with_example_table do
sql = "select * from ex"
name = "foo"
assert_logged [[sql, name, []]] do
@conn.select_rows sql, name
end
end
end
def test_transaction
with_example_table do
count_sql = 'select count(*) from ex'
@conn.begin_db_transaction
@conn.create "INSERT INTO ex (number) VALUES (10)"
assert_equal 1, @conn.select_rows(count_sql).first.first
@conn.rollback_db_transaction
assert_equal 0, @conn.select_rows(count_sql).first.first
end
end
def test_tables
with_example_table do
assert_equal %w{ ex }, @conn.tables
with_example_table 'id integer PRIMARY KEY AUTOINCREMENT, number integer', 'people' do
assert_equal %w{ ex people }.sort, @conn.tables.sort
end
end
end
def test_tables_logs_name
sql = <<-SQL
SELECT name FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
SQL
assert_logged [[sql.squish, 'SCHEMA', []]] do
@conn.tables('hello')
end
end
def test_indexes_logs_name
with_example_table do
assert_logged [["PRAGMA index_list(\"ex\")", 'SCHEMA', []]] do
@conn.indexes('ex', 'hello')
end
end
end
def test_table_exists_logs_name
with_example_table do
sql = <<-SQL
SELECT name FROM sqlite_master
WHERE type = 'table'
AND NOT name = 'sqlite_sequence' AND name = \"ex\"
SQL
assert_logged [[sql.squish, 'SCHEMA', []]] do
assert @conn.table_exists?('ex')
end
end
end
def test_columns
with_example_table do
columns = @conn.columns('ex').sort_by { |x| x.name }
assert_equal 2, columns.length
assert_equal %w{ id number }.sort, columns.map { |x| x.name }
assert_equal [nil, nil], columns.map { |x| x.default }
assert_equal [true, true], columns.map { |x| x.null }
end
end
def test_columns_with_default
with_example_table 'id integer PRIMARY KEY AUTOINCREMENT, number integer default 10' do
column = @conn.columns('ex').find { |x|
x.name == 'number'
}
assert_equal 10, column.default
end
end
def test_columns_with_not_null
with_example_table 'id integer PRIMARY KEY AUTOINCREMENT, number integer not null' do
column = @conn.columns('ex').find { |x| x.name == 'number' }
assert_not column.null, "column should not be null"
end
end
def test_indexes_logs
with_example_table do
assert_logged [["PRAGMA index_list(\"ex\")", "SCHEMA", []]] do
@conn.indexes('ex')
end
end
end
def test_no_indexes
assert_equal [], @conn.indexes('items')
end
def test_index
with_example_table do
@conn.add_index 'ex', 'id', unique: true, name: 'fun'
index = @conn.indexes('ex').find { |idx| idx.name == 'fun' }
assert_equal 'ex', index.table
assert index.unique, 'index is unique'
assert_equal ['id'], index.columns
end
end
def test_non_unique_index
with_example_table do
@conn.add_index 'ex', 'id', name: 'fun'
index = @conn.indexes('ex').find { |idx| idx.name == 'fun' }
assert_not index.unique, 'index is not unique'
end
end
def test_compound_index
with_example_table do
@conn.add_index 'ex', %w{ id number }, name: 'fun'
index = @conn.indexes('ex').find { |idx| idx.name == 'fun' }
assert_equal %w{ id number }.sort, index.columns.sort
end
end
def test_primary_key
with_example_table do
assert_equal 'id', @conn.primary_key('ex')
with_example_table 'internet integer PRIMARY KEY AUTOINCREMENT, number integer not null', 'foos' do
assert_equal 'internet', @conn.primary_key('foos')
end
end
end
def test_no_primary_key
with_example_table 'number integer not null' do
assert_nil @conn.primary_key('ex')
end
end
def test_supports_extensions
assert_not @conn.supports_extensions?, 'does not support extensions'
end
def test_respond_to_enable_extension
assert @conn.respond_to?(:enable_extension)
end
def test_respond_to_disable_extension
assert @conn.respond_to?(:disable_extension)
end
private
def assert_logged logs
subscriber = SQLSubscriber.new
subscription = ActiveSupport::Notifications.subscribe('sql.active_record', subscriber)
yield
assert_equal logs, subscriber.logged
ensure
ActiveSupport::Notifications.unsubscribe(subscription)
end
def with_example_table(definition = nil, table_name = 'ex', &block)
definition ||= <<-SQL
id integer PRIMARY KEY AUTOINCREMENT,
number integer
SQL
super(@conn, table_name, definition, &block)
end
end
end
end
| 30.934091 | 131 | 0.58607 |
d5d182b6196e3834d0604d2db7c6821e49745910 | 9,177 | Pod::Spec.new do |s|
s.name = "TQKit"
s.version = "2.0.2"
s.summary = "TQKit is iOS TQ Project"
s.description = <<-DESC
ๆฐๅขๅป้คๅญ็ฌฆไธฒๆๆ็ฉบๆ ผ็ๆนๆณ๏ผๆฐๅข่ทๅ็ฝ็ปๆถ้ด็ๆนๆณ
DESC
s.homepage = "https://github.com/love0912/TQKit"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "guojie" => "[email protected]" }
s.ios.deployment_target = "8.0"
s.source = { :git => "https://github.com/love0912/TQKit.git", :tag => "#{s.version}"}
# โโโ Source Code โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ #
s.source_files = "TQKit/TQKit/TQKit.h"
s.exclude_files = "TQKit/TQKit.xcodeproj"
# โโโ Project Linking โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ #
s.frameworks = 'Foundation', 'CoreGraphics', 'UIKit', 'QuartzCore', 'SystemConfiguration'
s.libraries = 'sqlite3', 'z'
s.requires_arc = true
# s.subspec '3rdLib' do |ss|
# ss.dependency 'TQKit/Category'
# ss.subspec 'AFNetworking' do |sss|
# sss.source_files = 'TQKit/TQKit/3rdLib/AFNetworking/*'
#end
#ss.subspec 'YYCache' do |sss1|
# sss1.source_files = 'TQKit/TQKit/3rdLib/YYCache/*'
# end
# end
s.subspec 'Category' do |ss|
ss.source_files = 'TQKit/TQKit/Category/*.h'
ss.dependency 'YYCache', '~> 1.0.4'
ss.subspec 'Foundation' do |sss|
sss.source_files = 'TQKit/TQKit/Category/Foundation/TT_FoundationHeader.h'
sss.subspec 'NSData' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/Foundation/NSData/*'
end
sss.subspec 'NSDate' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/Foundation/NSDate/*'
end
sss.subspec 'NSDictionary' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/Foundation/NSDictionary/*'
end
sss.subspec 'NSObject' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/Foundation/NSObject/*'
end
sss.subspec 'NSNumber' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/Foundation/NSNumber/*'
ssss.dependency 'TQKit/Category/Foundation/NSData'
end
sss.subspec 'NSString' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/Foundation/NSString/*'
ssss.dependency 'TQKit/Category/Foundation/NSNumber'
end
sss.subspec 'NSTimer' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/Foundation/NSTimer/*'
end
sss.subspec 'NSUserDefaults' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/Foundation/NSUserDefaults/*'
end
end
ss.subspec 'Quartz' do |sss|
sss.source_files = 'TQKit/TQKit/Category/Quartz/*'
end
ss.subspec 'UIKit' do |sss|
sss.source_files = 'TQKit/TQKit/Category/UIKit/TT_UIKitHeader.h'
sss.subspec 'UIApplication' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UIApplication/*'
ssss.dependency 'TQKit/Category/UIKit/UIDevice'
end
sss.subspec 'UIBarButtonItem' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UIBarButtonItem/*'
end
sss.subspec 'UIBezierPath' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UIBezierPath/*'
ssss.dependency 'TQKit/Category/UIKit/UIFont'
end
sss.subspec 'UIButton' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UIButton/*'
end
sss.subspec 'UIColor' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UIColor/*'
end
sss.subspec 'UIControl' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UIControl/*'
end
sss.subspec 'UIDevice' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UIDevice/*'
ssss.dependency 'TQKit/Category/Foundation/NSString'
end
sss.subspec 'UIFont' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UIFont/*'
end
sss.subspec 'UIGesture' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UIGesture/*'
end
sss.subspec 'UIImage' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UIImage/*'
ssss.dependency 'TQKit/Category/YYUtils'
end
sss.subspec 'UIImageView' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UIImageView/*'
end
sss.subspec 'UINavigationBar' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UINavigationBar/*'
end
sss.subspec 'UINavigationController' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UINavigationController/*.{h,m}'
end
sss.subspec 'UIScrollView' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UIScrollView/*'
end
sss.subspec 'UITableView' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UITableView/*'
end
sss.subspec 'UITextField' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UITextField/*'
end
sss.subspec 'UITextView' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UITextView/*'
end
sss.subspec 'UIView' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UIView/*'
end
sss.subspec 'UIViewController' do |ssss|
ssss.source_files = 'TQKit/TQKit/Category/UIKit/UIViewController/*'
end
end
ss.subspec 'YYUtils' do |sss|
sss.source_files = 'TQKit/TQKit/Category/YYUtils/*'
sss.dependency 'TQKit/Category/UIKit/UIView'
end
end
s.subspec 'Macros' do |ss|
ss.source_files = 'TQKit/TQKit/Macros/*.h'
ss.dependency 'TQKit/Category'
end
s.subspec 'Utils' do |ss|
ss.source_files = 'TQKit/TQKit/Utils/TT_Utils_Header.h'
ss.dependency 'TQKit/Macros'
ss.subspec 'TTAlertUtil' do |sss|
sss.source_files = 'TQKit/TQKit/Utils/TTAlertUtil/*'
sss.dependency 'TQKit/Category/Foundation/NSString'
end
ss.subspec 'TTProgressHUD' do |sss|
sss.source_files = 'TQKit/TQKit/Utils/TTProgressHUD/*.{h,m}'
sss.dependency 'SVProgressHUD', '~> 2.1.2'
end
ss.subspec 'AppInfoUtil' do |sss|
sss.source_files = 'TQKit/TQKit/Utils/AppInfoUtil/*'
sss.dependency 'AFNetworking', '~> 3.1.0'
end
ss.subspec 'TTQRCodeUtil' do |sss|
sss.source_files = 'TQKit/TQKit/Utils/TTQRCodeUtil/*'
end
ss.subspec 'TTTableViewUtil' do |sss|
sss.source_files = 'TQKit/TQKit/Utils/TTTableViewUtil/*'
end
ss.subspec 'UserInfoUtil' do |sss|
sss.source_files = 'TQKit/TQKit/Utils/UserInfoUtil/*'
sss.dependency 'TQKit/Core/Action/Constants'
end
end
s.subspec 'Core' do |ss|
ss.dependency 'AFNetworking', '~> 3.1.0'
ss.subspec 'Action' do |sss|
sss.subspec 'Reachability' do |ssss|
ssss.source_files = 'TQKit/TQKit/Core/Action/Reachability/*.{h,m}'
ssss.dependency 'TQKit/Utils'
end
sss.subspec 'Constants' do |ssss|
ssss.source_files = 'TQKit/TQKit/Core/Action/Constants/*.{h,m}'
end
sss.subspec 'Actions' do |ssss|
ssss.source_files = 'TQKit/TQKit/Core/Action/Actions/*.{h,m}'
ssss.dependency 'TQKit/Core/Action/Reachability'
end
end
ss.subspec 'Service' do |sss|
sss.source_files = 'TQKit/TQKit/Core/Service/*.{h,m}'
sss.dependency 'TQKit/Core/Action'
end
ss.subspec 'TTMediator' do |sss|
sss.source_files = 'TQKit/TQKit/Core/TTMediator/*.{h,m}'
sss.dependency 'TQKit/Category/Foundation/NSString'
end
end
s.subspec 'Component' do |ss|
ss.source_files = 'TQKit/TQKit/Component/TT_ComponetHeader.h'
ss.subspec 'TTBanner' do |sss|
sss.source_files = 'TQKit/TQKit/Component/TTBanner/*'
end
ss.subspec 'TTQRCodeScan' do |sss|
sss.source_files = 'TQKit/TQKit/Component/TTQRCodeScan/*.{h,m}'
sss.frameworks = 'AVFoundation'
end
end
end
| 41.90411 | 99 | 0.544296 |
872f45d9c9d4cbda3bc798ed67c9a0eb3246bde6 | 1,330 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'bocci/version'
Gem::Specification.new do |spec|
spec.name = "bocci"
spec.version = Bocci::VERSION
spec.authors = ["mrpero"]
spec.email = ["[email protected]"]
spec.summary = %q{bocci crawler}
spec.description = %q{๏ผไบบใผใฃใกใฎใฏใญใผใฉใผ}
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against " \
"public gem pushes."
end
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.14"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
end
| 35.945946 | 96 | 0.654135 |
bb7e94f1c633c94f76399789ba027f98a88e436f | 2,133 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2021_05_08_124748) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "users", force: :cascade do |t|
t.string "provider", default: "email", null: false
t.string "uid", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.boolean "allow_password_change", default: false
t.datetime "remember_created_at"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email"
t.string "name"
t.string "nickname"
t.string "image"
t.string "email"
t.integer "sign_in_count", default: 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.json "tokens"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
t.index ["uid", "provider"], name: "index_users_on_uid_and_provider", unique: true
end
end
| 43.530612 | 95 | 0.741678 |
ff65db486870670f09fa4e28364947e54642a45b | 1,949 | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2020 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
module OpenProject
##
# Events defined in OpenProject, e.g. created work packages.
# The module defines a constant for each event.
#
# Plugins should register their events here too by prepending a module
# including the respective constants.
#
# @note Does not include all events but it should!
# @see OpenProject::Notifications
module Events
AGGREGATED_WORK_PACKAGE_JOURNAL_READY = "aggregated_work_package_journal_ready".freeze
AGGREGATED_WIKI_JOURNAL_READY = "aggregated_wiki_journal_ready".freeze
NEW_TIME_ENTRY_CREATED = "new_time_entry_created".freeze
PROJECT_CREATED = "project_created".freeze
PROJECT_UPDATED = "project_updated".freeze
PROJECT_RENAMED = "project_renamed".freeze
end
end
| 39.77551 | 91 | 0.768086 |
f7e4ea6383f180aff003c9dbf8e9a202cb2ba257 | 1,456 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `rails
# db:schema:load`. When creating a new database, `rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_06_16_144719) do
create_table "accounts", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["email"], name: "index_accounts_on_email", unique: true
t.index ["reset_password_token"], name: "index_accounts_on_reset_password_token", unique: true
end
end
| 45.5 | 98 | 0.757555 |
bf67b336b14a775b75101a2c5f7d8b9ae5a03b6a | 1,282 | # frozen_string_literal: true
module Pipedawg
# util class
class Util
def self.expand_env_vars(item) # rubocop:disable Metrics/MethodLength
case item
when Array
item.map { |i| expand_env_vars(i) }
when Hash
item.each { |k, v| item[k] = expand_env_vars(v) }
item.transform_keys! { |k| expand_env_vars(k) }
item
when String
item.gsub(/\${([^} ]+)}/) do |e|
ENV[e.gsub('${', '').gsub('}', '')]
end
else
item
end
end
def self.puts_proxy_vars
puts 'Proxy settings:'
puts "http_proxy: #{ENV['http_proxy']}"
puts "https_proxy: #{ENV['https_proxy']}"
puts "no_proxy: #{ENV['no_proxy']}"
puts "HTTP_PROXY: #{ENV['HTTP_PROXY']}"
puts "HTTPS_PROXY: #{ENV['HTTPS_PROXY']}"
puts "NO_PROXY: #{ENV['NO_PROXY']}"
end
def self.echo_proxy_vars
script = ['echo Proxy settings:']
script << 'echo http_proxy: "${http_proxy}"'
script << 'echo https_proxy: "${https_proxy}"'
script << 'echo no_proxy: "${no_proxy}"'
script << 'echo HTTP_PROXY: "${HTTP_PROXY}"'
script << 'echo HTTPS_PROXY: "${HTTPS_PROXY}"'
script << 'echo NO_PROXY: "${NO_PROXY}"'
script
end
end
end
| 28.488889 | 73 | 0.562402 |
3999d51225e6e68baf436ddeba91a245fa916fb8 | 734 | cask 'xamarin-jdk' do
version '7.71'
sha256 '70a18547b529a111c4e5cf133532082e142908819b0d61e273c21dee86fcc87a'
url "https://download.xamarin.com/Installer/MonoForAndroid/jdk-#{version.major}u#{version.minor}-macosx-x64.dmg"
appcast 'https://static.xamarin.com/installer_assets/v3/Mac/Universal/InstallationManifest.xml',
checkpoint: '855d95a330efdd9cc13cbaabc6e49dfcda111db3b16cbc6345e3a0d17e769972'
name 'Xamarin Java JDK'
homepage 'https://xamarin.com/platform'
license :unknown # TODO: change license and remove this comment; ':unknown' is a machine-generated placeholder
pkg "JDK #{version.major} Update #{version.minor}.pkg"
uninstall pkgutil: "com.oracle.jdk#{version.major}u#{version.minor}"
end
| 45.875 | 114 | 0.779292 |
21648c17c50a3673835d173c07fce66bd2b3ed9d | 3,303 | require 'rails_helper'
describe "upload TaggedAnimalAssessment category", type: :feature do
let(:user) { User.create({ :email => "[email protected]",
:password => "password",
:password_confirmation => "password" }) }
let(:valid_file) { "db/sample_data_files/tagged_animal_assessment/Tagged_assessment_12172018 (original).csv" }
let(:invalid_file) { "spec/support/csv/invalid_headers.csv" }
let(:incomplete_data_file) { "spec/support/csv/Tagged_assessment_03172018-invalid-rows.csv" }
let(:expected_success_message) { 'Successfully queued spreadsheet for import' }
before do
sign_in user
visit new_file_upload_path
end
context 'when user successfully uploads a CSV with no errors' do
it "creates new ProcessedFile record with 'Processed' status " do
upload_file("Tagged Animal Assessment", valid_file)
processed_file = ProcessedFile.last
expect(ProcessedFile.count).to eq 1
expect(processed_file.status).to eq "Processed"
expect(processed_file.job_errors).to eq(nil)
expect(processed_file.job_stats).to eq(
{ "row_count"=>201,
"rows_imported"=>201,
"shl_case_numbers" => {"SF16-9A"=>100, "SF16-9B"=>21, "SF16-9C"=>11, "SF16-9D"=>69},
}
)
expect(page).to have_content expected_success_message
end
end
context 'when user uploads a CSV with invalid headers' do
it "creates new ProcessedFile record with 'Failed' status" do
upload_file("Tagged Animal Assessment", invalid_file)
processed_file = ProcessedFile.last
expect(ProcessedFile.count).to eq 1
expect(processed_file.status).to eq "Failed"
expect(processed_file.job_errors).to eq "Does not have valid header(s). Data not imported!"
expect(processed_file.job_stats).to eq({})
expect(page).to have_content expected_success_message
end
end
context 'when user upload a CSV that has been already processed' do
let(:temporary_file) { create(:temporary_file, contents: '') }
before do
FactoryBot.create :processed_file,
status: 'Processed',
temporary_file_id: temporary_file.id
end
it "creates new ProcessedFile record with 'Failed' status" do
upload_file("Tagged Animal Assessment", valid_file)
processed_file = ProcessedFile.where(status: "Failed").first
expect(ProcessedFile.count).to eq 2
expect(processed_file.job_errors).to eq "Already processed a file from the same upload event. Data not imported!"
expect(processed_file.job_stats).to eq({})
expect(page).to have_content expected_success_message
end
end
context 'when user upload file with invalid rows' do
it "creates new ProcessedFile record with 'Failed' status" do
upload_file("Tagged Animal Assessment", incomplete_data_file)
processed_file = ProcessedFile.last
expect(ProcessedFile.count).to eq 1
expect(processed_file.status).to eq "Failed"
expect(processed_file.job_errors).to eq("Does not have valid row(s). Data not imported!")
expect(processed_file.job_stats).to eq({"row_number_2"=>{"shl_case_number"=>[{"error"=>"blank"}]}, "row_number_3"=>{"tag"=>[{"error"=>"blank"}]}})
expect(page).to have_content expected_success_message
end
end
end
| 39.795181 | 152 | 0.703603 |
26e90e8cf8c0618bb90d11c7301916758be88d8f | 6,718 | # frozen_string_literal: true
class GitPushService < BaseService
attr_accessor :push_data, :push_commits
include Gitlab::Access
include Gitlab::Utils::StrongMemoize
# The N most recent commits to process in a single push payload.
PROCESS_COMMIT_LIMIT = 100
# This method will be called after each git update
# and only if the provided user and project are present in GitLab.
#
# All callbacks for post receive action should be placed here.
#
# Next, this method:
# 1. Creates the push event
# 2. Updates merge requests
# 3. Recognizes cross-references from commit messages
# 4. Executes the project's webhooks
# 5. Executes the project's services
# 6. Checks if the project's main language has changed
#
def execute
project.repository.after_create if project.empty_repo?
project.repository.after_push_commit(branch_name)
if push_remove_branch?
project.repository.after_remove_branch
@push_commits = []
elsif push_to_new_branch?
project.repository.after_create_branch
# Re-find the pushed commits.
if default_branch?
# Initial push to the default branch. Take the full history of that branch as "newly pushed".
process_default_branch
else
# Use the pushed commits that aren't reachable by the default branch
# as a heuristic. This may include more commits than are actually pushed, but
# that shouldn't matter because we check for existing cross-references later.
@push_commits = project.repository.commits_between(project.default_branch, params[:newrev])
# don't process commits for the initial push to the default branch
process_commit_messages
end
elsif push_to_existing_branch?
# Collect data for this git push
@push_commits = project.repository.commits_between(params[:oldrev], params[:newrev])
process_commit_messages
# Update the bare repositories info/attributes file using the contents of the default branches
# .gitattributes file
update_gitattributes if default_branch?
end
execute_related_hooks
perform_housekeeping
update_remote_mirrors
update_caches
update_signatures
end
def update_gitattributes
project.repository.copy_gitattributes(params[:ref])
end
def update_caches
if default_branch?
if push_to_new_branch?
# If this is the initial push into the default branch, the file type caches
# will already be reset as a result of `Project#change_head`.
types = []
else
paths = Set.new
last_pushed_commits.each do |commit|
commit.raw_deltas.each do |diff|
paths << diff.new_path
end
end
types = Gitlab::FileDetector.types_in_paths(paths.to_a)
end
DetectRepositoryLanguagesWorker.perform_async(@project.id, current_user.id)
else
types = []
end
ProjectCacheWorker.perform_async(project.id, types, [:commit_count, :repository_size])
end
def update_signatures
commit_shas = last_pushed_commits.map(&:sha)
return if commit_shas.empty?
shas_with_cached_signatures = GpgSignature.where(commit_sha: commit_shas).pluck(:commit_sha)
commit_shas -= shas_with_cached_signatures
return if commit_shas.empty?
commit_shas = Gitlab::Git::Commit.shas_with_signatures(project.repository, commit_shas)
CreateGpgSignatureWorker.perform_async(commit_shas, project.id)
end
# Schedules processing of commit messages.
def process_commit_messages
default = default_branch?
last_pushed_commits.each do |commit|
if commit.matches_cross_reference_regex?
ProcessCommitWorker
.perform_async(project.id, current_user.id, commit.to_hash, default)
end
end
end
protected
def update_remote_mirrors
return unless project.has_remote_mirror?
project.mark_stuck_remote_mirrors_as_failed!
project.update_remote_mirrors
end
def execute_related_hooks
# Update merge requests that may be affected by this push. A new branch
# could cause the last commit of a merge request to change.
#
UpdateMergeRequestsWorker
.perform_async(project.id, current_user.id, params[:oldrev], params[:newrev], params[:ref])
EventCreateService.new.push(project, current_user, build_push_data)
Ci::CreatePipelineService.new(project, current_user, build_push_data).execute(:push)
project.execute_hooks(build_push_data.dup, :push_hooks)
project.execute_services(build_push_data.dup, :push_hooks)
if push_remove_branch?
AfterBranchDeleteService
.new(project, current_user)
.execute(branch_name)
end
end
def perform_housekeeping
housekeeping = Projects::HousekeepingService.new(project)
housekeeping.increment!
housekeeping.execute if housekeeping.needed?
rescue Projects::HousekeepingService::LeaseTaken
end
def process_default_branch
offset = [push_commits_count_for_ref - PROCESS_COMMIT_LIMIT, 0].max
@push_commits = project.repository.commits(params[:newrev], offset: offset, limit: PROCESS_COMMIT_LIMIT)
project.after_create_default_branch
end
def build_push_data
@push_data ||= Gitlab::DataBuilder::Push.build(
project,
current_user,
params[:oldrev],
params[:newrev],
params[:ref],
@push_commits,
commits_count: commits_count)
end
def push_to_existing_branch?
# Return if this is not a push to a branch (e.g. new commits)
branch_ref? && !Gitlab::Git.blank_ref?(params[:oldrev])
end
def push_to_new_branch?
strong_memoize(:push_to_new_branch) do
branch_ref? && Gitlab::Git.blank_ref?(params[:oldrev])
end
end
def push_remove_branch?
strong_memoize(:push_remove_branch) do
branch_ref? && Gitlab::Git.blank_ref?(params[:newrev])
end
end
def default_branch?
branch_ref? &&
(branch_name == project.default_branch || project.default_branch.nil?)
end
def commit_user(commit)
commit.author || current_user
end
def branch_name
strong_memoize(:branch_name) do
Gitlab::Git.ref_name(params[:ref])
end
end
def branch_ref?
strong_memoize(:branch_ref) do
Gitlab::Git.branch_ref?(params[:ref])
end
end
def commits_count
return push_commits_count_for_ref if default_branch? && push_to_new_branch?
Array(@push_commits).size
end
def push_commits_count_for_ref
strong_memoize(:push_commits_count_for_ref) do
project.repository.commit_count_for_ref(params[:ref])
end
end
def last_pushed_commits
@last_pushed_commits ||= @push_commits.last(PROCESS_COMMIT_LIMIT)
end
end
| 28.956897 | 108 | 0.72343 |
915854a9bdf4a1e28c78b6eea5b7875be67f522a | 47 | module Inspec
VERSION = "4.18.25".freeze
end
| 11.75 | 28 | 0.702128 |
26a2a34f0934d57744099d1a8975a143719b3605 | 509 | # Dump JSON Schema from YAML
#
# Run thes following command in the repo root directory:
# bundle exec ruby bin/schema-generator.rb ./data/sde/fsd/blueprints.yaml
require "json-schema-generator"
require "yaml"
y = File.open(ARGV[0], "r") { |f| YAML.load_file(f) }
File.open("./tmp/tmp.json", "w") { |f| f.write(y.to_json) }
fname = "./tmp/tmp.json"
File.open("./tmp/tmp_schema.json", "w") do |f|
d = JSON::SchemaGenerator.generate(fname, File.read(fname), { schema_version: "draft4" })
f.write(d)
end
| 29.941176 | 91 | 0.679764 |
91cad6a19249cf4b82876f79fa2f53d8cbfa6eab | 1,790 | # Copyright (c) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'rubygems'
Gem::manage_gems
require 'rake/gempackagetask'
spec = Gem::Specification.new do |s|
s.name = 'opensocial'
s.version = '0.0.4'
s.author = 'Dan Holevoet'
s.email = '[email protected]'
s.homepage = 'http://code.google.com/p/opensocial-ruby-client/'
s.platform = Gem::Platform::RUBY
s.summary = 'Provides wrapper functionality and authentication for REST ' +
'and RPC HTTP requests to OpenSocial-compliant endpoints, ' +
'along with validation of incoming signed makeRequest calls.'
s.files = FileList['lib/*.rb', 'lib/**/*.rb', 'lib/**/**/*.rb', 'tests/*.rb', 'tests/fixtures/*.json'].to_a
s.require_path = 'lib'
s.test_files = FileList['tests/test.rb']
s.has_rdoc = true
s.extra_rdoc_files = ['README', 'LICENSE', 'NOTICE']
s.rdoc_options << '--main' << 'README'
s.add_dependency('json', '>= 1.1.3')
s.add_dependency('oauth', '>= 0.3.2')
s.add_dependency('mocha', '>= 0.9.2')
s.add_dependency('rails', '>= 2.1.0')
end
Rake::GemPackageTask.new(spec) do |pkg|
pkg.need_tar = true
end
task :default => "pkg/#{spec.name}-#{spec.version}.gem" do
puts 'generated latest version'
end
task :test do
ruby 'tests/test.rb'
end | 35.098039 | 109 | 0.684916 |
e940a2f009ede541c280de1e2c83c015aa3bb47f | 303 | class StaticPagesController < ApplicationController
include HideBlockingUser
def home
if logged_in?
@micropost = current_user.microposts.build
@feed_items = current_user.feed.paginate(page: params[:page])
end
end
def help
end
def about
end
def contact
end
end
| 15.15 | 67 | 0.709571 |
61cbbf84fa58befbd53f5b009b8ae191245ff412 | 654 | RSpec.describe Directions::North do
before(:each) do
@north = Directions::North.new
end
describe "#turn_left" do
it "returns WEST" do
expect(@north.turn_left).to eq(Directions::WEST)
end
end
describe "#turn_right" do
it "returns EAST" do
expect(@north.turn_right).to eq(Directions::EAST)
end
end
describe "#move" do
context "with current position at (0, 0)" do
it "returns (0, 1)" do
expect(@north.move([0, 0])).to eq [0, 1]
end
end
end
describe "#to_s" do
it "returns N" do
expect(@north.to_s).to eq("N")
end
end
end | 21.096774 | 55 | 0.568807 |
38e4feca8a3f99d4cb0a5f947dc37d3d1a7469dc | 3,810 | =begin
#Datadog API V1 Collection
#Collection of all Datadog Public endpoints.
The version of the OpenAPI document: 1.0
Contact: [email protected]
Generated by: https://github.com/DataDog/datadog-api-client-ruby/tree/master/.generator
Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
This product includes software developed at Datadog (https://www.datadoghq.com/).
Copyright 2020-Present Datadog, Inc.
=end
require 'date'
require 'time'
module DatadogAPIClient::V1
# Response containing the number of hourly recorded custom metrics for a given organization.
class UsageTopAvgMetricsResponse
include BaseGenericModel
# Whether the object has unparsed attributes
# @!visibility private
attr_accessor :_unparsed
# The object containing document metadata.
attr_accessor :metadata
# Number of hourly recorded custom metrics for a given organization.
attr_accessor :usage
# Attribute mapping from ruby-style variable name to JSON key.
# @!visibility private
def self.attribute_map
{
:'metadata' => :'metadata',
:'usage' => :'usage'
}
end
# Returns all the JSON keys this model knows about
# @!visibility private
def self.acceptable_attributes
attribute_map.values
end
# Attribute type mapping.
# @!visibility private
def self.openapi_types
{
:'metadata' => :'UsageTopAvgMetricsMetadata',
:'usage' => :'Array<UsageTopAvgMetricsHour>'
}
end
# List of attributes with nullable: true
# @!visibility private
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param attributes [Hash] Model attributes in the form of hash
# @!visibility private
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `DatadogAPIClient::V1::UsageTopAvgMetricsResponse` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `DatadogAPIClient::V1::UsageTopAvgMetricsResponse`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'metadata')
self.metadata = attributes[:'metadata']
end
if attributes.key?(:'usage')
if (value = attributes[:'usage']).is_a?(Array)
self.usage = value
end
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
# @!visibility private
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
# @!visibility private
def valid?
true
end
# Checks equality by comparing each attribute.
# @param o [Object] Object to be compared
# @!visibility private
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
metadata == o.metadata &&
usage == o.usage
end
# @see the `==` method
# @param o [Object] Object to be compared
# @!visibility private
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
# @!visibility private
def hash
[metadata, usage].hash
end
end
end
| 28.863636 | 226 | 0.665879 |
ed3cc4f78833f2086bbd733990fb40d9ed0e54cc | 2,123 | #
# Be sure to run `pod lib lint MLNCore.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'MLN'
s.version = '0.1.0'
s.summary = 'A lib of Momo Lua Native.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
A lib of Momo Lua Native Core.
DESC
s.homepage = 'https://mln.immomo.com'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = 'MoMo'
s.source = { :git => 'https://github.com/momotech/MLN.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0'
s.libraries = 'z'
s.requires_arc = true
s.subspec 'LuaLib' do |lua|
lua.name = 'LuaLib'
lua.source_files = 'MLN-iOS/**/Classes/LuaLib/**/*.{h,m,c}'
lua.public_header_files = 'MLN-iOS/**/Classes/LuaLib/**/*.h'
end
s.subspec 'Core' do |c|
c.name = 'Core'
c.framework = 'Foundation', 'UIKit'
c.source_files = 'MLN-iOS/**/Classes/Core/**/*.{h,m,c}'
c.public_header_files = 'MLN-iOS/**/Classes/Core/**/*.h'
c.dependency 'MLN/LuaLib'
end
s.subspec 'Kit' do |k|
k.name = 'Kit'
k.framework = 'Foundation', 'UIKit', 'CoreGraphics', 'AVFoundation'
k.source_files = 'MLN-iOS/**/Classes/Kit/**/*.{h,m,c}'
k.public_header_files = 'MLN-iOS/**/Classes/Kit/**/*.h'
k.dependency 'MLN/Core'
end
end
| 36.603448 | 98 | 0.581253 |
11600a21b36d8d64d1e94e21e80cf91e9194ed80 | 8,339 | # -*- coding: binary -*-
require 'rex/socket'
require 'rex/proto/http'
require 'rex/proto/http/handler'
module Rex
module Proto
module Http
###
#
# Runtime extension of the HTTP clients that connect to the server.
#
###
module ServerClient
#
# Initialize a new request instance.
#
def init_cli(server)
self.request = Request.new
self.server = server
self.keepalive = false
end
#
# Resets the parsing state.
#
def reset_cli
self.request.reset
end
#
# Transmits a response and adds the appropriate headers.
#
def send_response(response)
# Set the connection to close or keep-alive depending on what the client
# can support.
response['Connection'] = (keepalive) ? 'Keep-Alive' : 'close'
# Add any other standard response headers.
server.add_response_headers(response)
# Send it off.
put(response.to_s)
end
#
# The current request context.
#
attr_accessor :request
#
# Boolean that indicates whether or not the connection supports keep-alive.
#
attr_accessor :keepalive
#
# A reference to the server the client is associated with.
#
attr_accessor :server
end
###
#
# Acts as an HTTP server, processing requests and dispatching them to
# registered procs. Some of this server was modeled after webrick.
#
###
class Server
include Proto
#
# A hash that associated a file extension with a mime type for use as the
# content type of responses.
#
ExtensionMimeTypes =
{
"rhtml" => "text/html",
"html" => "text/html",
"htm" => "text/htm",
"jpg" => "image/jpeg",
"jpeg" => "image/jpeg",
"jpeg" => "image/jpeg",
"gif" => "image/gif",
"png" => "image/png",
"bmp" => "image/bmp",
"txt" => "text/plain",
"css" => "text/css",
"ico" => "image/x-icon",
}
#
# The default server name that will be returned in the Server attribute of
# a response.
#
DefaultServer = "Rex"
#
# Initializes an HTTP server as listening on the provided port and
# hostname.
#
def initialize(port = 80, listen_host = '0.0.0.0', ssl = false, context = {}, comm = nil, ssl_cert = nil)
self.listen_host = listen_host
self.listen_port = port
self.ssl = ssl
self.context = context
self.comm = comm
self.ssl_cert = ssl_cert
self.listener = nil
self.resources = {}
self.server_name = DefaultServer
end
# More readable inspect that only shows the url and resources
# @return [String]
def inspect
resources_str = resources.keys.map{|r| r.inspect }.join ", "
"#<#{self.class} http#{ssl ? "s" : ""}://#{listen_host}:#{listen_port} [ #{resources_str} ]>"
end
#
# Returns the hardcore alias for the HTTP service
#
def self.hardcore_alias(*args)
"#{(args[0] || '')}#{(args[1] || '')}"
end
#
# HTTP server.
#
def alias
super || "HTTP Server"
end
#
# Listens on the defined port and host and starts monitoring for clients.
#
def start
self.listener = Rex::Socket::TcpServer.create(
'LocalHost' => self.listen_host,
'LocalPort' => self.listen_port,
'Context' => self.context,
'SSL' => self.ssl,
'SSLCert' => self.ssl_cert,
'Comm' => self.comm
)
# Register callbacks
self.listener.on_client_connect_proc = Proc.new { |cli|
on_client_connect(cli)
}
self.listener.on_client_data_proc = Proc.new { |cli|
on_client_data(cli)
}
self.listener.start
end
#
# Terminates the monitor thread and turns off the listener.
#
def stop
self.listener.stop
self.listener.close
end
#
# Waits for the HTTP service to terminate
#
def wait
self.listener.wait if self.listener
end
#
# Closes the supplied client, if valid.
#
def close_client(cli)
listener.close_client(cli)
end
#
# Mounts a directory or resource as being serviced by the supplied handler.
#
def mount(root, handler, long_call = false, *args)
resources[root] = [ handler, long_call, args ]
end
#
# Remove the mount point.
#
def unmount(root)
resources.delete(root)
end
#
# Adds a resource handler, such as one for /, which will be called whenever
# the resource is requested. The ``opts'' parameter can have any of the
# following:
#
# Proc (proc) - The procedure to call when a request comes in for this resource.
# LongCall (bool) - Hints to the server that this resource may have long
# request processing times.
#
def add_resource(name, opts)
if (resources[name])
raise RuntimeError,
"The supplied resource '#{name}' is already added.", caller
end
# If a procedure was passed, mount the resource with it.
if (opts['Proc'])
mount(name, Handler::Proc, false, opts['Proc'], opts['VirtualDirectory'])
else
raise ArgumentError, "You must specify a procedure."
end
end
#
# Removes the supplied resource handler.
#
def remove_resource(name)
self.resources.delete(name)
end
#
# Adds Server headers and stuff.
#
def add_response_headers(resp)
resp['Server'] = self.server_name if not resp['Server']
end
#
# Returns the mime type associated with the supplied file. Right now the
# set of mime types is fairly limited.
#
def mime_type(file)
type = nil
if (file =~ /\.(.+?)$/)
type = ExtensionMimeTypes[$1.downcase]
end
type || "text/plain"
end
#
# Sends a 404 error to the client for a given request.
#
def send_e404(cli, request)
resp = Response::E404.new
resp['Content-Type'] = 'text/html'
resp.body =
"<html><head>" +
"<title>404 Not Found</title>" +
"</head><body>" +
"<h1>Not found</h1>" +
"The requested URL #{html_escape(request.resource)} was not found on this server.<p><hr>" +
"</body></html>"
# Send the response to the client like what
cli.send_response(resp)
end
attr_accessor :listen_port, :listen_host, :server_name, :context, :ssl, :comm, :ssl_cert
attr_accessor :listener, :resources
protected
#
# Extends new clients with the ServerClient module and initializes them.
#
def on_client_connect(cli)
cli.extend(ServerClient)
cli.init_cli(self)
end
#
# Processes data coming in from a client.
#
def on_client_data(cli)
begin
data = cli.read(65535)
raise ::EOFError if not data
raise ::EOFError if data.empty?
case cli.request.parse(data)
when Packet::ParseCode::Completed
dispatch_request(cli, cli.request)
cli.reset_cli
when Packet::ParseCode::Partial
# Return and wait for the on_client_data handler to be called again
# The Request object tracks the state of the request for us
return
when Packet::ParseCode::Error
close_client(cli)
end
rescue EOFError
if (cli.request.completed?)
dispatch_request(cli, cli.request)
cli.reset_cli
end
close_client(cli)
end
end
#
# Dispatches the supplied request for a given connection.
#
def dispatch_request(cli, request)
# Is the client requesting keep-alive?
if ((request['Connection']) and
(request['Connection'].downcase == 'Keep-Alive'.downcase))
cli.keepalive = true
end
# Search for the resource handler for the requested URL. This is pretty
# inefficient right now, but we can spruce it up later.
p = nil
len = 0
root = nil
resources.each_pair { |k, val|
if (request.resource =~ /^#{k}/ and k.length > len)
p = val
len = k.length
root = k
end
}
if (p)
# Create an instance of the handler for this resource
handler = p[0].new(self, *p[2])
# If the handler class requires a relative resource...
if (handler.relative_resource_required?)
# Substituted the mount point root in the request to make things
# relative to the mount point.
request.relative_resource = request.resource.gsub(/^#{root}/, '')
request.relative_resource = '/' + request.relative_resource if (request.relative_resource !~ /^\//)
end
# If we found the resource handler for this resource, call its
# procedure.
if (p[1] == true)
Rex::ThreadFactory.spawn("HTTPServerRequestHandler", false) {
handler.on_request(cli, request)
}
else
handler.on_request(cli, request)
end
else
elog("Failed to find handler for resource: #{request.resource}",
LogSource)
send_e404(cli, request)
end
# If keep-alive isn't enabled for this client, close the connection
if (cli.keepalive == false)
close_client(cli)
end
end
end
end
end
end
| 21.716146 | 106 | 0.669025 |
f78bf0bebc625d22775c4ea23c411e2162c3d4f3 | 434 | require "spec_helper"
describe "a parser with two terminal rules which overlap" do
let(:parser) do
Class.new(Whittle::Parser) do
rule("def")
rule("define")
rule(:id => /[a-z_]+/)
rule(:prog) do |r|
r["def"]
r["define"]
r[:id]
end
start(:prog)
end
end
it "uses the longest match" do
parser.new.parse("define_method").should == "define_method"
end
end
| 18.083333 | 63 | 0.564516 |
186008634ec4feb232cc7522c01b0ad892c92284 | 246 | require_relative 'resource'
module Contentful
# An Assets's file info
class File
include Contentful::Resource
property :fileName, :string
property :contentType, :string
property :details
property :url, :string
end
end
| 17.571429 | 34 | 0.715447 |
0184440d87744ffe2d27ae2284f6256a21d81206 | 697 | require_relative '../../../spec_helper'
require 'rexml/document'
describe "REXML::CData#initialize" do
it "creates a new CData object" do
c = REXML::CData.new("some text")
c.should be_kind_of(REXML::CData)
c.should be_kind_of(REXML::Text)
end
it "respects whitespace if whitespace is true" do
c = REXML::CData.new("whitespace test", true)
c1 = REXML::CData.new("whitespace test", false)
c.to_s.should == "whitespace test"
c1.to_s.should == "whitespace test"
end
it "receives parent as third argument" do
e = REXML::Element.new("root")
REXML::CData.new("test", true, e)
e.to_s.should == "<root><![CDATA[test]]></root>"
end
end
| 27.88 | 55 | 0.645624 |
1dfb7bc86de0e7c6e38122e0a5e1c7412c616653 | 1,630 | # frozen_string_literal: true
class Fisk
module Instructions
# Instruction SUBSS: Subtract Scalar Single-Precision Floating-Point Values
SUBSS = Instruction.new("SUBSS", [
# subss: xmm, xmm
Form.new([
OPERAND_TYPES[23],
OPERAND_TYPES[24],
].freeze, [
Class.new(Fisk::Encoding) {
def encode buffer, operands
add_prefix(buffer, operands, 0xF3, true) +
add_rex(buffer, operands,
false,
0,
operands[0].rex_value,
0,
operands[1].rex_value) +
add_opcode(buffer, 0x0F, 0) +
add_opcode(buffer, 0x5C, 0) +
add_modrm(buffer,
3,
operands[0].op_value,
operands[1].op_value, operands) +
0
end
}.new.freeze,
].freeze).freeze,
# subss: xmm, m32
Form.new([
OPERAND_TYPES[23],
OPERAND_TYPES[14],
].freeze, [
Class.new(Fisk::Encoding) {
def encode buffer, operands
add_prefix(buffer, operands, 0xF3, true) +
add_rex(buffer, operands,
false,
0,
operands[0].rex_value,
operands[1].rex_value,
operands[1].rex_value) +
add_opcode(buffer, 0x0F, 0) +
add_opcode(buffer, 0x5C, 0) +
add_modrm(buffer,
0,
operands[0].op_value,
operands[1].op_value, operands) +
0
end
}.new.freeze,
].freeze).freeze,
].freeze).freeze
end
end
| 28.103448 | 79 | 0.497546 |
333d94081ec0544beccd1c3c6d6faf187a4bec34 | 570 | module ReverseMarkdown
module Converters
class Del < Base
def convert(node, state = {})
content = treat_children(node, state.merge(already_crossed_out: true))
if disabled? || content.strip.empty? || state[:already_crossed_out]
content
else
"~~#{content}~~"
end
end
def enabled?
ReverseMarkdown.config.github_flavored
end
def disabled?
!enabled?
end
end
register :strike, Del.new
register :s, Del.new
register :del, Del.new
end
end
| 21.111111 | 78 | 0.582456 |
1c874766bf1256d4167e00356eba70118911e914 | 1,390 | $: << File.join(File.dirname(__FILE__),'lib')
require 'calculations'
include Calculations
# MyWorker defines the behaviour of workers.
# Here is where the real processing takes place
class MyWorker < ScbiMapreduce::Worker
# starting_worker method is called one time at initialization
# and allows you to initialize your variables
def starting_worker
# You can use worker logs at any time in this way:
# $WORKER_LOG.info "Starting a worker"
end
# receive_initial_config is called only once just after
# the first connection, when initial parameters are
# received from manager
def receive_initial_config(parameters)
# Reads the parameters
# You can use worker logs at any time in this way:
# $WORKER_LOG.info "Params received"
# save received parameters, if any
# @params = parameters
end
# process_object method is called for each received object.
# Be aware that objs is always an array, and you must iterate
# over it if you need to process it independently
#
# The value returned here will be received by the work_received
# method at your worker_manager subclass.
def process_object(objs)
# iterate over all objects received
# objs.each do |obj|
# convert to uppercase
do_dummy_calculations
# end
# return objs back to manager
return objs
end
def closing_worker
end
end
| 24.385965 | 65 | 0.72446 |
e89af1cd7cb701debef8bb906162eaaebbe20a19 | 1,130 | module Vitals::Formats
class HostLastFormat
attr_accessor :environment
attr_accessor :host
attr_accessor :facility
def initialize(environment:'development', facility:'default', host:'localhost')
@environment = environment
@facility = facility
@host = host
@host = Vitals::Utils.normalize_metric(host).freeze if @host
@prefix = [environment, facility].compact.map{|m| Vitals::Utils.normalize_metric(m) }
.join(Vitals::Utils::SEPARATOR).freeze
@prefix_with_host = [environment, facility, @host].compact.map{|m| Vitals::Utils.normalize_metric(m) }
.join(Vitals::Utils::SEPARATOR).freeze
end
def format(m)
return @prefix_with_host if (m.nil? || m.empty?)
# TODO optimize by building a renderer function (inlining this) in the initializer.
# see https://github.com/evanphx/benchmark-ips/blob/master/lib/benchmark/ips/job/entry.rb#L63
[@prefix, Vitals::Utils.normalize_metric(m), @host].reject{|s| s.nil? || s.empty? }.join(Vitals::Utils::SEPARATOR)
end
end
end
| 41.851852 | 120 | 0.649558 |
e28b237f518f0ff7fc4844600750f22fa87bd159 | 115 | class AddTypeToImages < ActiveRecord::Migration[4.2]
def change
add_column :images, :type, :string
end
end
| 19.166667 | 52 | 0.730435 |
3309caa3907ec2ce37203895a77ec7aed34bf6cc | 126 | require "fullcalendar/rails/version"
module Fullcalendar
module Rails
class Engine < ::Rails::Engine
end
end
end
| 14 | 36 | 0.722222 |
d5082b413247bdf86dd666deea39e38653e88b08 | 9,689 | class WorkPaper < ApplicationRecord
include Auditable
include ParameterSelector
include Comparable
include WorkPapers::LocalFiles
include WorkPapers::Review
# Named scopes
scope :list, -> { where(organization_id: Current.organization&.id) }
scope :sorted_by_code, -> { order(code: :asc) }
scope :with_prefix, ->(prefix) {
where("#{quoted_table_name}.#{qcn 'code'} LIKE ?", "#{prefix}%").sorted_by_code
}
# Restricciones de los atributos
attr_accessor :code_prefix
attr_readonly :organization_id
# Callbacks
before_save :check_for_modifications
after_save :create_cover_and_zip
after_destroy :destroy_file_model # TODO: delete when Rails fix gets in stable
# Restricciones
validates :organization_id, :name, :code, :presence => true
validates :number_of_pages, :numericality =>
{:only_integer => true, :less_than => 100000, :greater_than => 0},
:allow_nil => true, :allow_blank => true
validates :organization_id, :numericality => {:only_integer => true},
:allow_nil => true, :allow_blank => true
validates :name, :code, :length => {:maximum => 255}, :allow_nil => true,
:allow_blank => true
validates :code, :uniqueness => { :scope => :owner_id }, :on => :create,
:allow_nil => true, :allow_blank => true
validates :name, :code, :description, :pdf_encoding => true
validates_each :code, :on => :create do |record, attr, value|
if record.check_code_prefix && !record.marked_for_destruction?
raise 'No code_prefix is set!' unless record.code_prefix
regex = /^(#{Regexp.escape(record.code_prefix)})\s\d+$/
record.errors.add attr, :invalid unless value =~ regex
# TODO: Eliminar, duplicado para validar los objetos en memoria
codes = record.owner.work_papers.reject(
&:marked_for_destruction?).map(&:code)
if codes.select { |c| c.strip == value.strip }.size > 1
record.errors.add attr, :taken
end
end
end
# Relaciones
belongs_to :organization
belongs_to :file_model, :optional => true
belongs_to :owner, :polymorphic => true, :touch => true, :optional => true
accepts_nested_attributes_for :file_model, :allow_destroy => true,
reject_if: ->(attrs) { ['file', 'file_cache'].all? { |a| attrs[a].blank? } }
def initialize(attributes = nil)
super(attributes)
self.organization_id = Current.organization&.id
end
def inspect
number_of_pages.present? ? "#{code} - #{name} (#{pages_to_s})" : "#{code} - #{name}"
end
def <=>(other)
if other.kind_of?(WorkPaper) && self.owner_id == other.owner_id && self.owner_type == other.owner_type
self.code <=> other.code
else
-1
end
end
def ==(other)
other.kind_of?(WorkPaper) && other.id &&
(self.id == other.id || (self <=> other) == 0)
end
def check_code_prefix
unless @__ccp_first_access
@check_code_prefix = true
@__ccp_first_access = true
end
@check_code_prefix
end
def check_code_prefix=(check_code_prefix)
@__ccp_first_access = true
@check_code_prefix = check_code_prefix
end
def pages_to_s
I18n.t('work_paper.number_of_pages', :count => self.number_of_pages)
end
def check_for_modifications
@zip_must_be_created = self.file_model.try(:file?) ||
self.file_model.try(:changed?)
@cover_must_be_created = self.changed?
@previous_code = self.code_was if self.code_changed?
true
end
def create_cover_and_zip
self.file_model.try(:file?) &&
(@zip_must_be_created || @cover_must_be_created) &&
create_zip
true
end
def create_pdf_cover(filename = nil, review = nil)
pdf = Prawn::Document.create_generic_pdf(:portrait, footer: false)
review ||= owner.review
pdf.add_review_header review.try(:organization),
review.try(:identification), review.try(:plan_item).try(:project)
pdf.move_down PDF_FONT_SIZE * 2
pdf.add_title WorkPaper.model_name.human, PDF_FONT_SIZE * 2
pdf.move_down PDF_FONT_SIZE * 4
if owner.respond_to?(:pdf_cover_items)
owner.pdf_cover_items.each do |label, text|
pdf.move_down PDF_FONT_SIZE
pdf.add_description_item label, text, 0, false
end
end
unless self.name.blank?
pdf.move_down PDF_FONT_SIZE
pdf.add_description_item WorkPaper.human_attribute_name(:name),
self.name, 0, false
end
unless self.description.blank?
pdf.move_down PDF_FONT_SIZE
pdf.add_description_item WorkPaper.human_attribute_name(:description),
self.description, 0, false
end
unless self.code.blank?
pdf.move_down PDF_FONT_SIZE
pdf.add_description_item WorkPaper.human_attribute_name(:code),
self.code, 0, false
end
unless self.number_of_pages.blank?
pdf.move_down PDF_FONT_SIZE
pdf.add_description_item WorkPaper.human_attribute_name(
:number_of_pages), self.number_of_pages.to_s, 0, false
end
pdf.save_as self.absolute_cover_path(filename)
end
def pdf_cover_name(filename = nil, short = false)
code = sanitized_code
short_code = sanitized_code.sub(/(\w+_)\d(\d{2})$/, '\1\2')
prev_code = @previous_code.sanitized_for_filename if @previous_code
if self.file_model.try(:file?)
filename ||= self.file_model.identifier.sanitized_for_filename
filename = filename.sanitized_for_filename.
sub(/^(#{Regexp.quote(code)})?\-?(zip-)*/i, '').
sub(/^(#{Regexp.quote(short_code)})?\-?(zip-)*/i, '')
filename = filename.sub("#{prev_code}-", '') if prev_code
end
I18n.t 'work_paper.cover_name', :prefix => "#{short ? short_code : code}-",
:filename => File.basename(filename, File.extname(filename))
end
def absolute_cover_path(filename = nil)
if self.file_model.try(:file?)
File.join File.dirname(self.file_model.file.path), self.pdf_cover_name
else
"#{TEMP_PATH}#{self.pdf_cover_name(filename || "#{object_id.abs}.pdf")}"
end
end
def filename_with_prefix
filename = self.file_model.identifier.sub /^(zip-)*/i, ''
filename = filename.sanitized_for_filename
code_suffix = File.extname(filename) == '.zip' ? '-zip' : ''
code = sanitized_code
short_code = sanitized_code.sub(/(\w+_)\d(\d{2})$/, '\1\2')
filename.starts_with?(code, short_code) ?
filename : "#{code}#{code_suffix}-#{filename}"
end
def create_zip
self.unzip_if_necesary
if @previous_code
prev_code = sanitized_previous_code
end
original_filename = self.file_model.file.path
directory = File.dirname original_filename
code = sanitized_code
short_code = sanitized_code.sub(/(\w+_)\d(\d{2})$/, '\1\2')
filename = File.basename original_filename, File.extname(original_filename)
filename = filename.sanitized_for_filename.
sub(/^(#{Regexp.quote(code)})?\-?(zip-)*/i, '').
sub(/^(#{Regexp.quote(short_code)})?\-?(zip-)*/i, '')
filename = filename.sub("#{prev_code}-", '') if prev_code
zip_filename = File.join directory, "#{code}-#{filename}.zip"
pdf_filename = self.absolute_cover_path
self.create_pdf_cover
if File.file?(original_filename) && File.file?(pdf_filename)
FileUtils.rm zip_filename if File.exists?(zip_filename)
Zip::File.open(zip_filename, Zip::File::CREATE) do |zipfile|
zipfile.add(self.filename_with_prefix, original_filename) { true }
zipfile.add(File.basename(pdf_filename), pdf_filename) { true }
end
FileUtils.rm pdf_filename if File.exists?(pdf_filename)
FileUtils.rm original_filename if File.exists?(original_filename)
self.file_model.file = File.open(zip_filename)
self.file_model.save!
end
FileUtils.chmod 0640, zip_filename if File.exist?(zip_filename)
end
def unzip_if_necesary
file_name = self.file_model.try(:identifier) || ''
code = sanitized_code
if File.extname(file_name) == '.zip' && start_with_code?(file_name)
zip_path = self.file_model.file.path
base_dir = File.dirname self.file_model.file.path
Zip::File.foreach(zip_path) do |entry|
if entry.file?
filename = File.join base_dir, entry.name
filename = filename.sub(sanitized_previous_code, code) if @previous_code
if filename != zip_path && !File.exist?(filename)
entry.extract(filename)
end
if File.basename(filename) != pdf_cover_name &&
File.basename(filename) != pdf_cover_name(nil, true)
self.file_model.file = File.open(filename)
end
end
end
self.file_model.save! if self.file_model.changed?
# Pregunta para evitar eliminar el archivo si es un zip con el mismo
# nombre
unless File.basename(zip_path) == self.file_model.identifier
FileUtils.rm zip_path if File.exists? zip_path
end
end
end
def sanitized_previous_code
@previous_code.sanitized_for_filename
end
def start_with_code? file_name
code = sanitized_code
short_code = sanitized_code.sub(/(\w+_)\d(\d{2})$/, '\1\2')
result = file_name.start_with?(code, short_code) &&
!file_name.start_with?("#{code}-zip", "#{short_code}-zip")
if @previous_code
prev_code = sanitized_previous_code
prev_short_code = prev_code.sub(/(\w+_)\d(\d{2})$/, '\1\2')
result = result || (file_name.start_with?(prev_code, prev_short_code) &&
!file_name.start_with?("#{prev_code}-zip", "#{prev_short_code}-zip"))
end
result
end
def sanitized_code
self.code.sanitized_for_filename
end
private
def destroy_file_model
file_model.try(:destroy!)
end
end
| 30.955272 | 106 | 0.672825 |
085866deb8d05c688a341ac0d5a7e86f0d73dc51 | 933 | module VagrantPlugins
module GuestLinux
module Cap
class ShellExpandGuestPath
def self.shell_expand_guest_path(machine, path)
real_path = nil
path = path.gsub(/ /, '\ ')
machine.communicate.execute("echo; printf #{path}") do |type, data|
if type == :stdout
real_path ||= ""
real_path += data
end
end
if real_path
# The last line is the path we care about
real_path = real_path.split("\n").last.chomp
end
if !real_path
# If no real guest path was detected, this is really strange
# and we raise an exception because this is a bug.
raise Vagrant::Errors::ShellExpandFailed
end
# Chomp the string so that any trailing newlines are killed
return real_path.chomp
end
end
end
end
end
| 28.272727 | 77 | 0.55627 |
01b178f7ef13a2fb7f2b41ffd52f82f61fd37887 | 621 | require 'umu/common'
module Umu
module ConcreteSyntax
module Module
module Pattern
class Abstract < Abstraction::Model
def desugar_value(expr, env)
E::Tracer.trace(
env.pref,
env.trace_stack.count,
'Desu(Val)',
self.class,
self.pos,
self.to_s
) { |event|
__desugar_value__ expr, env, event
}
end
def exported_vars
raise X::SubclassResponsibility
end
private
def __desugar_value__(expr, env, event)
raise X::SubclassResponsibility
end
end
end # Umu::ConcreteSyntax::Module::Pattern
end # Umu::ConcreteSyntax::Module
end # Umu::ConcreteSyntax
end # Umu
| 13.5 | 42 | 0.697262 |
ed94c52228e7b334c7d4cb23f8f7cec63688461d | 29 | module UnauthRsvpsHelper
end
| 9.666667 | 24 | 0.896552 |
1d770060a7779dddb20149ead94a3c489fdde45c | 2,663 | # Effective Engine concern
module EffectiveGem
extend ActiveSupport::Concern
EXCLUDED_GETTERS = [
:config, :setup, :send_email, :parent_mailer_class,
:deliver_method, :mailer_layout, :mailer_sender, :mailer_admin, :mailer_subject
]
included do
raise("expected self.config_keys method") unless respond_to?(:config_keys)
# Define getters
(config_keys - EXCLUDED_GETTERS).each do |key|
self.singleton_class.define_method(key) { config()[key] }
end
# Define setters
config_keys.each do |key|
self.singleton_class.define_method("#{key}=") { |value| config()[key] = value }
end
end
module ClassMethods
def config(namespace = nil)
namespace ||= Tenant.current if defined?(Tenant)
@config.dig(namespace) || @config.dig(:effective)
end
def setup(namespace = nil, &block)
@config ||= ActiveSupport::OrderedOptions.new
namespace ||= Tenant.current if defined?(Tenant)
namespace ||= :effective
@config[namespace] ||= ActiveSupport::OrderedOptions.new
yield(config(namespace))
if(unsupported = (config(namespace).keys - config_keys)).present?
if unsupported.include?(:authorization_method)
raise("config.authorization_method has been removed. This gem will call EffectiveResources.authorization_method instead. Please double check the config.authorization_method setting in config/initializers/effective_resources.rb and remove it from this file.")
end
raise("unsupported config keys: #{unsupported}\n supported keys: #{config_keys}")
end
true
end
# Mailer Settings
# These methods are intended to flow through to the default EffectiveResources settings
def parent_mailer_class
config[:parent_mailer].presence&.constantize || EffectiveResources.parent_mailer_class
end
def deliver_method
config[:deliver_method].presence || EffectiveResources.deliver_method
end
def mailer_layout
config[:mailer_layout].presence || EffectiveResources.mailer_layout
end
def mailer_sender
config[:mailer_sender].presence || EffectiveResources.mailer_sender
end
def mailer_admin
config[:mailer_admin].presence || EffectiveResources.mailer_admin
end
def mailer_subject
config[:mailer_subject].presence || EffectiveResources.mailer_subject
end
def send_email(email, *args)
raise('gem does not respond to mailer_class') unless respond_to?(:mailer_class)
raise('expected args to be an Array') unless args.kind_of?(Array)
mailer_class.send(email, *args).send(deliver_method)
end
end
end
| 29.921348 | 268 | 0.711603 |
abaced02b17a195bfcfa9160f0b9648e131aa2c4 | 72 | class StaticPagesController < ApplicationController
def home
end
end
| 12 | 51 | 0.833333 |
1d26b0acefd277f716dbed96513314fd5060c8d8 | 2,353 | require 'fog/aws/elbv2/default_tg_attributes'
Shindo.tests('AWS::elbv2 | target_group', ['aws', 'elbv2', 'models']) do
Fog::Compute::AWS::Mock.reset if Fog.mocking?
ELBV2 = Fog::AWS[:elbv2]
@server1 = Fog::Compute[:aws].servers.create
@server1.wait_for { ready? }
@server2 = Fog::Compute[:aws].servers.create
@server2.wait_for { ready? }
tests('success') do
@target_group = ELBV2.target_groups.create(:name => "test-tg-1")
tests('defaults').returns(Fog::AWS::ELBV2::Mock.default_tg_attributes) do
@target_group.tg_attributes
end
tests('#register_targets') do
@target_group.register_targets(@server1.id)
tests('target health') do
tests('#healthy?').returns(true) { @target_group.target_health.first.healthy? }
end
@target_group.register_targets(@server2.id)
tests('target health second') do
tests('#target_health').returns(1) { @target_group.target_health([@server2.id]).size }
end
end
tests('#deregister_targets') do
tests('number of targets before destroy').returns(2) { @target_group.target_health.size }
@target_group.deregister_targets(@server1.id)
tests('number of targets').returns(1) { @target_group.target_health.size }
@target_group.deregister_targets(@server2.id)
tests('number of targets after destroy').returns(0) { @target_group.target_health.size }
end
tests('stickiness') do
tests('#stickiness_enabled?').returns(false) { @target_group.stickiness_enabled? }
tests('#stickiness_type').returns('lb_cookie') { @target_group.stickiness_type }
tests('#stickiness_duration').returns(3600*24) { @target_group.stickiness_duration }
tests('#deregistration_delay_timeout').returns(300) { @target_group.deregistration_delay_timeout }
tests('#enable_stickiness').returns(true) do
@target_group.enable_stickiness
@target_group.stickiness_enabled?
end
tests('#deregistration_delay_timeout=').returns(600) do
@target_group.deregistration_delay_timeout = 600
@target_group.deregistration_delay_timeout
end
end
tests('modify').returns('200-299') do
@target_group.update(:matcher => '200-299')
@target_group.reload.matcher
end
@target_group.destroy
end
[@server1, @server2].map(&:destroy)
end
| 33.614286 | 104 | 0.691033 |
792d50a193d10a7093c30a226a6a4b4a44b688eb | 3,063 | require 'arduino_firmata'
require 'active_support/core_ext/hash/except'
class HardwareConfig
def initialize()
@config = Hardware.first_or_create
@led = {
normal: @config.normal_mode_led,
reset: @config.reset_mode_led,
a: @config.a_led_pin,
x: @config.x_led_pin,
up: @config.a_led_pin,
right: @config.x_led_pin,
home: @config.home_led_pin,
shiny: @config.shiny_detected_led,
not_shiny: @config.not_shiny_detected_led
}
@servo =
{
a: {
pin: @config.a_pin,
standby_angle: @config.a_standby_angle,
press_angle: @config.a_press_angle,
up_angle: @config.a_up_angle
},
x: {
pin: @config.x_pin,
standby_angle: @config.x_standby_angle,
press_angle: @config.x_press_angle,
up_angle: @config.x_up_angle
},
home: {
pin: @config.home_pin,
standby_angle: @config.home_standby_angle,
press_angle: @config.home_press_angle,
up_angle: @config.home_up_angle
},
up: {
pin: @config.up_pin,
standby_angle: @config.up_standby_angle,
press_angle: @config.up_press_angle,
up_angle: @config.up_up_angle
},
right: {
pin: @config.right_pin,
standby_angle: @config.right_standby_angle,
press_angle: @config.right_press_angle,
up_angle: @config.right_up_angle
},
}
begin
Rails.logger.info "Se connecte au Arduino"
@arduino = ArduinoFirmata.connect
Rails.logger.info "Arduino connectรฉ"
rescue ArduinoFirmata::Error
Rails.logger.info "Error: the arduino board was not found"
end
end
def press(button, delay)
raise_motors if delay < 0
ActionCable.server.broadcast("trash", {button => "pressed"})
light(button, true)
motor_angle(button, :press_angle)
sleep 0.4
motor_angle(button, :standby_angle)
light(button, false)
ActionCable.server.broadcast("trash", {button => "released"})
sleep delay / 1000.0
end
def motor_angle(motor, angle)
@arduino.servo_write @servo[motor][:pin], angle.is_a?(Symbol) ? @servo[motor][angle] : angle
end
def light(led, value)
@arduino.digital_write @led[led], value
end
def normal_mode
light(:normal, true)
yield
ensure
light(:normal, false)
end
def reseting
light(:reset, true)
yield
ensure
light(:reset, false)
end
def raise_motors
@servo.each do |button, hash|
light(button, true)
motor_angle(button, :up_angle)
sleep 0.3
light(button, false)
end
@led.except(:shiny).keys.each do |pin|
light pin, false
end
end
def lower_motors
@servo.each do |button, hash|
light(button, true)
motor_angle(button, :standby_angle)
sleep 0.3
light(button, false)
end
end
def reset_lights
@led.each do |led, hash|
light(led, false)
end
end
end
| 24.701613 | 96 | 0.612798 |
1c11dd40f2cfe9605769ad4b09bdee44cf2d35d2 | 382 | require 'puppet/provider/confine'
class Puppet::Provider::Confine::False < Puppet::Provider::Confine
def self.summarize(confines)
confines.inject(0) { |count, confine| count + confine.summary }
end
def pass?(value)
! value
end
def message(value)
"true value when expecting false"
end
def summary
result.find_all { |v| v == false }.length
end
end
| 19.1 | 67 | 0.683246 |
e8e53e3b43daaeddeedd7c41fe5a83f18240f975 | 81 | require 'omniauth-http-header/version'
require 'omniauth/strategies/http_header'
| 27 | 41 | 0.839506 |
7af32b46fdc5888ea8c0be8cf17bfb4649d34450 | 1,601 | module Fog
module Rackspace
class Monitoring
class Real
def get_system_info(agent_id)
request(
:expects => [200, 203],
:method => 'GET',
:path => "agents/#{agent_id}/host_info/system"
)
end
end
class Mock
def get_system_info(agent_id)
if agent_id == -1
raise Fog::Rackspace::Monitoring::BadRequest
end
response = Excon::Response.new
response.status = 200
response.body = {
"info" => [
{
"name" => "Linux",
"arch" => "x86_64",
"version" => "2.6.18-308.el5xen",
"vendor" => "CentOS",
"vendor_version" => "5.10"
}
]
}
response.headers = {
"Date" => Time.now.utc.to_s,
"Content-Type" => "application/json; charset=UTF-8",
"X-RateLimit-Limit" => "50000",
"X-RateLimit-Remaining" => "49627",
"X-RateLimit-Window" => "24 hours",
"X-RateLimit-Type" => "global",
"X-Response-Id" => "j23jlk234jl2j34j",
"X-LB" => "dfw1-maas-prod-api0",
"Vary" => "Accept-Encoding",
"Transfer-Encoding" => "chunked"
}
response.remote_ip = Fog::Mock.random_ip({:version => :v4})
response
end
end
end
end
end
| 30.788462 | 73 | 0.413492 |
b92460aa0e158fa145845684e672d34e7dd175ed | 4,090 | require 'spec_helper'
describe Admin::CoursesController do
before { sign_in_teacher }
let(:valid_attributes) { build(:course).attributes }
let(:unit) { create :unit }
describe "GET show" do
let(:course) { create :course, unit: unit }
it "assigns the requested course as @course" do
get :show, unit_id: unit.to_param, id: course.to_param
expect(assigns(:course)).to eq(course)
end
end
describe "GET new" do
it "assigns a new course as @course" do
get :new, unit_id: unit.to_param
expect(assigns(:course)).to be_a_new(Course)
end
end
describe "GET edit" do
let!(:course) { create(:course, unit: unit) }
it "assigns the requested course as @course" do
get :edit, unit_id: unit.to_param, id: course.to_param
expect(assigns(:course)).to eq(course)
end
end
describe "POST create" do
describe "with valid params" do
it "creates a new Course" do
expect {
post :create, unit_id: unit.to_param, course: valid_attributes
}.to change(Course, :count).by(1)
end
it "assigns a newly created course as @course" do
post :create, unit_id: unit.to_param, course: valid_attributes
expect(assigns(:course)).to be_a(Course)
expect(assigns(:course)).to be_persisted
end
it "redirects to the created course" do
post :create, unit_id: unit.to_param, course: valid_attributes
expect(response).to redirect_to(admin_unit_course_subjects_url(unit, Course.last))
end
end
describe "with invalid params" do
it "assigns a newly created but unsaved course as @course" do
allow_any_instance_of(Course).to receive(:save).and_return(false)
post :create, unit_id: unit.to_param, course: { "name" => "invalid value" }
expect(assigns(:course)).to be_a_new(Course)
end
it "re-renders the 'new' template" do
allow_any_instance_of(Course).to receive(:save).and_return(false)
post :create, unit_id: unit.to_param, course: { "name" => "invalid value" }
expect(response).to render_template("new")
end
end
end
describe "PUT update" do
describe "with valid params" do
let!(:course) { create(:course, unit: unit) }
it "updates the requested course" do
expect_any_instance_of(Course).to receive(:update).with({ "name" => "Rails for Designers" })
put :update, unit_id: unit.to_param, id: course.to_param, course: { "name" => "Rails for Designers" }
end
it "assigns the requested course as @course" do
put :update, unit_id: unit.to_param, id: course.to_param, course: valid_attributes
expect(assigns(:course)).to eq(course)
end
it "redirects to the course" do
put :update, unit_id: unit.to_param, id: course.to_param, course: valid_attributes
expect(response).to redirect_to(admin_unit_course_subjects_url(unit, course))
end
end
describe "with invalid params" do
let!(:course) { create(:course, unit: unit) }
it "assigns the course as @course" do
allow_any_instance_of(Course).to receive(:save).and_return(false)
put :update, unit_id: unit.to_param, id: course.to_param, course: { "name" => "invalid value" }
expect(assigns(:course)).to eq(course)
end
it "re-renders the 'edit' template" do
allow_any_instance_of(Course).to receive(:save).and_return(false)
put :update, unit_id: unit.to_param, id: course.to_param, course: { "name" => "invalid value" }
expect(response).to render_template("edit")
end
end
end
describe "DELETE destroy" do
let!(:course) { create(:course, unit: unit) }
it "destroys the requested course" do
expect {
delete :destroy, unit_id: unit.to_param, id: course.to_param
}.to change(Course, :count).by(-1)
end
it "redirects to the courses list" do
delete :destroy, unit_id: unit.to_param, id: course.to_param
expect(response).to redirect_to(admin_unit_url(unit))
end
end
end
| 33.801653 | 109 | 0.655501 |
f8346c148524362c0cc883e0ef2083f8fde9fbb5 | 6,355 | require_relative '../test_helper'
describe Game do
describe "#all" do
# describe "if there are no games in the database" do
# it "should return an empty array" do
# assert_equal [], Game.all
# end
# end
describe "if there are games" do
before do
create_game("Bob", "3", "2", "1", "2")
create_game("Sally", "3", "2", "1", "2")
create_game("Amanda", "3", "2", "1", "2")
end
# it "should return an array" do
# # You don't need to be pedantic like this.
# # This is just an example to remind you that you can use multiple "its"
# assert_equal Array, Game.all.class
# end
it "should return the games in alphabetical order" do
expected = ["Amanda", "Bob", "Sally"]
actual = Game.all.map{ |game| game.name }
assert_equal expected, actual
end
# it "populates the returned games' ids" do
# expected_ids = Database.execute("SELECT id FROM games order by name ASC").map{ |row| row['id'] }
# actual_ids = Game.all.map{ |game| game.id }
# assert_equal expected_ids, actual_ids
end
end
end
# describe "#count" do
# describe "if there are no games in the database" do
# it "should return 0" do
# assert_equal 0, Game.count
# end
# end
# describe "if there are games 2" do
# before do
# create_game("Bob", "3", "2", "1", "2")
# create_game("Sally", "3", "2", "1", "2")
# create_game("Amanda", "3", "2", "1", "2")
# end
# it "should return the correct count" do
# assert_equal 3, Game.count
# end
# end
# end
# describe "#find" do
# let(:game){ Game.new("Make pancakes", "1", "2", "3", "1") }
# before do
# game.save
# end
# describe "if there isn't a matching game in the database" do
# it "should return nil" do
# assert_equal nil, Game.find(14)
# end
# end
# describe "if there is a matching game in the database" do
# it "should return the game, populated with id and name" do
# actual = Game.find(game.id)
# assert_equal game.id, actual.id
# assert_equal game.name, actual.name
# end
# end
# end
# describe "equality" do
# describe "when the game ids are the same" do
# it "is true" do
# game1 = Game.new("foo", "3", "2", "1", "2")
# game1.save
# game2 = Game.all.first
# assert_equal game1, game2
# end
# end
# describe "when the game ids are not the same" do
# it "is true" do
# game1 = Game.new("foo", "3", "2", "1", "2")
# game1.save
# game2 = Game.new("foo", "3", "2", "1", "2")
# game2.save
# assert game1 != game2
# end
# end
# end
describe ".initialize" do
it "sets the name attribute" do
game = Game.new("foo", "3", "2", "1", "2")
assert_equal "foo", game.name
end
end
# describe ".save" do
# describe "if the model is valid" do
# let(:game){ Game.new("roast a pig", "3", "2", "1", "2") }
# it "should return true" do
# assert game.save
# end
# it "should save the model to the database" do
# game.save
# assert_equal 1, Game.count
# last_row = Database.execute("SELECT * FROM games")[0]
# database_name = last_row['name']
# assert_equal "roast a pig", database_name
# end
# it "should populate the model with id from the database" do
# game.save
# last_row = Database.execute("SELECT * FROM games")[0]
# database_id = last_row['id']
# assert_equal database_id, game.id
# end
# end
# describe "if the model is invalid" do
# let(:game){ Game.new("") }
# it "should return false" do
# refute game.save
# end
# it "should not save the model to the database" do
# game.save
# assert_equal 0, Game.count
# end
# it "should populate the error messages" do # I have some qualms.
# game.save
# assert_equal "\"\" is not a valid game name.", game.errors
# end
# end
# end
describe ".valid?" do
describe "with valid data" do
let(:game){ Game.new("eat corn on the cob") }
it "returns true" do
assert game.valid?
end
it "should set errors to nil" do
game.valid?
assert game.errors.nil?
end
end
describe "with no name" do
let(:game){ Game.new(nil) }
it "returns false" do
refute game.valid?
end
it "sets the error message" do
game.valid?
assert_equal "\"\" is not a valid game name.", game.errors
end
end
describe "with empty name" do
let(:game){ Game.new("") }
it "returns false" do
refute game.valid?
end
it "sets the error message" do
game.valid?
assert_equal "\"\" is not a valid game name.", game.errors
end
end
describe "with a name with no letter characters" do
let(:game){ Game.new("777") }
it "returns false" do
refute game.valid?
end
it "sets the error message" do
game.valid?
assert_equal "\"777\" is not a valid game name.", game.errors
end
end
describe "with a previously invalid name" do
let(:game){ Game.new("666") }
before do
refute game.valid?
game.name = "Eat a pop tart"
assert_equal "Eat a pop tart", game.name
end
it "should return true" do
assert game.valid?
end
it "should not have an error message" do
game.valid?
assert_nil game.errors
end
end
describe ".update" do
describe "edit previously entered game" do
let(:game_name){ "Eat a pop tart" }
let(:new_game_name){ "Eat a toaster strudel" }
it "should update game name but not id" do
skip
game = Game.new(game_name)
game.save
assert_equal 1, Game.count
game.update(game_name, new_game_name)
last_row = Database.execute("SELECT * FROM games WHERE name LIKE ?", game_name)[0]
assert_equal 1, Game.count
assert_equal new_game_name, last_row['name']
end
end
end
end
# end | 30.552885 | 106 | 0.555625 |
f77addb735a46a4496e1514be35d37a8bcf7c2bd | 5,010 | require 'rails_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator. If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails. There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec. Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.
#
# Also compared to earlier versions of this generator, there are no longer any
# expectations of assigns and templates rendered. These features have been
# removed from Rails core in Rails 5, but can be added back in via the
# `rails-controller-testing` gem.
RSpec.describe LevelsController, type: :controller do
# This should return the minimal set of attributes required to create a valid
# Level. As you add validations to Level, be sure to
# adjust the attributes here as well.
let(:valid_attributes) {
skip("Add a hash of attributes valid for your model")
}
let(:invalid_attributes) {
skip("Add a hash of attributes invalid for your model")
}
# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# LevelsController. Be sure to keep this updated too.
let(:valid_session) { {} }
describe "GET #index" do
it "returns a success response" do
level = Level.create! valid_attributes
get :index, params: {}, session: valid_session
expect(response).to be_success
end
end
describe "GET #show" do
it "returns a success response" do
level = Level.create! valid_attributes
get :show, params: {id: level.to_param}, session: valid_session
expect(response).to be_success
end
end
describe "GET #new" do
it "returns a success response" do
get :new, params: {}, session: valid_session
expect(response).to be_success
end
end
describe "GET #edit" do
it "returns a success response" do
level = Level.create! valid_attributes
get :edit, params: {id: level.to_param}, session: valid_session
expect(response).to be_success
end
end
describe "POST #create" do
context "with valid params" do
it "creates a new Level" do
expect {
post :create, params: {level: valid_attributes}, session: valid_session
}.to change(Level, :count).by(1)
end
it "redirects to the created level" do
post :create, params: {level: valid_attributes}, session: valid_session
expect(response).to redirect_to(Level.last)
end
end
context "with invalid params" do
it "returns a success response (i.e. to display the 'new' template)" do
post :create, params: {level: invalid_attributes}, session: valid_session
expect(response).to be_success
end
end
end
describe "PUT #update" do
context "with valid params" do
let(:new_attributes) {
skip("Add a hash of attributes valid for your model")
}
it "updates the requested level" do
level = Level.create! valid_attributes
put :update, params: {id: level.to_param, level: new_attributes}, session: valid_session
level.reload
skip("Add assertions for updated state")
end
it "redirects to the level" do
level = Level.create! valid_attributes
put :update, params: {id: level.to_param, level: valid_attributes}, session: valid_session
expect(response).to redirect_to(level)
end
end
context "with invalid params" do
it "returns a success response (i.e. to display the 'edit' template)" do
level = Level.create! valid_attributes
put :update, params: {id: level.to_param, level: invalid_attributes}, session: valid_session
expect(response).to be_success
end
end
end
describe "DELETE #destroy" do
it "destroys the requested level" do
level = Level.create! valid_attributes
expect {
delete :destroy, params: {id: level.to_param}, session: valid_session
}.to change(Level, :count).by(-1)
end
it "redirects to the levels list" do
level = Level.create! valid_attributes
delete :destroy, params: {id: level.to_param}, session: valid_session
expect(response).to redirect_to(levels_url)
end
end
end
| 35.28169 | 100 | 0.697605 |
ed711af545b8fe6c0899f47781009ed3ba60ee7d | 1,838 | # encoding: utf-8
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# /spec/fixtures/responses/whois.cctld.uz/uz/status_registered.expected
#
# and regenerate the tests with the following rake task
#
# $ rake spec:generate
#
require 'spec_helper'
require 'whois/record/parser/whois.cctld.uz.rb'
describe Whois::Record::Parser::WhoisCctldUz, "status_registered.expected" do
subject do
file = fixture("responses", "whois.cctld.uz/uz/status_registered.txt")
part = Whois::Record::Part.new(body: File.read(file))
described_class.new(part)
end
describe "#status" do
it do
expect(subject.status).to eq(:registered)
end
end
describe "#available?" do
it do
expect(subject.available?).to eq(false)
end
end
describe "#registered?" do
it do
expect(subject.registered?).to eq(true)
end
end
describe "#created_on" do
it do
expect(subject.created_on).to be_a(Time)
expect(subject.created_on).to eq(Time.parse("2006-04-13"))
end
end
describe "#updated_on" do
it do
expect(subject.updated_on).to be_a(Time)
expect(subject.updated_on).to eq(Time.parse("2010-03-26"))
end
end
describe "#expires_on" do
it do
expect(subject.expires_on).to be_a(Time)
expect(subject.expires_on).to eq(Time.parse("2011-05-01"))
end
end
describe "#nameservers" do
it do
expect(subject.nameservers).to be_a(Array)
expect(subject.nameservers.size).to eq(2)
expect(subject.nameservers[0]).to be_a(Whois::Record::Nameserver)
expect(subject.nameservers[0].name).to eq("ns1.google.com")
expect(subject.nameservers[1]).to be_a(Whois::Record::Nameserver)
expect(subject.nameservers[1].name).to eq("ns2.google.com")
end
end
end
| 27.029412 | 77 | 0.683896 |
e8debb5475d5684b7c1c95986fdb780a6a1a231b | 383 | module Billimatic
module Entities
class AddressInformation < Base
attribute :id, Integer
attribute :address, String
attribute :number, String
attribute :complement, String
attribute :district, String
attribute :zipcode, String
attribute :city, String
attribute :state, String
attribute :ibge_code, String
end
end
end
| 23.9375 | 35 | 0.678851 |
627a2d0ca8a198e4f3264be4865fb0ffe7c0379a | 1,000 | # Author:: radiospiel (mailto:[email protected])
# Copyright:: Copyright (c) 2011, 2012 radiospiel
# License:: Distributes under the terms of the Modified BSD License, see LICENSE.BSD for details.
require_relative 'test_helper'
require "contracts"
class ContractsModuleTest < Test::Unit::TestCase
module M
include Contracts
+Expects(one: 1)
def needs_one(one)
one * 2
end
end
class Klass
extend M
end
class Instance
include M
end
def test_class_method
assert_nothing_raised() {
Klass.needs_one(1)
}
e = assert_raise(Contracts::Error) {
Klass.needs_one(2)
}
assert e.backtrace.first.include?("test/contracts_module_test.rb:")
end
def test_instance_method
instance = Instance.new
assert_nothing_raised() {
instance.needs_one(1)
}
e = assert_raise(Contracts::Error) {
instance.needs_one(2)
}
assert e.backtrace.first.include?("test/contracts_module_test.rb:")
end
end
| 20.408163 | 100 | 0.681 |
793426cb7dc3f31ad4b5ad985b5f6a9c644a6b9b | 857 | # = Archon.populated_recordset
module Archon
def self.populated_recordset(base, rows = [])
return Nodes::PopulatedRecordset.new base, rows
end
module Nodes
# = PopulatedRecordset
#
# This ARel node creates a populated recordset from a JSON generated by the given ruby array of
# hashes.
class PopulatedRecordset < Arel::Nodes::NamedFunction
def initialize(base, rows = [])
raise ArgumentError, "rows is not an array" unless rows.is_a? Array
super 'json_populate_recordset', [
Arel::Nodes::SqlLiteral.new(base),
Arel::Nodes::Quoted.new(ActiveSupport::JSON.encode(rows))
]
end
def aliased_as(recordset_alias)
Arel::Nodes::TableAlias.new(self, recordset_alias)
end
def selectable
Arel::SelectManager.new self
end
end
end
end
| 27.645161 | 99 | 0.662777 |
1ac4f14ad3c7f82240e677cad35554b894a754a9 | 6,324 | =begin
#Selling Partner API for Product Fees
#The Selling Partner API for Product Fees lets you programmatically retrieve estimated fees for a product. You can then account for those fees in your pricing.
OpenAPI spec version: v0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 3.0.24
=end
require 'date'
module AmzSpApi::ProductFeesApiModel
# Additional information that can help the caller understand or fix the issue.
class FeesEstimateErrorDetail
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
}
end
# Attribute type mapping.
def self.openapi_types
{
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `AmzSpApi::ProductFeesApiModel::FeesEstimateErrorDetail` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `AmzSpApi::ProductFeesApiModel::FeesEstimateErrorDetail`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
# call parent's initialize
super(attributes)
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = super
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class && super(o)
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
super(attributes)
self.class.openapi_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
elsif attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
end
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
AmzSpApi::ProductFeesApiModel.const_get(type).build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = super
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end end
end
| 31.152709 | 232 | 0.636622 |
ab4f2eec020ae307c632dd1d972c9c3cb9fc7dcf | 3,546 | # frozen_string_literal: true
# Cloud Foundry TomEE Buildpack
# Copyright 2013-2019 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'java_buildpack/component/modular_component'
require 'java_buildpack/container'
require 'java_buildpack/container/tomcat/tomcat_insight_support'
require 'java_buildpack/container/tomee/tomee_instance'
require 'java_buildpack/container/tomee/tomee_resource_configuration'
require 'java_buildpack/container/tomcat/tomcat_external_configuration'
require 'java_buildpack/container/tomcat/tomcat_lifecycle_support'
require 'java_buildpack/container/tomcat/tomcat_logging_support'
require 'java_buildpack/container/tomcat/tomcat_access_logging_support'
require 'java_buildpack/container/tomcat/tomcat_redis_store'
require 'java_buildpack/container/tomcat/tomcat_setenv'
require 'java_buildpack/util/java_main_utils'
module JavaBuildpack
module Container
# Encapsulates the detect, compile, and release functionality for Tomee applications.
class Tomee < JavaBuildpack::Component::ModularComponent
protected
# (see JavaBuildpack::Component::ModularComponent#command)
def command
@droplet.environment_variables.add_environment_variable 'JAVA_OPTS', '$JAVA_OPTS'
@droplet.java_opts.add_system_property 'http.port', '$PORT'
[
@droplet.environment_variables.as_env_vars,
@droplet.java_home.as_env_var,
'exec',
"$PWD/#{(@droplet.sandbox + 'bin/catalina.sh').relative_path_from(@droplet.root)}",
'run'
].flatten.compact.join(' ')
end
# (see JavaBuildpack::Component::ModularComponent#sub_components)
def sub_components(context)
components = [
TomeeInstance.new(sub_configuration_context(context, 'tomee')),
TomeeResourceConfiguration.new(sub_configuration_context(context, 'resource_configuration')),
TomcatLifecycleSupport.new(sub_configuration_context(context, 'lifecycle_support')),
TomcatInsightSupport.new(context),
TomcatLoggingSupport.new(sub_configuration_context(context, 'logging_support')),
TomcatAccessLoggingSupport.new(sub_configuration_context(context, 'access_logging_support')),
TomcatRedisStore.new(sub_configuration_context(context, 'redis_store')),
TomcatSetenv.new(context)
]
tomee_configuration = @configuration['tomee']
components << TomcatExternalConfiguration.new(sub_configuration_context(context, 'external_configuration')) if
tomee_configuration['external_configuration_enabled']
components
end
# (see JavaBuildpack::Component::ModularComponent#supports?)
def supports?
(web_inf? && !JavaBuildpack::Util::JavaMainUtils.main_class(@application)) || ear?
end
private
def ear?
(@application.root + 'META-INF/application.xml').exist?
end
def web_inf?
(@application.root + 'WEB-INF').exist?
end
end
end
end
| 38.543478 | 118 | 0.740835 |
b903ea68172fed33f8be58af553d9b4d4a0db10b | 5,734 | =begin
PureCloud Platform API
With the PureCloud Platform API, you can control all aspects of your PureCloud environment. With the APIs you can access the system configuration, manage conversations and more.
OpenAPI spec version: v2
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
License: UNLICENSED
https://help.mypurecloud.com/articles/terms-and-conditions/
Terms of Service: https://help.mypurecloud.com/articles/terms-and-conditions/
=end
require 'date'
module PureCloud
class WorkspaceCreate
# The workspace name
attr_accessor :name
attr_accessor :bucket
attr_accessor :description
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'name' => :'name',
:'bucket' => :'bucket',
:'description' => :'description'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'name' => :'String',
:'bucket' => :'String',
:'description' => :'String'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v}
if attributes.has_key?(:'name')
self.name = attributes[:'name']
end
if attributes.has_key?(:'bucket')
self.bucket = attributes[:'bucket']
end
if attributes.has_key?(:'description')
self.description = attributes[:'description']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properies with the reasons
def list_invalid_properties
invalid_properties = Array.new
return invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
if @name.nil?
return false
end
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
name == o.name &&
bucket == o.bucket &&
description == o.description
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[name, bucket, description].hash
end
# build the object from hash
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
else
#TODO show warning in debug mode
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
else
# data not found in attributes(hash), not an issue as the data can be optional
end
end
self
end
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /^(true|t|yes|y|1)$/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
_model = Object.const_get("PureCloud").const_get(type).new
_model.build_from_hash(value)
end
end
def to_s
to_hash.to_s
end
# to_body is an alias to to_body (backward compatibility))
def to_body
to_hash
end
# return the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Method to output non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
def _to_hash(value)
if value.is_a?(Array)
value.compact.map{ |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 22.224806 | 177 | 0.565051 |
ff866b93bb6ba1b94befeecfa66c919d17b164b0 | 702 | module Pump
class Install::Firewall < Launchctl
PLIST_DIR = "/Library/LaunchDaemons"
PLIST = File.join(PLIST_DIR, "#{SERVICE_NAME_TEMPLATE}.plist")
def self.service_name
"firewall"
end
# Create and load plist under root
def self.install
mkdir_plist
create_plist
Base.load(PLIST % service_name)
end
# Unload and remove plist under root
def self.uninstall
Base.stop(SERVICE_NAME_TEMPLATE % service_name)
Base.unload(PLIST % service_name)
remove_plist
# TODO: Removing ipfw rule, is there more ruby way?
system("ipfw list | grep 127.0.0.1,11280 | awk '{ system(\"sudo ipfw delete \" $1) }'")
end
end
end
| 26 | 93 | 0.659544 |
0113bbe2d9b85250f12c12e988030c73178c9bc7 | 130 | class RenameForkedAppId < ActiveRecord::Migration
def change
rename_column :apps, :forked_play_id, :forked_app_id
end
end
| 21.666667 | 56 | 0.784615 |
3944dc8734c14c0ad97fe3ff4b7a3ab6b53af0eb | 148 | class Element < ActiveRecord::Base
belongs_to :dimension
has_many :scripts
has_many :scenes, through: :scripts
translates :description
end
| 18.5 | 37 | 0.77027 |
875b0451d8611f0a6f1101db7ff8183d6b03de1f | 245 | # frozen_string_literal: true
require 'feature_test'
class TestGraphicsFeature < FeatureTest
feature :graphics do
report = Thinreports::Report.new layout: template_path
report.start_new_page
assert_pdf report.generate
end
end
| 18.846154 | 58 | 0.779592 |
38dca22a6ac70358968ccd6cadaff59dd8956ed6 | 5,182 | ## --- BEGIN LICENSE BLOCK ---
# Original work Copyright (c) 2015-present the fastlane authors
# Modified work Copyright 2016-present WeWantToKnow AS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
## --- END LICENSE BLOCK ---
module U3dCore
# Shell is the terminal output of things
# For documentation for each of the methods open `interface.rb`
class Shell < Interface
# test_log_buffer: by default, don't show any logs when running tests
def initialize(test_log_buffer: nil)
@test_log_buffer = test_log_buffer
end
def log
return @log if @log
$stdout.sync = true
@log ||= if Helper.test?
Logger.new(@test_log_buffer)
else
Logger.new(EPipeIgnorerLogDevice.new($stdout))
end
@log.formatter = proc do |severity, datetime, _progname, msg|
"#{format_string(datetime, severity)}#{msg}\n"
end
require 'u3d_core/ui/disable_colors' if U3dCore::Helper.colors_disabled?
@log
end
class EPipeIgnorerLogDevice < Logger::LogDevice
def initialize(logdev)
@logdev = logdev
end
# rubocop:disable HandleExceptions
def write(message)
@logdev.write(message)
rescue Errno::EPIPE
# ignored
end
# rubocop:enable HandleExceptions
end
def format_string(datetime = Time.now, severity = "")
if U3dCore::Globals.log_timestamps?
timestamp = ENV["U3D_UI_TIMESTAMP"]
# default timestamp if none specified
timestamp ||= if U3dCore::Globals.verbose?
'%Y-%m-%d %H:%M:%S.%2N'
else
'%H:%M:%S'
end
end
# hide has last word
timestamp = nil if ENV["U3D_HIDE_TIMESTAMP"]
s = []
s << "#{severity} " if U3dCore::Globals.verbose? && severity && !severity.empty?
s << "[#{datetime.strftime(timestamp)}] " if timestamp
s.join('')
end
#####################################################
# @!group Messaging: show text to the user
#####################################################
def error(message)
log.error(message.to_s.red)
end
def important(message)
log.warn(message.to_s.yellow)
end
def success(message)
log.info(message.to_s.green)
end
def message(message)
log.info(message.to_s)
end
def deprecated(message)
log.error(message.to_s.bold.blue)
end
def command(message)
log.info("$ #{message}".cyan.underline)
end
def command_output(message)
actual = (message.split("\r").last || "") # as clearing the line will remove the `>` and the time stamp
actual.split("\n").each do |msg|
prefix = msg.include?("โธ") ? "" : "โธ "
log.info(prefix + "" + msg.magenta)
end
end
def verbose(message)
log.debug(message.to_s) if U3dCore::Globals.verbose?
end
def header(message)
i = message.length + 8
success("-" * i)
success("--- " + message + " ---")
success("-" * i)
end
#####################################################
# @!group Errors: Inputs
#####################################################
def interactive?
interactive = true
interactive = false if $stdout.isatty == false
interactive = false if Helper.ci?
return interactive
end
def input(message)
verify_interactive!(message)
ask("#{format_string}#{message.to_s.yellow}").to_s.strip
end
def confirm(message)
verify_interactive!(message)
agree("#{format_string}#{message.to_s.yellow} (y/n)", true)
end
def select(message, options)
verify_interactive!(message)
important(message)
choose(*options)
end
def password(message)
verify_interactive!(message)
ask("#{format_string}#{message.to_s.yellow}") { |q| q.echo = "*" }
end
private
def verify_interactive!(message)
return if interactive?
important(message)
crash!("Could not retrieve response as u3d runs in non-interactive mode")
end
end
end
| 29.611429 | 109 | 0.609996 |
085f6fad3120abfca7f2956d247c54886b96c678 | 411 | class CreateContractApprovers < ActiveRecord::Migration
def change
create_table :contract_approvers do |t|
t.references :contract, index: true
t.references :user, index: true
t.string :approved
t.string :notified
t.text :log
t.timestamps null: false
end
add_foreign_key :contract_approvers, :contracts
add_foreign_key :contract_approvers, :users
end
end
| 25.6875 | 55 | 0.705596 |
bfdbe0987a9be6ebf8175710116a091ad35ccec1 | 90 | #!/usr/bin/ruby
require_relative '../../../lib/kvm'
KVM.load_conf
puts DomainList.info
| 11.25 | 35 | 0.688889 |
b95d0bdb7689fb144bc136529b579d4c8088db5d | 5,462 | require "set"
require "tempfile"
require "vagrant/util/retryable"
require "vagrant/util/template_renderer"
module VagrantPlugins
module GuestFedora
module Cap
class ConfigureNetworks
extend Vagrant::Util::Retryable
include Vagrant::Util
def self.configure_networks(machine, networks)
network_scripts_dir = machine.guest.capability("network_scripts_dir")
virtual = false
interface_names = Array.new
interface_names_by_slot = Array.new
machine.communicate.sudo("/usr/sbin/biosdevname &>/dev/null; echo $?") do |_, result|
# The above command returns:
# - '4' if /usr/sbin/biosdevname detects it is running in a virtual machine
# - '127' if /usr/sbin/biosdevname doesn't exist
virtual = true if ['4', '127'].include? result.chomp
end
if virtual
machine.communicate.sudo("ls /sys/class/net | egrep -v lo\\|docker") do |_, result|
interface_names = result.split("\n")
end
interface_names_by_slot = networks.map do |network|
"#{interface_names[network[:interface]]}"
end
else
machine.communicate.sudo("/usr/sbin/biosdevname -d | grep Kernel | cut -f2 -d: | sed -e 's/ //;'") do |_, result|
interface_names = result.split("\n")
end
interface_name_pairs = Array.new
interface_names.each do |interface_name|
machine.communicate.sudo("/usr/sbin/biosdevname --policy=all_ethN -i #{interface_name}") do |_, result|
interface_name_pairs.push([interface_name, result.gsub("\n", "")])
end
end
setting_interface_names = networks.map do |network|
"eth#{network[:interface]}"
end
interface_names_by_slot = interface_names.dup
interface_name_pairs.each do |interface_name, previous_interface_name|
if setting_interface_names.index(previous_interface_name) == nil
interface_names_by_slot.delete(interface_name)
end
end
end
# Read interface MAC addresses for later matching
mac_addresses = Array.new(interface_names.length)
interface_names.each_with_index do |ifname, index|
machine.communicate.sudo("cat /sys/class/net/#{ifname}/address") do |_, result|
mac_addresses[index] = result.strip
end
end
# Accumulate the configurations to add to the interfaces file as well
# as what interfaces we're actually configuring since we use that later.
interfaces = Set.new
networks.each do |network|
interface = nil
if network[:mac_address]
found_idx = mac_addresses.find_index(network[:mac_address])
# Ignore network if requested MAC address could not be found
next if found_idx.nil?
interface = interface_names[found_idx]
else
ifname_by_slot = interface_names_by_slot[network[:interface]-1]
# Don't overwrite if interface was already matched via MAC address
next if interfaces.include?(ifname_by_slot)
interface = ifname_by_slot
end
interfaces.add(interface)
network[:device] = interface
# Remove any previous vagrant configuration in this network
# interface's configuration files.
machine.communicate.sudo("touch #{network_scripts_dir}/ifcfg-#{interface}")
machine.communicate.sudo("sed -e '/^#VAGRANT-BEGIN/,/^#VAGRANT-END/ d' #{network_scripts_dir}/ifcfg-#{interface} > /tmp/vagrant-ifcfg-#{interface}")
machine.communicate.sudo("cat /tmp/vagrant-ifcfg-#{interface} > #{network_scripts_dir}/ifcfg-#{interface}")
machine.communicate.sudo("rm -f /tmp/vagrant-ifcfg-#{interface}")
# Render and upload the network entry file to a deterministic
# temporary location.
entry = TemplateRenderer.render("guests/fedora/network_#{network[:type]}",
options: network)
temp = Tempfile.new("vagrant")
temp.binmode
temp.write(entry)
temp.close
machine.communicate.upload(temp.path, "/tmp/vagrant-network-entry_#{interface}")
end
# Bring down all the interfaces we're reconfiguring. By bringing down
# each specifically, we avoid reconfiguring p7p (the NAT interface) so
# SSH never dies.
interfaces.each do |interface|
retryable(on: Vagrant::Errors::VagrantError, tries: 3, sleep: 2) do
machine.communicate.sudo(<<-SCRIPT, error_check: true)
cat /tmp/vagrant-network-entry_#{interface} >> #{network_scripts_dir}/ifcfg-#{interface}
if command -v nmcli &>/dev/null; then
if command -v systemctl &>/dev/null && systemctl -q is-enabled NetworkManager &>/dev/null; then
nmcli c reload #{interface}
elif command -v service &>/dev/null && service NetworkManager status &>/dev/null; then
nmcli c reload #{interface}
fi
fi
/sbin/ifdown #{interface}
/sbin/ifup #{interface}
rm -f /tmp/vagrant-network-entry_#{interface}
SCRIPT
end
end
end
end
end
end
end
| 40.459259 | 160 | 0.613328 |
f8b6592875826f2223d9b29c1eb97f4cf2d55545 | 1,108 | # frozen_string_literal: true
module Gitlab
class GroupSearchResults < SearchResults
attr_reader :group
def initialize(current_user, query, limit_projects = nil, group:, default_project_filter: false)
@group = group
super(current_user, query, limit_projects, default_project_filter: default_project_filter)
end
# rubocop:disable CodeReuse/ActiveRecord
def users
# 1: get all groups the current user has access to
groups = GroupsFinder.new(current_user).execute.joins(:users)
# 2: Get the group's whole hierarchy
group_users = @group.direct_and_indirect_users
# 3: get all users the current user has access to (->
# `SearchResults#users`), which also applies the query.
users = super
# 4: filter for users that belong to the previously selected groups
users
.where(id: group_users.select('id'))
.where(id: groups.select('members.user_id'))
end
# rubocop:enable CodeReuse/ActiveRecord
def issuable_params
super.merge(group_id: group.id, include_subgroups: true)
end
end
end
| 29.945946 | 100 | 0.701264 |
6179d02a9ecf0ea09db2ae9e830ddc7ceee53177 | 860 | class Order < ApplicationRecord
include AASM
belongs_to :user, dependent: :destroy
has_many :order_items
validates :recipient, :tel, :address, presence: true
before_create :generate_order_num
aasm column: 'state' do
state :pending, initial: true
state :paid, :delivered, :cancelled
event :pay do
transitions from: :pending, to: :paid
before do |args|
self.transaction_id = args[:transaction_id]
self.paid_at = Time.now
end
end
event :deliver do
transitions from: :paid, to: :delivered
end
event :cancel do
transitions from: [:pending, :paid, :delivered], to: :cancelled
end
end
def total_price
order_items.reduce(0) { |sum, item| sum + item.total_price }
end
private
def generate_order_num
self.num = SecureRandom.hex(5) unless num
end
end
| 20.97561 | 69 | 0.666279 |
e9441817de1b3d512587cbc3627088d4a38fe11a | 9,655 | # encoding: utf-8
module Mail
# Provides access to a header object.
#
# ===Per RFC2822
#
# 2.2. Header Fields
#
# Header fields are lines composed of a field name, followed by a colon
# (":"), followed by a field body, and terminated by CRLF. A field
# name MUST be composed of printable US-ASCII characters (i.e.,
# characters that have values between 33 and 126, inclusive), except
# colon. A field body may be composed of any US-ASCII characters,
# except for CR and LF. However, a field body may contain CRLF when
# used in header "folding" and "unfolding" as described in section
# 2.2.3. All field bodies MUST conform to the syntax described in
# sections 3 and 4 of this standard.
class Header
include Patterns
include Utilities
include Enumerable
@@maximum_amount = 1000
# Large amount of headers in Email might create extra high CPU load
# Use this parameter to limit number of headers that will be parsed by
# mail library.
# Default: 1000
def self.maximum_amount
@@maximum_amount
end
def self.maximum_amount=(value)
@@maximum_amount = value
end
# Creates a new header object.
#
# Accepts raw text or nothing. If given raw text will attempt to parse
# it and split it into the various fields, instantiating each field as
# it goes.
#
# If it finds a field that should be a structured field (such as content
# type), but it fails to parse it, it will simply make it an unstructured
# field and leave it alone. This will mean that the data is preserved but
# no automatic processing of that field will happen. If you find one of
# these cases, please make a patch and send it in, or at the least, send
# me the example so we can fix it.
def initialize(header_text = nil, charset = nil)
@errors = []
@charset = charset
self.raw_source = header_text.to_crlf.lstrip
split_header if header_text
end
# The preserved raw source of the header as you passed it in, untouched
# for your Regexing glory.
def raw_source
@raw_source
end
# Returns an array of all the fields in the header in order that they
# were read in.
def fields
@fields ||= FieldList.new
end
# 3.6. Field definitions
#
# It is important to note that the header fields are not guaranteed to
# be in a particular order. They may appear in any order, and they
# have been known to be reordered occasionally when transported over
# the Internet. However, for the purposes of this standard, header
# fields SHOULD NOT be reordered when a message is transported or
# transformed. More importantly, the trace header fields and resent
# header fields MUST NOT be reordered, and SHOULD be kept in blocks
# prepended to the message. See sections 3.6.6 and 3.6.7 for more
# information.
#
# Populates the fields container with Field objects in the order it
# receives them in.
#
# Acceps an array of field string values, for example:
#
# h = Header.new
# h.fields = ['From: [email protected]', 'To: [email protected]']
def fields=(unfolded_fields)
@fields = Mail::FieldList.new
warn "Warning: more than #{self.class.maximum_amount} header fields only using the first #{self.class.maximum_amount}" if unfolded_fields.length > self.class.maximum_amount
unfolded_fields[0..(self.class.maximum_amount-1)].each do |field|
field = Field.new(field, nil, charset)
field.errors.each { |error| self.errors << error }
if limited_field?(field.name) && (selected = select_field_for(field.name)) && selected.any?
selected.first.update(field.name, field.value)
else
@fields << field
end
end
end
def errors
@errors
end
# 3.6. Field definitions
#
# The following table indicates limits on the number of times each
# field may occur in a message header as well as any special
# limitations on the use of those fields. An asterisk next to a value
# in the minimum or maximum column indicates that a special restriction
# appears in the Notes column.
#
# <snip table from 3.6>
#
# As per RFC, many fields can appear more than once, we will return a string
# of the value if there is only one header, or if there is more than one
# matching header, will return an array of values in order that they appear
# in the header ordered from top to bottom.
#
# Example:
#
# h = Header.new
# h.fields = ['To: [email protected]', 'X-Mail-SPAM: 15', 'X-Mail-SPAM: 20']
# h['To'] #=> '[email protected]'
# h['X-Mail-SPAM'] #=> ['15', '20']
def [](name)
name = dasherize(name).downcase
selected = select_field_for(name)
case
when selected.length > 1
selected.map { |f| f }
when !selected.blank?
selected.first
else
nil
end
end
# Sets the FIRST matching field in the header to passed value, or deletes
# the FIRST field matched from the header if passed nil
#
# Example:
#
# h = Header.new
# h.fields = ['To: [email protected]', 'X-Mail-SPAM: 15', 'X-Mail-SPAM: 20']
# h['To'] = '[email protected]'
# h['To'] #=> '[email protected]'
# h['X-Mail-SPAM'] = '10000'
# h['X-Mail-SPAM'] # => ['15', '20', '10000']
# h['X-Mail-SPAM'] = nil
# h['X-Mail-SPAM'] # => nil
def []=(name, value)
name = dasherize(name)
if name.include?(':')
raise ArgumentError, "Header names may not contain a colon: #{name.inspect}"
end
fn = name.downcase
selected = select_field_for(fn)
case
# User wants to delete the field
when !selected.blank? && value == nil
fields.delete_if { |f| selected.include?(f) }
# User wants to change the field
when !selected.blank? && limited_field?(fn)
selected.first.update(fn, value)
# User wants to create the field
else
# Need to insert in correct order for trace fields
self.fields << Field.new(name.to_s, value, charset)
end
if dasherize(fn) == "content-type"
# Update charset if specified in Content-Type
params = self[:content_type].parameters rescue nil
@charset = params && params[:charset]
end
end
def charset
@charset
end
def charset=(val)
params = self[:content_type].parameters rescue nil
if params
params[:charset] = val
end
@charset = val
end
LIMITED_FIELDS = %w[ date from sender reply-to to cc bcc
message-id in-reply-to references subject
return-path content-type mime-version
content-transfer-encoding content-description
content-id content-disposition content-location]
def encoded
buffer = ''
buffer.force_encoding('us-ascii') if buffer.respond_to?(:force_encoding)
fields.each do |field|
buffer << field.encoded
end
buffer
end
def to_s
encoded
end
def decoded
raise NoMethodError, 'Can not decode an entire header as there could be character set conflicts, try calling #decoded on the various fields.'
end
def field_summary
fields.map { |f| "<#{f.name}: #{f.value}>" }.join(", ")
end
# Returns true if the header has a Message-ID defined (empty or not)
def has_message_id?
!fields.select { |f| f.responsible_for?('Message-ID') }.empty?
end
# Returns true if the header has a Content-ID defined (empty or not)
def has_content_id?
!fields.select { |f| f.responsible_for?('Content-ID') }.empty?
end
# Returns true if the header has a Date defined (empty or not)
def has_date?
!fields.select { |f| f.responsible_for?('Date') }.empty?
end
# Returns true if the header has a MIME version defined (empty or not)
def has_mime_version?
!fields.select { |f| f.responsible_for?('Mime-Version') }.empty?
end
private
def raw_source=(val)
@raw_source = val
end
# 2.2.3. Long Header Fields
#
# The process of moving from this folded multiple-line representation
# of a header field to its single line representation is called
# "unfolding". Unfolding is accomplished by simply removing any CRLF
# that is immediately followed by WSP. Each header field should be
# treated in its unfolded form for further syntactic and semantic
# evaluation.
def unfold(string)
string.gsub(/#{CRLF}#{WSP}+/, ' ').gsub(/#{WSP}+/, ' ')
end
# Returns the header with all the folds removed
def unfolded_header
@unfolded_header ||= unfold(raw_source)
end
# Splits an unfolded and line break cleaned header into individual field
# strings.
def split_header
self.fields = unfolded_header.split(CRLF)
end
def select_field_for(name)
fields.select { |f| f.responsible_for?(name) }
end
def limited_field?(name)
LIMITED_FIELDS.include?(name.to_s.downcase)
end
# Enumerable support; yield each field in order to the block if there is one,
# or return an Enumerator for them if there isn't.
def each( &block )
return self.fields.each( &block ) if block
self.fields.each
end
end
end
| 33.408304 | 178 | 0.627343 |
79408fb2ff10bef328b7cba01802d9c75adfd388 | 6,269 |
require 'sass/plugin'
require 'compass'
require 'compass/commands'
require 'fileutils'
module Jekyll
module Compass
# This is the main generator plugin for Jekyll. Jekyll finds these plugins
# itself, we just need to be setup by the user as a gem plugin for their
# website. The plugin will only do something if there is a `_sass` folder
# in the source folder of the Jekyll website.
class Generator < ::Jekyll::Generator
safe true
priority :high
# This is the entry point to our plugin from Jekyll. We setup a compass
# environment and force a full compilation directly into the Jekyll output
# folder.
#
# @param site [Jekyll::Site] The site to generate for
# @return [void]
def generate(site)
@site = site
config = configuration(@site.source)
puts "\rGenerating Compass: #{config[:sass_path]}" +
" => #{config[:css_path]}"
unless File.exist? config[:sass_path]
print " Generating... "
return
end
configure_compass(config)
::Compass::Commands::UpdateProject.new(site.config['source'], config).
execute
puts
print " Generating... "
nil
end
private
# Compile a configuration Hash from sane defaults mixed with user input
# from `_config.yml` as well as `_data/compass.yml`.
#
# @param source [String] The project source folder
# @return [Hash]
def configuration(source)
config = {
:project_path => source,
:http_path => '/',
:sass_dir => '_sass',
:css_dir => 'css',
:images_path => File.join(source, 'images'),
:javascripts_path => File.join(source, 'js'),
:environment => :production,
:force => true,
}
user_config = @site.config['compass']
config = deep_merge!(config, symbolize_keys(user_config)) if user_config
user_data = @site.data['compass']
config = deep_merge!(config, symbolize_keys(user_data)) if user_data
unless config.key? :sass_path
config[:sass_path] =
File.join(source, config[:sass_dir])
end
unless config.key? :css_path
config[:css_path] =
File.join(@site.config['destination'], config[:css_dir])
end
symbolize_configuration!(config)
end
# Symbolize values for configuration values which require it.
#
# @param config [Hash]
# @return [Hash]
def symbolize_configuration!(config)
[
:project_type,
:environment,
:output_style,
:preferred_syntax,
:sprite_engine,
].each do |k|
config[k] = config[k].to_sym if config.key? k
end
config
end
# Sets up event handlers with Compass and various other
# configuration setup needs
#
# @param config [Hash] Configuration to pass to Compass and Sass
# @return [void]
def configure_compass(config)
::Compass.add_configuration(config, 'Jekyll::Compass')
::Compass.configuration.on_stylesheet_saved(
&method(:on_stylesheet_saved)
)
::Compass.configuration.on_sprite_saved(
&method(:on_sprite_saved)
)
::Compass.configuration.on_sprite_removed(
&method(:on_sprite_removed)
)
nil
end
# Event handler triggered when Compass creates a new stylesheet
#
# @param filename [String] The name of the created stylesheet.
# @return [void]
def on_stylesheet_saved(filename)
source = @site.config['destination']
@site.static_files <<
CompassFile.new(
@site,
source,
File.dirname(filename)[source.length..-1],
File.basename(filename)
)
nil
end
# Event handler triggered when Compass creates a new sprite image
#
# @param filename [String] The name of the created image.
# @return [void]
def on_sprite_saved(filename)
@site.static_files <<
StaticFile.new(
@site,
@site.source,
File.dirname(filename)[@site.source.length..-1],
File.basename(filename)
)
nil
end
# Event handler triggered when Compass deletes a stylesheet
#
# @param filename [String] The name of the deleted stylesheet.
# @return [void]
def on_sprite_removed(filename)
@site.static_files = @site.static_files.select do |p|
if p.path == filename
sprite_output = p.destination(@site.config['destination'])
File.delete sprite_output if File.exist? sprite_output
false
else
true
end
end
nil
end
# Merges a target hash with another hash, recursively.
#
# @param target [Hash] The target hash
# @param merge [Hash] The hash to merge into the target
# @return [Hash] Returns the merged target
def deep_merge!(target, merge)
merge.keys.each do |key|
if merge[key].is_a? Hash and target[key].is_a? Hash
target[key] = deep_merge!(target[key], merge[key])
else
target[key] = merge[key]
end
end
target
end
# Turn all String keys of a hash into symbols, and return in another Hash.
#
# @param hash [Hash] The hash to convert
# @return [Hash] Returns the symbolized copy of hash.
def symbolize_keys(hash)
target = hash.dup
target.keys.each do |key|
value = target.delete(key)
if value.is_a? Hash
value = symbolize_keys(value)
end
target[(key.to_sym rescue key) || key] = value
end
target
end
end
end
end
| 31.034653 | 81 | 0.553517 |
fff602328b69ba2b6a83daf36041ef0499699957 | 1,818 | # frozen_string_literal: true
require_relative "capture_code_context"
require_relative "display_code_with_line_numbers"
module DeadEnd
# Used for formatting invalid blocks
class DisplayInvalidBlocks
attr_reader :filename
def initialize(code_lines:, blocks:, io: $stderr, filename: nil, terminal: DEFAULT_VALUE)
@io = io
@blocks = Array(blocks)
@filename = filename
@code_lines = code_lines
@terminal = terminal == DEFAULT_VALUE ? io.isatty : terminal
end
def document_ok?
@blocks.none? { |b| !b.hidden? }
end
def call
if document_ok?
@io.puts "Syntax OK"
return self
end
if filename
@io.puts("--> #{filename}")
@io.puts
end
@blocks.each do |block|
display_block(block)
end
self
end
private def display_block(block)
# Build explanation
explain = ExplainSyntax.new(
code_lines: block.lines
).call
# Enhance code output
# Also handles several ambiguious cases
lines = CaptureCodeContext.new(
blocks: block,
code_lines: @code_lines
).call
# Build code output
document = DisplayCodeWithLineNumbers.new(
lines: lines,
terminal: @terminal,
highlight_lines: block.lines
).call
# Output syntax error explanation
explain.errors.each do |e|
@io.puts e
end
@io.puts
# Output code
@io.puts(document)
end
private def code_with_context
lines = CaptureCodeContext.new(
blocks: @blocks,
code_lines: @code_lines
).call
DisplayCodeWithLineNumbers.new(
lines: lines,
terminal: @terminal,
highlight_lines: @invalid_lines
).call
end
end
end
| 21.388235 | 93 | 0.612211 |
08e2b8d4cf8001c1b0d69761ad6e9c32f34cd19a | 2,302 | # frozen_string_literal: true
module Spotlight
module Concerns
##
# Search context helpers
module CatalogSearchContext
protected
def current_page_context
@current_page_context ||= if current_search_session_from_home_page?
current_exhibit.home_page if can? :read, current_exhibit.home_page
elsif current_search_session_from_page?
current_search_session_page_context
end
rescue ActiveRecord::RecordNotFound => e
Rails.logger.debug "Unable to get current page context from #{current_search_session.inspect}: #{e}"
nil
end
def current_browse_category
@current_browse_category ||= if current_search_session_from_browse_category?
search_id = current_search_session.query_params['id']
current_exhibit.searches.accessible_by(current_ability).find(search_id)
end
rescue ActiveRecord::RecordNotFound => e
Rails.logger.debug "Unable to get current page context from #{current_search_session.inspect}: #{e}"
nil
end
def current_search_session_from_browse_category?
current_search_session &&
current_search_session.query_params['action'] == 'show' &&
current_search_session.query_params['controller'] == 'spotlight/browse' &&
current_search_session.query_params['id']
end
def current_search_session_from_page?
current_search_session &&
current_search_session.query_params['action'] == 'show' &&
current_search_session.query_params['controller'].ends_with?('_pages')
end
def current_search_session_from_home_page?
current_search_session &&
current_search_session.query_params['action'] == 'show' &&
current_search_session.query_params['controller'] == 'spotlight/home_pages'
end
def current_search_session_page_context
page_id = current_search_session.query_params['id']
return unless page_id
current_exhibit.pages.accessible_by(current_ability).find(page_id)
end
end
end
end
| 38.366667 | 110 | 0.643354 |
62599229f11e0514a2d5a11f943de53fc5038126 | 522 | require('net/http')
address = ENV['PUMA_BIND_ADDRESS'] || 'localhost'
port = ENV['PUMA_BIND_PORT'] || 9292
http_class = Net::HTTP
target_address = URI.parse("http://#{address}:#{port}/health-check")
request_setup = { open_timeout: 5, read_timeout: 5 }
get_configuration = http_class::Get.new(target_address.to_s)
response =
http_class.start(target_address.host, target_address.port, **request_setup) do |session|
session.request(get_configuration)
end
if response.code.to_i == 200
exit(0)
else
exit(1)
end
| 24.857143 | 90 | 0.733716 |
bbba363f017d1110be26cb6471c8134784155854 | 48 | # ๅผ็จ rails engine
require 'company_info/engine'
| 16 | 29 | 0.791667 |
28e16e5b53d34fa4b2b2d427385a5d63f89c2aaf | 2,621 | # frozen_string_literal: true
require("config")
require("ctci/ctci_c3_p3")
module CTCI
module C3
class TestP3 < Minitest::Test
def setup
@stack = P3.new(3)
end
def test_size
@stack.push(0)
assert_equal(1, @stack.size)
end
def test_size_when_empty
assert_equal(0, @stack.size)
end
def test_size_when_over_capacity
4.times { @stack.push("foo") }
assert_equal(4, @stack.size)
end
def test_push_adds_to_the_top
(0..2).each { |i| @stack.push(i) }
assert_equal(2, @stack.peek)
end
def test_push_when_over_capacity
(0..3).each { |i| @stack.push(i) }
assert_equal(3, @stack.peek)
end
def test_peek_doesnt_remove_item
(0..2).each { |i| @stack.push(i) }
assert_equal(3, @stack.size)
assert_equal(2, @stack.peek)
assert_equal(3, @stack.size)
assert_equal(2, @stack.peek)
end
def test_peek_when_empty
assert_nil(@stack.peek)
end
def test_peek_when_over_capacity
(0..3).each { |i| @stack.push(i) }
assert_equal(3, @stack.peek)
end
def test_pop_removes_item
(0..2).each { |i| @stack.push(i) }
assert_equal(3, @stack.size)
assert_equal(2, @stack.pop)
assert_equal(2, @stack.size)
assert_equal(1, @stack.pop)
assert_equal(1, @stack.size)
end
def test_pop_when_empty
assert_nil(@stack.pop)
end
def test_pop_when_over_capacity
(0..3).each { |i| @stack.push(i) }
assert_equal(3, @stack.pop)
assert_equal(3, @stack.size)
assert_equal(2, @stack.pop)
assert_equal(2, @stack.size)
end
def test_pop_at_returns_top_item_from_specific_stack
(0..5).each { |i| @stack.push(i) }
assert_equal(2, @stack.pop_at(0))
assert_equal(5, @stack.pop_at(1))
end
def test_pop_at_removes_item
(0..5).each { |i| @stack.push(i) }
assert_equal(6, @stack.size)
assert_equal(2, @stack.pop_at(0))
assert_equal(5, @stack.size)
assert_equal(5, @stack.pop_at(1))
assert_equal(4, @stack.size)
end
def test_pop_at_when_empty
assert_nil(@stack.pop_at(0))
end
def test_pop_at_when_over_capacity
(0..8).each { |i| @stack.push(i) }
assert_equal(5, @stack.pop_at(1))
assert_equal(4, @stack.pop_at(1))
assert_equal(3, @stack.pop_at(1))
assert_equal(8, @stack.pop_at(1))
end
end
end
end
| 22.401709 | 58 | 0.579168 |
d508d2a84a3ebcc213b47a86f76423c2021dd840 | 708 | require 'pry'
class Spells
attr_accessor :_id, :index, :name, :desc, :higher_level, :range, :components, :material, :ritual, :duration, :concentration, :casting_time, :level, :attack_type, :damage, :school, :classes, :subclasses, :url, :dc, :heal_at_slot_level,
:area_of_effect
@@all = []
def initialize(attributes)
attributes.each {|key, value| self.send(("#{key}="), value)}
@@all << self
assign_to_klass
end
def self.all
@@all
end
def assign_to_klass
CharacterKlass.all.each do |klass_inst|
if self.classes.any? {|klass| klass[:name] == klass_inst.name}
klass_inst.spells << self
end
end
end
def self.spells_sorted_by_level
self.all.sort_by {|spell| spell.level}
end
end
| 22.83871 | 234 | 0.704802 |
abc85c0f29c15b3bb5c13ca2548a8e46ba2d9189 | 1,613 | #
# Be sure to run `pod lib lint MGXRouter.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'MGXRouter'
s.version = '1.0.0'
s.summary = 'iOS็ปไปถ่ฐๅบฆๅทฅๅ
ท๏ผ่ด่ดฃๆจกๅ้ดๅจๆ่ฐ็จ๏ผๆ ้ๅฎ้
ไพ่ตๅบฆๅ
ทไฝๆจกๅ๏ผ้ไฝๆจกๅ้ด็่ฆๅๅบฆ.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
ๆฏๆๅจๆ่ฐ็จ่ๅด๏ผ
1) ็ฑปๆนๆณ
2) ๅฏน่ฑกๆนๆณ
3) ๅไพ
DESC
s.homepage = 'https://github.com/changjianfeishui/MGXRouter.git'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'mangox' => '[email protected]' }
s.source = { :git => 'https://github.com/changjianfeishui/MGXRouter.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0'
s.source_files = 'MGXRouter/Classes/**/*'
# s.resource_bundles = {
# 'MGXRouter' => ['MGXRouter/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 35.065217 | 110 | 0.631122 |
f7f3954cec3cf6582adf7c6058e0a07868780ed5 | 223 | # Converts a blank node ID into a dummy URI
class ConvertBnodeToUri
def self.call(value)
return value unless value.is_a?(String) && value.starts_with?('_:')
"https://credreg.net/bnodes/#{value[2..-1]}"
end
end
| 24.777778 | 71 | 0.690583 |
0857fc162782f8ad6e0eaa9a9af8a09c357e3eb2 | 96 | class RestaurantSerializer < ActiveModel::Serializer
attributes :id, :name, :sample_image
end
| 24 | 52 | 0.802083 |
bb20ab91eec21fb70d914025924d42b8c431f457 | 1,066 | # encoding: utf-8
RSpec.describe TTY::Prompt::Result do
it "checks value to be invalid" do
question = double(:question)
result = TTY::Prompt::Result.new(question, nil)
answer = result.with { |quest, value|
if value.nil?
[value, ["`#{value}` provided cannot be empty"]]
else
value
end
}
expect(answer).to be_a(TTY::Prompt::Result::Failure)
expect(answer.success?).to eq(false)
expect(answer.errors).to eq(["`` provided cannot be empty"])
end
it "checks value to be valid" do
question = double(:question)
result = TTY::Prompt::Result.new(question, 'Piotr')
CheckRequired = Class.new do
def self.call(quest, value)
if value.nil?
[value, ["`#{value}` provided cannot be empty"]]
else
value
end
end
end
answer = result.with(CheckRequired)
expect(answer).to be_a(TTY::Prompt::Result::Success)
expect(answer.success?).to eq(true)
expect(answer.value).to eq('Piotr')
expect(answer.errors).to eq([])
end
end
| 26 | 64 | 0.613508 |
08c75563a6d13a03b209f074ad66ea4fdabaf574 | 820 | require 'test_helper'
module DocusignTransactionRooms
class ConfigurationTest < Minitest::Test
class ModifiedSettings < Minitest::Test
def test_the_api_url_can_be_set
assert_equal "https://demo.rooms.docusign.com", DocusignTransactionRooms.configuration.api_url
DocusignTransactionRooms.configure { |config| config.api_url = "https://api.mylittlepony.com"}
assert_equal "https://api.mylittlepony.com", DocusignTransactionRooms.configuration.api_url
end
def test_the_path_url_can_be_set
assert_equal "restapi/v1", DocusignTransactionRooms.configuration.path_url
DocusignTransactionRooms.configure { |config| config.path_url = "v1/towns"}
assert_equal "v1/towns", DocusignTransactionRooms.configuration.path_url
end
end
end
end
| 29.285714 | 102 | 0.75122 |
2114bb6201635862ee0153f3e1c3205ee274f8f1 | 2,207 | # frozen_string_literal: true
require 'rails_helper'
feature 'Admins can browse car categories' do
before :each do
log_user_in!
end
scenario 'and view car models links inside a dropdown' do
honda = Manufacturer.create! name: 'Honda'
fiat = Manufacturer.create! name: 'Fiat'
sedan = CarCategory.create! name: 'Sedan', daily_rate: 100.0,
insurance: 10.0, third_party_insurance: 5.0
truck = CarCategory.create! name: 'Camiรฃo', daily_rate: 140.0, insurance: 20.0,
third_party_insurance: 15.0
civic = CarModel.create! name: 'Civic', year: '2010', manufacturer: honda,
metric_horsepower: '135 @ 6500 rpm', car_category: sedan,
fuel_type: 'gasolina', metric_city_milage: 12,
metric_highway_milage: 16, engine: '1.6 L R16A1 I4'
uno = CarModel.create! name: 'Uno', year: '2019', manufacturer: fiat,
metric_horsepower: '120 @ 6500 rpm', car_category: sedan,
fuel_type: 'gasolina', metric_city_milage: 14,
metric_highway_milage: 18, engine: '1.3 L L13A I4'
ridgeline = CarModel.create! name: 'Ridgeline', year: '2005', manufacturer: honda,
metric_horsepower: '120 @ 6500 rpm', car_category: truck,
fuel_type: 'gasolina', metric_city_milage: 14,
metric_highway_milage: 18, engine: '1.3 L L13A I4'
visit car_categories_path
within "tr#car-category-#{sedan.id}" do
expect(page).to have_link 'Honda Civic 2010', href: car_model_path(civic)
expect(page).to have_link 'Fiat Uno 2019', href: car_model_path(uno)
expect(page).not_to have_link 'Honda Ridgeline 2005', href: car_model_path(ridgeline)
end
within "tr#car-category-#{truck.id}" do
expect(page).to have_link 'Honda Ridgeline 2005', href: car_model_path(ridgeline)
expect(page).not_to have_link 'Honda Civic 2010', href: car_model_path(civic)
expect(page).not_to have_link 'Fiat Uno 2019', href: car_model_path(uno)
end
end
end
| 44.14 | 91 | 0.613956 |
38fa9d61a40ceee56223fd79d088ac6d3759dc47 | 150 | class ChangeAddressesCountryToCountryCode < ActiveRecord::Migration[4.2]
def change
rename_column :addresses, :country, :country_code
end
end
| 25 | 72 | 0.793333 |
acb6482a64fcdcd32482d8b00c4ba33b2983d78a | 464 | #!/usr/bin/env ruby
require "./lib/orphaned_statefiles"
s3 = Aws::S3::Resource.new(
region: ENV.fetch("TF_STATE_BUCKET_REGION"),
access_key_id: ENV.fetch("TF_STATE_BUCKET_AWS_ACCESS_KEY_ID"),
secret_access_key: ENV.fetch("TF_STATE_BUCKET_AWS_SECRET_ACCESS_KEY"),
)
ctsf = DeletedClusterTerraformStateFiles.new(
s3: s3,
bucket: "cloud-platform-terraform-state",
cluster_region: "eu-west-2",
)
puts({ data: ctsf.list, updated_at: Time.now }.to_json)
| 25.777778 | 72 | 0.75431 |
1da64b5643b3058997f34fd2a2c3a6940f7a8a7b | 166 | # This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
run Samplewebservice::Application
| 33.2 | 67 | 0.783133 |
d5c63bdd0ce68f5dfcad5d1414be23f211402ff4 | 729 |
class Publicaciones < Referencia
attr_reader :nombre
def initialize(autores,titulo,nombre)
super(autores,titulo)
@nombre = nombre
end
def ==(other)
if (super(other))
for i in (0..nombre.length)
if (nombre[i] != other.nombre[i])
return false
end
end
return true
end
false
end
def getNombre
return @nombre
end
def to_s
out = super.to_s + "#{@nombre}" + ", "
return out
end
end | 20.828571 | 53 | 0.377229 |
616991fcfd6b7f9d9d02687708229e60ee22cf8e | 881 | class Api::V1::DoctorsController < ApplicationController
before_action :set_doctor, only: [:show, :update, :destroy]
def show
render json: @doctor
end
def create
@doctor = Doctor.new(doctor_params)
if @doctor.save
render json: @doctor
else
render json: @doctor.errors, status: :unprocessable_entity
end
end
def update
if @doctor.update(doctor_params)
render json: @doctor
else
render @doctor.errors, status: :unprocessable_entity
end
end
def destroy
@doctor.destroy
end
private
def set_doctor
@doctor = Doctor.find(params[:id])
end
def doctor_params
params.require(:doctor).permit(:last_name, :uid, :user_note, :user_id)
end
end
| 21.487805 | 83 | 0.561862 |
8752ea265b8eed3af0d26c900ff2af52409f07cb | 1,088 | require "rails_helper"
describe "GET /zones", type: :feature do
context "User with viewer permissions" do
before do
login_as create(:user, :reader)
end
it "lists zones" do
zone = create :zone
zone2 = create :zone, name: "test.example.com"
visit "/dns"
expect(page).to have_content zone.name
expect(page).to have_content zone.forwarders.join(" ")
expect(page).to have_content zone.purpose
expect(page).to have_content zone2.name
end
it "can see the zone management links" do
visit "/dns"
expect(page).to_not have_content "Create a new zone"
expect(page).to_not have_content "Edit"
expect(page).to_not have_content "Delete"
end
end
context "User with editor permissions" do
before do
login_as create(:user, :editor)
create :zone
end
it "can see the zone management links" do
visit "/dns"
expect(page).to have_content "Create a new zone"
expect(page).to have_content "Manage"
expect(page).to have_content "Delete"
end
end
end
| 24.177778 | 60 | 0.653493 |
33806679220d870ed67a3cc89bb70a243eeeb73e | 5,389 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Policy::Mgmt::V2017_06_01_preview
#
# A service client - single point of access to the REST API.
#
class PolicyClient < MsRestAzure::AzureServiceClient
include MsRestAzure
include MsRestAzure::Serialization
# @return [String] the base URI of the service.
attr_accessor :base_url
# @return Credentials needed for the client to connect to Azure.
attr_reader :credentials
# @return [String] The ID of the target subscription.
attr_accessor :subscription_id
# @return [String] The API version to use for the operation.
attr_reader :api_version
# @return [String] The preferred language for the response.
attr_accessor :accept_language
# @return [Integer] The retry timeout in seconds for Long Running
# Operations. Default value is 30.
attr_accessor :long_running_operation_retry_timeout
# @return [Boolean] Whether a unique x-ms-client-request-id should be
# generated. When set to true a unique x-ms-client-request-id value is
# generated and included in each request. Default is true.
attr_accessor :generate_client_request_id
# @return [PolicyAssignments] policy_assignments
attr_reader :policy_assignments
# @return [PolicySetDefinitions] policy_set_definitions
attr_reader :policy_set_definitions
#
# Creates initializes a new instance of the PolicyClient class.
# @param credentials [MsRest::ServiceClientCredentials] credentials to authorize HTTP requests made by the service client.
# @param base_url [String] the base URI of the service.
# @param options [Array] filters to be applied to the HTTP requests.
#
def initialize(credentials = nil, base_url = nil, options = nil)
super(credentials, options)
@base_url = base_url || 'https://management.azure.com'
fail ArgumentError, 'invalid type of credentials input parameter' unless credentials.is_a?(MsRest::ServiceClientCredentials) unless credentials.nil?
@credentials = credentials
@policy_assignments = PolicyAssignments.new(self)
@policy_set_definitions = PolicySetDefinitions.new(self)
@api_version = '2017-06-01-preview'
@accept_language = 'en-US'
@long_running_operation_retry_timeout = 30
@generate_client_request_id = true
add_telemetry
end
#
# Makes a request and returns the body of the response.
# @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
# @param path [String] the path, relative to {base_url}.
# @param options [Hash{String=>String}] specifying any request options like :body.
# @return [Hash{String=>String}] containing the body of the response.
# Example:
#
# request_content = "{'location':'westus','tags':{'tag1':'val1','tag2':'val2'}}"
# path = "/path"
# options = {
# body: request_content,
# query_params: {'api-version' => '2016-02-01'}
# }
# result = @client.make_request(:put, path, options)
#
def make_request(method, path, options = {})
result = make_request_with_http_info(method, path, options)
result.body unless result.nil?
end
#
# Makes a request and returns the operation response.
# @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
# @param path [String] the path, relative to {base_url}.
# @param options [Hash{String=>String}] specifying any request options like :body.
# @return [MsRestAzure::AzureOperationResponse] Operation response containing the request, response and status.
#
def make_request_with_http_info(method, path, options = {})
result = make_request_async(method, path, options).value!
result.body = result.response.body.to_s.empty? ? nil : JSON.load(result.response.body)
result
end
#
# Makes a request asynchronously.
# @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
# @param path [String] the path, relative to {base_url}.
# @param options [Hash{String=>String}] specifying any request options like :body.
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def make_request_async(method, path, options = {})
fail ArgumentError, 'method is nil' if method.nil?
fail ArgumentError, 'path is nil' if path.nil?
request_url = options[:base_url] || @base_url
if(!options[:headers].nil? && !options[:headers]['Content-Type'].nil?)
@request_headers['Content-Type'] = options[:headers]['Content-Type']
end
request_headers = @request_headers
request_headers.merge!({'accept-language' => @accept_language}) unless @accept_language.nil?
options.merge!({headers: request_headers.merge(options[:headers] || {})})
options.merge!({credentials: @credentials}) unless @credentials.nil?
super(request_url, method, path, options)
end
private
#
# Adds telemetry information.
#
def add_telemetry
sdk_information = 'azure_mgmt_policy'
sdk_information = "#{sdk_information}/0.17.8"
add_user_agent_information(sdk_information)
end
end
end
| 39.625 | 154 | 0.696048 |
1d4e4ee713c562ed815e47f690e14ac595bc5430 | 1,599 | require 'open3'
module Wisepdf
class Writer
def initialize(wkhtmltopdf = nil, options = {})
self.wkhtmltopdf = wkhtmltopdf unless wkhtmltopdf.nil?
self.options = options
end
def to_pdf(string, options={})
invoke = self.command(options).join(' ')
self.log(invoke) if Wisepdf::Configuration.development? || Wisepdf::Configuration.test? || Wisepdf::Configuration.debug?
result, err = Open3.popen3(invoke) do |stdin, stdout, stderr|
stdin.write(string)
stdin.close
[stdout.read, stderr.read]
end
raise Wisepdf::WriteError if result.to_s.strip.empty?
return result
end
def wkhtmltopdf
@wkhtmltopdf ||= Wisepdf::Configuration.wkhtmltopdf
@wkhtmltopdf
end
def wkhtmltopdf=(value)
@wkhtmltopdf = value
raise Wisepdf::NoExecutableError.new(@wkhtmltopdf) if @wkhtmltopdf.blank? || !File.exists?(@wkhtmltopdf)
end
def options
@options ||= Wisepdf::Parser.parse(Wisepdf::Configuration.options.dup)
@options
end
def options=(value)
self.options.merge!(Wisepdf::Parser.parse(value))
end
protected
def command(options = {})
options = Wisepdf::Parser.parse(options)
args = [self.wkhtmltopdf]
args += self.options.merge(options).to_a.flatten.compact
args << '--quiet'
args << '-'
args << '-'
args.map {|arg| %Q{"#{arg.gsub('"', '\"')}"}}
end
def log(command)
puts "*"*15
puts command
puts "*"*15
end
end
end | 24.984375 | 127 | 0.601626 |
3947e1b9d7b562a6d09cd2550896bc3c37f78c86 | 1,888 | cask 'cocktail' do
if MacOS.release == :snow_leopard
version '5.1'
sha256 '630fc5236e95d5ec36c0de4b487f8ece76d8f02ecd00ec4b37124ddd0eed0f34'
url "http://www.maintain.se/downloads/sparkle/snowleopard/Cocktail_#{version}.zip"
appcast 'http://www.maintain.se/downloads/sparkle/snowleopard/snowleopard.xml'
elsif MacOS.release == :lion
version '5.6'
sha256 '9fa8ff2ade1face0a1a36baf36cfa384535179b261716c18538b0102f281ee60'
url "http://www.maintain.se/downloads/sparkle/lion/Cocktail_#{version}.zip"
appcast 'http://www.maintain.se/downloads/sparkle/lion/lion.xml'
elsif MacOS.release == :mountain_lion
version '6.9'
sha256 '309bac603a6ded301e9cc61b32bb522fc3a5208973cbd6c6f1a09d0e2c78d1e6'
url "http://www.maintain.se/downloads/sparkle/mountainlion/Cocktail_#{version}.zip"
appcast 'http://www.maintain.se/downloads/sparkle/mountainlion/mountainlion.xml'
elsif MacOS.release == :mavericks
version '7.9.1'
sha256 'b8b5c37df3a2c44406f9fdf1295357d03b8fca6a9112b61401f0cca2b8e37033'
url "http://www.maintain.se/downloads/sparkle/mavericks/Cocktail_#{version}.zip"
appcast 'http://www.maintain.se/downloads/sparkle/mavericks/mavericks.xml'
elsif MacOS.release == :yosemite
version '8.6'
sha256 '847f199c18d0dccec6590b4e1820a358672ba789b7e8586c20376656db84b8d7'
url "http://www.maintain.se/downloads/sparkle/yosemite/Cocktail_#{version}.zip"
appcast 'http://www.maintain.se/downloads/sparkle/yosemite/yosemite.xml'
else
version '9.1'
sha256 '4db7952900fce3a2c556ec5151b76db336a456bd37c30ff88a0bbfd9708ed3e0'
url "http://www.maintain.se/downloads/sparkle/elcapitan/Cocktail_#{version}.zip"
appcast 'http://www.maintain.se/downloads/sparkle/elcapitan/elcapitan.xml'
end
name 'Cocktail'
homepage 'http://www.maintain.se/cocktail/'
license :commercial
app 'Cocktail.app'
end
| 41.043478 | 87 | 0.768008 |
61b252075d61754d5a9ab341e9f4fb2f5ee5d390 | 2,938 | # frozen_string_literal: true
require 'dopp'
require 'dopp/section/cid_type0_font'
module Dopp
module Font
# CID font "MS Mincho".
class MsMincho
include ::Dopp::Error
include ::Dopp::Font
# Font names.
NAMES ||= %w[
MSๆๆ MS-Mincho
].tap { |v| ::Dopp::Util.deep_freeze(v) }
# Add self to font store.
NAMES.each do |name|
STORE.add_font_builder(name, self)
end
# Initialize.
# @param [::Dopp::Document::Structure]
# structure PDF document structure.
def initialize(structure, opts = {})
check_is_a!(structure, ::Dopp::Document::Structure)
@opts = opts
@font = ::Dopp::Section::CidType0Font.new(structure)
@dict = @font.new_dictionary
@desc = @dict.new_descriptor
@desc_flags = { fixed_pitch: true, symbolic: true }
end
# Build font section.
# @return [::Dopp::Section::CidType0Font] Font section.
def build
build_common
return bold_italic if @opts[:bold] && @opts[:italic]
return italic if @opts[:italic]
return bold if @opts[:bold]
normal
end
private
# Build common part of this font.
def build_common
@font.encoding = 'UniJIS-UCS2-H'
@font.names = NAMES
# Initialize font dictionary.
@dict.registry = 'Adobe'
@dict.ordering = 'Japan1'
@dict.supplement = 2
@dict.default_width = 1000
@dict.default_vertical_widths = [880, -1000]
# Initialize font descriptor.
@desc.b_box = [0, -136, 1000, 859]
@desc.italic_angle = 0
@desc.ascent = 859
@desc.descent = -140
@desc.cap_height = 769
@desc.stem_v = 78
end
# Build normal font.
# @return [::Dopp::Section::CidType0Font] Font section.
def normal
@font.fullname = 'MS-Mincho'
@desc.flags = flag_value(@desc_flags)
@font
end
# Build bold font.
# @return [::Dopp::Section::CidType0Font] Font section.
def bold
@font.fullname = 'MS-Mincho.Bold'
@desc.flags = flag_value(
@desc_flags.merge(force_bold: true)
)
@desc.stem_v = 156
@font
end
# Build italic font.
# @return [::Dopp::Section::CidType0Font] Font section.
def italic
@font.fullname = 'MS-Mincho.Italic'
@desc.flags = flag_value(
@desc_flags.merge(italic: true)
)
@desc.italic_angle = -11
@font
end
# Build bold italic font.
# @return [::Dopp::Section::CidType0Font] Font section.
def bold_italic
@font.fullname = 'MS-Mincho.BoldItalic'
@desc.flags = flag_value(
@desc_flags.merge(italic: true, force_bold: true)
)
@desc.italic_angle = -11
@desc.stem_v = 156
@font
end
end
end
end
| 26.468468 | 61 | 0.566031 |
1a0359b20cd5444f8ab84bc70f5ae0f9c293b137 | 3,648 | require 'spec_helper'
RSpec.describe 'OkexSwap integration specs' do
let(:client) { Cryptoexchange::Client.new }
let(:xbt_usd_pair) { Cryptoexchange::Models::MarketPair.new(base: 'BTC', target: 'USD', market: 'okex_swap', contract_interval: "perpetual", inst_id: "BTC-USD-SWAP") }
let(:xbt_usd_pair_weekly) { Cryptoexchange::Models::MarketPair.new(base: 'BTC', target: 'USD', market: 'okex_swap', contract_interval: "weekly", inst_id: "BTC-USD-190927") }
it 'fetch pairs' do
pairs = client.pairs('okex_swap')
expect(pairs).not_to be_empty
pair = pairs.first
expect(pair.base).to_not be nil
expect(pair.target).to_not be nil
expect(pair.market).to eq 'okex_swap'
expect(pair.contract_interval).to eq "perpetual"
expect(pair.inst_id).to eq "BTC-USD-SWAP"
end
it 'fetch ticker' do
ticker = client.ticker(xbt_usd_pair)
expect(ticker.base).to eq 'BTC'
expect(ticker.target).to eq 'USD'
expect(ticker.market).to eq 'okex_swap'
expect(ticker.inst_id).to eq 'BTC-USD-SWAP'
expect(ticker.last).to be_a Numeric
expect(ticker.ask).to be_a Numeric
expect(ticker.bid).to be_a Numeric
expect(ticker.low).to be_a Numeric
expect(ticker.high).to be_a Numeric
expect(ticker.volume).to be_a Numeric
expect(ticker.timestamp).to be nil
expect(ticker.payload).to_not be nil
expect(ticker.contract_interval).to eq "perpetual"
end
it 'fetch futures ticker' do
ticker = client.ticker(xbt_usd_pair_weekly)
expect(ticker.base).to eq 'BTC'
expect(ticker.target).to eq 'USD'
expect(ticker.market).to eq 'okex_swap'
expect(ticker.inst_id).to eq 'BTC-USD-190927'
expect(ticker.last).to be_a Numeric
expect(ticker.ask).to be_a Numeric
expect(ticker.bid).to be_a Numeric
expect(ticker.low).to be_a Numeric
expect(ticker.high).to be_a Numeric
expect(ticker.volume).to be_a Numeric
expect(ticker.timestamp).to be nil
expect(ticker.payload).to_not be nil
expect(ticker.contract_interval).to eq "weekly"
end
it 'fetch order book' do
order_book = client.order_book(xbt_usd_pair)
expect(order_book.base).to eq 'BTC'
expect(order_book.target).to eq 'USD'
expect(order_book.market).to eq 'okex_swap'
expect(order_book.asks).to_not be_empty
expect(order_book.bids).to_not be_empty
expect(order_book.asks.first.price).to_not be_nil
expect(order_book.bids.first.amount).to_not be_nil
expect(order_book.bids.first.timestamp).to be_nil
expect(order_book.asks.count).to be > 10
expect(order_book.bids.count).to be > 10
expect(order_book.timestamp).to be nil
expect(order_book.payload).to_not be nil
end
it 'fetch contract stat' do
contract_stat = client.contract_stat(xbt_usd_pair_weekly)
expect(contract_stat.base).to eq 'BTC'
expect(contract_stat.target).to eq 'USD'
expect(contract_stat.market).to eq 'okex_swap'
expect(contract_stat.index).to be_a Numeric
expect(contract_stat.open_interest).to be_a Numeric
expect(contract_stat.timestamp).to be nil
expect(contract_stat.payload).to_not be nil
end
# it 'fetch trade' do
# trades = client.trades(xbt_usd_pair)
# trade = trades.sample
# expect(trades).to_not be_empty
# expect(trade.base).to eq 'XBT'
# expect(trade.target).to eq 'USD'
# expect(trade.market).to eq 'bitmex'
# expect(trade.trade_id).to_not be_nil
# expect(['buy', 'sell']).to include trade.type
# expect(trade.price).to_not be_nil
# expect(trade.amount).to_not be_nil
# expect(trade.timestamp).to be_a Numeric
# expect(trade.payload).to_not be nil
# end
end
| 36.118812 | 175 | 0.712719 |
d579df1303fa05f61334f168e566a3a0f61ca23c | 310 | class CreateFaces < ActiveRecord::Migration
def change
create_table :faces do |t|
t.integer :photo_id
t.string :database_uuid
t.string :face_uuid
t.float :x
t.float :y
t.float :w
t.float :h
t.integer :person_id
t.string :timestamps
end
end
end
| 19.375 | 43 | 0.609677 |
b9640f68a511fbdc14c9d99da8a8666ca06f8915 | 2,448 | require 'spec_helper'
describe 'octavia::quota' do
let :default_params do
{
:default_load_balancer_quota => '<SERVICE DEFAULT>',
:default_listener_quota => '<SERVICE DEFAULT>',
:default_member_quota => '<SERVICE DEFAULT>',
:default_pool_quota => '<SERVICE DEFAULT>',
:default_health_monitor_quota => '<SERVICE DEFAULT>'
}
end
let :params do
{}
end
shared_examples_for 'octavia quota' do
let :p do
default_params.merge(params)
end
it 'contains default values' do
is_expected.to contain_octavia_config('quotas/default_load_balancer_quota').with_value(p[:default_load_balancer_quota])
is_expected.to contain_octavia_config('quotas/default_listener_quota').with_value(p[:default_listener_quota])
is_expected.to contain_octavia_config('quotas/default_member_quota').with_value(p[:default_member_quota])
is_expected.to contain_octavia_config('quotas/default_pool_quota').with_value(p[:default_pool_quota])
is_expected.to contain_octavia_config('quotas/default_health_monitor_quota').with_value(p[:default_health_monitor_quota])
end
context 'configure quota with parameters' do
before :each do
params.merge!({
:default_load_balancer_quota => 10,
:default_listener_quota => 20,
:default_member_quota => 30,
:default_pool_quota => 40,
:default_health_monitor_quota => 50
})
end
it 'contains overrided values' do
is_expected.to contain_octavia_config('quotas/default_load_balancer_quota').with_value(p[:default_load_balancer_quota])
is_expected.to contain_octavia_config('quotas/default_listener_quota').with_value(p[:default_listener_quota])
is_expected.to contain_octavia_config('quotas/default_member_quota').with_value(p[:default_member_quota])
is_expected.to contain_octavia_config('quotas/default_pool_quota').with_value(p[:default_pool_quota])
is_expected.to contain_octavia_config('quotas/default_health_monitor_quota').with_value(p[:default_health_monitor_quota])
end
end
end
on_supported_os({
:supported_os => OSDefaults.get_supported_os
}).each do |os,facts|
context "on #{os}" do
let (:facts) do
facts.merge(OSDefaults.get_facts({:os_workers => 8}))
end
it_configures 'octavia quota'
end
end
end
| 37.090909 | 129 | 0.705065 |
e9c55648ce605ab724ea3b8405571afa1ee8cc9e | 2,393 | describe 'Additional Attribute data type', js: true do
context 'when viewing the descriptive keywords form' do
before do
login
draft = create(:collection_draft, user: User.where(urs_uid: 'testuser').first)
visit collection_draft_path(draft)
within '.metadata' do
click_on 'Descriptive Keywords'
end
click_on 'Expand All'
end
context 'when selecting a non-numeric data type' do
before do
select 'String', from: 'Data Type'
end
it 'disabled invalid fields' do
expect(page).to have_field('Parameter Range Begin', disabled: true)
expect(page).to have_field('Parameter Range End', disabled: true)
end
context 'when viewing a saved form with a non-numeric data type' do
before do
within '.nav-top' do
click_on 'Save'
end
click_on 'Yes'
click_on 'Expand All'
end
it 'disables the invalid fields' do
expect(page).to have_field('Parameter Range Begin', disabled: true)
expect(page).to have_field('Parameter Range End', disabled: true)
end
end
context 'when selecting a numeric data type' do
before do
select 'Integer', from: 'Data Type'
end
it 'enables all fields' do
expect(page).to have_field('Parameter Range Begin', disabled: false)
expect(page).to have_field('Parameter Range End', disabled: false)
end
end
end
context 'when entering an invalid range' do
before do
select 'Integer', from: 'Data Type'
fill_in 'Parameter Range Begin', with: '5'
fill_in 'Parameter Range End', with: '5'
find('body').click
end
it 'displays an error' do
expect(page).to have_content('Parameter Range End must be larger than Parameter Range Begin')
end
context 'when viewing the preview page with an invalid range' do
before do
fill_in 'Name', with: 'Attribute name'
within '.nav-top' do
click_on 'Done'
end
click_on 'Yes'
end
it 'displays an error circle for AdditionalAttributes' do
within 'a[title="Additional Attributes - Invalid"]' do
expect(page).to have_css('.icon-red')
end
end
end
end
end
end
| 28.488095 | 101 | 0.602591 |
7adf892d34c7e032f078e4ac95ef375f95a98abf | 292 | module Backline
module Attributes
class Attribute < Struct.new(:name, :options)
def initialize(name, options = {})
super(name.to_s, options)
end
def getter_method
name
end
def setter_method
"#{name}="
end
end
end
end | 15.368421 | 49 | 0.568493 |
1d81837a9315a263000ab907009b788f6f4ac18d | 806 |
Puppet::Type.newtype(:oneandone_firewall) do
@doc = 'Type representing a 1&1 firewall policy.'
ensurable
newparam(:name, namevar: true) do
desc 'The name of the firewall policy.'
validate do |value|
raise('The name should be a String.') unless value.is_a?(String)
end
end
newproperty(:rules, array_matching: :all) do
desc 'The firewall policy rules.'
end
newproperty(:id) do
desc 'The firewall policy ID.'
end
newproperty(:description) do
desc 'The firewall policy description.'
end
newproperty(:server_ips, array_matching: :all) do
desc 'The servers/IPs attached to the firewall policy.'
def insync?(is)
if is.is_a? Array
return is.sort == should.sort
else
return is == should
end
end
end
end
| 21.210526 | 70 | 0.657568 |
9150aa543a0925480be57ab12ac57af640978e83 | 1,240 | class Cbmc < Formula
desc "C Bounded Model Checker"
homepage "https://www.cprover.org/cbmc/"
url "https://github.com/diffblue/cbmc.git",
tag: "cbmc-5.18.0",
revision: "7ff70ee00d85ff9d84c2534db9b975d8e04d4559"
license "BSD-4-Clause"
bottle do
cellar :any_skip_relocation
sha256 "ed3c1e642156409d322f635bf7c140f6d7c7ce6958003878f4b02e9340515b63" => :catalina
sha256 "b81ec3bb2734293ed39d0c336c1c6445b7d87032994e642ea7ff5b195fbe16e5" => :mojave
sha256 "d7db72ec3bbb3f568e9ba432f5b146eb20d15b8a2fc5c4e3f9680d0d27852ce8" => :high_sierra
end
depends_on "cmake" => :build
depends_on "maven" => :build
depends_on "openjdk" => :build
def install
args = std_cmake_args + %w[
-DCMAKE_C_COMPILER=/usr/bin/clang
]
mkdir "build" do
system "cmake", "..", *args
system "cmake", "--build", "."
system "make", "install"
end
end
test do
# Find a pointer out of bounds error
(testpath/"main.c").write <<~EOS
#include <stdlib.h>
int main() {
char *ptr = malloc(10);
char c = ptr[10];
}
EOS
assert_match "VERIFICATION FAILED",
shell_output("#{bin}/cbmc --pointer-check main.c", 10)
end
end
| 27.555556 | 93 | 0.654839 |
331dbe2d6e1e001bb3e359ce01b56548a9ccc4b8 | 1,617 | class Crane < Formula
desc "Tool for interacting with remote images and registries"
homepage "https://github.com/google/go-containerregistry"
url "https://github.com/google/go-containerregistry/archive/v0.6.0.tar.gz"
sha256 "e9d9e9c662f6c9140083eb884bec9f2fc94554bb1d989aa6846e9cf2f69a27d5"
license "Apache-2.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "3be0fec76833c21b2fdddd3c6003a96e5578aad99638416a34c6285f91621db4"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "1ee6c8238a5e4a08025a0b89f7deb81d1b92dbad227c718b8188cc5524769aef"
sha256 cellar: :any_skip_relocation, monterey: "472727f4fe3ab1afc3abada8d197e8310648c240216e4e80031cff41a7ea6f10"
sha256 cellar: :any_skip_relocation, big_sur: "b95a968ba856bdb163b8a55bfe5d88308c3fc5f68e0f732e12fba0a947fd7496"
sha256 cellar: :any_skip_relocation, catalina: "622eb564e0cf74344e570722f144032caf795b0f65be6e897046add7abcf4ccf"
sha256 cellar: :any_skip_relocation, mojave: "41a0966f974b546da05413b9d16632e32852d8109a247d4cccfefe8c6bf03b72"
sha256 cellar: :any_skip_relocation, x86_64_linux: "63c3a660eeac1a72c066eb8f9cc4dd40b542686f247d031b4cda84830411b3bd"
end
depends_on "go" => :build
def install
system "go", "build", *std_go_args, "-ldflags",
"-s -w -X github.com/google/go-containerregistry/cmd/crane/cmd.Version=#{version}",
"./cmd/crane"
end
test do
json_output = shell_output("#{bin}/crane manifest gcr.io/go-containerregistry/crane")
manifest = JSON.parse(json_output)
assert_equal manifest["schemaVersion"], 2
end
end
| 50.53125 | 123 | 0.788497 |
d5b1aca0ea20039b70ab77b4172e1b0a3173ff22 | 771 | # frozen_string_literal: true
# extract logic here
class VotesController < ApplicationController
include SessionsHelper
include UsersHelper
before_action :authenticate_user
def new; end
def create
if current_user.active_membership?
@user = current_user
active_vote = @user.active_vote
@vote = Vote.find_or_create_by(user_id: params[:user_id], proposal_id: params[:proposal_id])
@user.clear_active_vote_if_exists
if @vote != active_vote
@vote.comment = params[:comment] ? params[:comment] : nil
@vote.active = true
@vote.save
end
end
redirect_to proposals_path
end
def update; end
def delete; end
private
def vote_params
params.require(:proposal_id, :user_id)
end
end
| 22.028571 | 98 | 0.701686 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.