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 = 'marcel@vernix.org' 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' =>'guolei_coder@126.com' } 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' => 'ekscrypto@gmail.com' } 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" => "john.doe@example.org", "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" => "john.doe@example.org", "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 "python@3.10" => :build depends_on "brotli" depends_on "c-ares" depends_on "icu4c" depends_on "libnghttp2" depends_on "libuv" depends_on "openssl@1.1" 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["openssl@1.1"].include} --shared-openssl-libpath=#{Formula["openssl@1.1"].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 = ['open-source@toptal.com'] 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{info@refinerycms.com} 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 = 'azrubyteam@microsoft.com' 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 <mikel@test.lindsaar.net>" result = "To: Mikel =?UTF-8?B?TGluZHPjgYLjgYJy?= <mikel@test.lindsaar.net>\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あ <ada@test.lindsaar.net>" result = "To: =?UTF-8?B?44GCZOOBgg==?= <ada@test.lindsaar.net>\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 <mikel@test.lindsaar.net>", "あdあ <ada@test.lindsaar.net>"] result = "To: Mikel =?UTF-8?B?TGluZHPjgYLjgYJy?= <mikel@test.lindsaar.net>, \r\n\s=?UTF-8?B?44GCZOOBgg==?= <ada@test.lindsaar.net>\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 áëô îü <extended@example.net>"] result = "To: Foo =?UTF-8?B?w6HDq8O0?= =?UTF-8?B?IMOuw7w=?= <extended@example.net>\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 <mikel@test.lindsaar.net>", "あdあ <ada@test.lindsaar.net>"]) result = "#{field}: Mikel =?UTF-8?B?TGluZHPjgYLjgYJy?= <mikel@test.lindsaar.net>, \r\n\s=?UTF-8?B?44GCZOOBgg==?= <ada@test.lindsaar.net>\r\n" mail[field].encoded.should eq result end end it "should handle groups" do mail = Mail.new mail.charset = 'utf-8' mail.to = "test1@lindsaar.net, group: test2@lindsaar.net, me@lindsaar.net;" result = "To: test1@lindsaar.net, \r\n\sgroup: test2@lindsaar.net, \r\n\sme@lindsaar.net;\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" <test1@lindsaar.net>, group: "あdあ" <test2@lindsaar.net>, me@lindsaar.net;' result = "To: =?UTF-8?B?TWlrZWwgTGluZHPjgYLjgYJy?= <test1@lindsaar.net>, \r\n\sgroup: =?UTF-8?B?44GCZOOBgg==?= <test2@lindsaar.net>, \r\n\sme@lindsaar.net;\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 <mikel@test.lindsaar.net>' mail[:to].encoded.should eq %{To: Mikel Lindsaar <mikel@test.lindsaar.net>\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" <mikel@test.lindsaar.net>' mail[:to].encoded.should eq %{To: Mikel Lindsaar <mikel@test.lindsaar.net>\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 <mikel@test.lindsaar.net>" mail[:to].encoded.should eq %{To: "Mikel @ me Lindsaar" <mikel@test.lindsaar.net>\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" <mikel@test.lindsaar.net>} mail[:to].encoded.should eq %{To: "Mikel @ me Lindsaar" <mikel@test.lindsaar.net>\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 <mikel@test.lindsaar.net>" 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?= <mikel@test.lindsaar.net>\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 <mikel@test.lindsaar.net>", "あdあ <ada@test.lindsaar.net>"] 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?= <mikel@test.lindsaar.net>, \r\n\s=?ISO-8859-1?B?44GCZOOBgg==?= <ada@test.lindsaar.net>\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 <mikel@test.lindsaar.net>", "あdあ <ada@test.lindsaar.net>"] 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?= <mikel@test.lindsaar.net>, \r\n\s=?ISO-8859-1?B?44GCZOOBgg==?= <ada@test.lindsaar.net>\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: 'zoo@portland.zoo' 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 'zoo@portland.zoo' 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" => 'jordan@howlett.io' } 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
79dd98ff052d95b63255d7a3c3286e8d73ac7c27
6,575
module BlobHelper def highlighter(blob_name, blob_content, nowrap: false) Gitlab::Highlight.new(blob_name, blob_content, nowrap: nowrap) end def highlight(blob_name, blob_content, nowrap: false, plain: false) Gitlab::Highlight.highlight(blob_name, blob_content, nowrap: nowrap, plain: plain) end def no_highlight_files %w(credits changelog news copying copyright license authors) end def edit_blob_link(project = @project, ref = @ref, path = @path, options = {}) return unless current_user blob = project.repository.blob_at(ref, path) rescue nil return unless blob && blob_text_viewable?(blob) from_mr = options[:from_merge_request_id] link_opts = {} link_opts[:from_merge_request_id] = from_mr if from_mr edit_path = namespace_project_edit_blob_path(project.namespace, project, tree_join(ref, path), link_opts) if !on_top_of_branch?(project, ref) button_tag "编辑", class: "btn disabled has-tooltip btn-file-option", title: "你只能在分支上修改编辑文件", data: { container: 'body' } elsif can_edit_blob?(blob, project, ref) link_to "编辑", edit_path, class: 'btn btn-file-option' elsif can?(current_user, :fork_project, project) continue_params = { to: edit_path, notice: edit_in_new_fork_notice, notice_now: edit_in_new_fork_notice_now } fork_path = namespace_project_forks_path(project.namespace, project, namespace_key: current_user.namespace.id, continue: continue_params) link_to "编辑", fork_path, class: 'btn btn-file-option', method: :post end end def modify_file_link(project = @project, ref = @ref, path = @path, label:, action:, btn_class:, modal_type:) return unless current_user blob = project.repository.blob_at(ref, path) rescue nil return unless blob if !on_top_of_branch?(project, ref) button_tag label, class: "btn btn-#{btn_class} disabled has-tooltip", title: "你只能在分支上#{action}文件", data: { container: 'body' } elsif blob.lfs_pointer? button_tag label, class: "btn btn-#{btn_class} disabled has-tooltip", title: "不能使用网页界面#{action}存储在 LFS 上的文件", data: { container: 'body' } elsif can_edit_blob?(blob, project, ref) button_tag label, class: "btn btn-#{btn_class}", 'data-target' => "#modal-#{modal_type}-blob", 'data-toggle' => 'modal' elsif can?(current_user, :fork_project, project) continue_params = { to: request.fullpath, notice: edit_in_new_fork_notice + "请重新尝试#{action}此文件。", notice_now: edit_in_new_fork_notice_now } fork_path = namespace_project_forks_path(project.namespace, project, namespace_key: current_user.namespace.id, continue: continue_params) link_to label, fork_path, class: "btn btn-#{btn_class}", method: :post end end def replace_blob_link(project = @project, ref = @ref, path = @path) modify_file_link( project, ref, path, label: "替换", action: "replace", btn_class: "default", modal_type: "upload" ) end def delete_blob_link(project = @project, ref = @ref, path = @path) modify_file_link( project, ref, path, label: "删除", action: "delete", btn_class: "remove", modal_type: "remove" ) end def can_edit_blob?(blob, project = @project, ref = @ref) !blob.lfs_pointer? && can_edit_tree?(project, ref) end def leave_edit_message "离开编辑模式?\n所有未保存的修改都会丢失。" end def editing_preview_title(filename) if Gitlab::MarkupHelper.previewable?(filename) '预览' else '预览修改' end end # Return an image icon depending on the file mode and extension # # mode - File unix mode # mode - File name def blob_icon(mode, name) icon("#{file_type_icon_class('file', mode, name)} fw") end def blob_text_viewable?(blob) blob && blob.text? && !blob.lfs_pointer? end def blob_size(blob) if blob.lfs_pointer? blob.lfs_size else blob.size end end # SVGs can contain malicious JavaScript; only include whitelisted # elements and attributes. Note that this whitelist is by no means complete # and may omit some elements. def sanitize_svg(blob) blob.data = Gitlab::Sanitizers::SVG.clean(blob.data) blob end # If we blindly set the 'real' content type when serving a Git blob we # are enabling XSS attacks. An attacker could upload e.g. a Javascript # file to a Git repository, trick the browser of a victim into # downloading the blob, and then the 'application/javascript' content # type would tell the browser to execute the attacker's Javascript. By # overriding the content type and setting it to 'text/plain' (in the # example of Javascript) we tell the browser of the victim not to # execute untrusted data. def safe_content_type(blob) if blob.text? 'text/plain; charset=utf-8' elsif blob.image? blob.content_type else 'application/octet-stream' end end def cached_blob? stale = stale?(etag: @blob.id) # The #stale? method sets cache headers. # Because we are opionated we set the cache headers ourselves. response.cache_control[:public] = @project.public? if @ref && @commit && @ref == @commit.id # This is a link to a commit by its commit SHA. That means that the blob # is immutable. The only reason to invalidate the cache is if the commit # was deleted or if the user lost access to the repository. response.cache_control[:max_age] = Blob::CACHE_TIME_IMMUTABLE else # A branch or tag points at this blob. That means that the expected blob # value may change over time. response.cache_control[:max_age] = Blob::CACHE_TIME end response.etag = @blob.id !stale end def licenses_for_select return @licenses_for_select if defined?(@licenses_for_select) licenses = Licensee::License.all @licenses_for_select = { 常用: licenses.select(&:featured).map { |license| [license.name, license.key] }, 其他: licenses.reject(&:featured).map { |license| [license.name, license.key] } } end def gitignore_names return @gitignore_names if defined?(@gitignore_names) @gitignore_names = { Global: Gitlab::Gitignore.global.map { |gitignore| { name: gitignore.name } }, # Note that the key here doesn't cover it really Languages: Gitlab::Gitignore.languages_frameworks.map{ |gitignore| { name: gitignore.name } } } end end
33.207071
143
0.675589
1d350ece3cdb81eceeeb596f5482383e18896c8f
1,025
class Staff::Base < ApplicationController before_action :authorize before_action :check_account before_action :check_timeout private def current_staff_member if session[:staff_member_id] @current_staff_member ||= StaffMember.find_by(id: session[:staff_member_id]) end end private def authorize unless current_staff_member flash.alert = "職員としてログインしてください。" redirect_to :staff_login end end private def check_account if current_staff_member && !current_staff_member.active? session.delete(:staff_member_id) flash.alert = "アカウントが無効になりました" redirect_to :staff_login end end TIMEOUT = 60.minutes private def check_timeout if current_staff_member if session[:last_access_time] >= TIMEOUT.ago session[:last_access_time] = Time.current else session.delete(:staff_member_id) flash.alert = "セッションがタイムアウトしました。" redirect_to :staff_login end end end helper_method :current_staff_member end
23.837209
82
0.717073
f8488972f8fac44d79f8a2b52491bd8f7e685090
872
# frozen_string_literal: true require_relative 'lib/chinese_remainder' input = ARGF.readlines.map(&:chomp) class Bus attr_accessor :id, :departure def initialize(id) @id = id.to_i @departure = @id end end # Part 1 start_time = input[0].to_i buses = input[1].split(/,/).filter_map do |bus_id| Bus.new(bus_id) unless bus_id == 'x' end while true behind_schedule = buses.reject { |bus| bus.departure >= start_time } break if behind_schedule.empty? behind_schedule.map { |bus| bus.departure += bus.id } end first_bus = buses.min_by(&:departure) p (first_bus.departure - start_time) * first_bus.id # => 174 # Part 2 departure_offsets = [] input[1].split(/,/).filter_map.with_index do |bus_id, index| departure_offsets << index * -1 unless bus_id == 'x' end p ChineseRemainder.solve(buses.map(&:id), departure_offsets) # => 780601154795940
20.27907
81
0.705275
0879fce69ca1a808b636546c7ee66e50e30df5e4
1,208
require 'test_helper' class Accounts::AccountCreatedEventTest < ActiveSupport::TestCase def test_create account = FactoryBot.build_stubbed(:simple_buyer, id: 1, provider_account_id: 2) event = Accounts::AccountCreatedEvent.create(account, user) assert event assert_equal event.account, account assert_equal event.provider, account.provider_account assert_equal event.user, user assert_equal event.metadata[:provider_id], 2 end def test_provider # master for master master = master_account event = Accounts::AccountCreatedEvent.create(master, user) assert_equal event.provider, master # provider for master provider = FactoryBot.build_stubbed(:simple_provider, provider_account: master) event = Accounts::AccountCreatedEvent.create(provider, user) assert_equal event.provider, master # buyer for provider buyer = FactoryBot.build_stubbed(:simple_buyer, provider_account: provider) event = Accounts::AccountCreatedEvent.create(buyer, user) assert_equal event.provider, provider end private def user @_user ||= FactoryBot.build_stubbed(:simple_user) end end
28.093023
83
0.725166
f7308c1b416112500db62f381a983a382e2b94f6
1,463
#-- encoding: UTF-8 #-- copyright # OpenProject is a project management system. # Copyright (C) 2012-2017 the OpenProject Foundation (OPF) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2017 Jean-Philippe Lang # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See doc/COPYRIGHT.rdoc for more details. #++ class CustomActions::Conditions::Status < CustomActions::Conditions::Base def self.key :status end private def associated ::Status .select(:id, :name) .order(:name) .map { |u| [u.id, u.name] } end end
32.511111
91
0.734108
62178e3c3b76481dbc674197734f74f44163b5d4
5,308
#== # Copyright (C) 2008 James S Urquhart # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. #++ class ListItemsController < ApplicationController before_filter :grab_page before_filter :grab_list cache_sweeper :page_sweeper, :only => [:create, :update, :destroy, :status] # GET /list_items # GET /list_items.xml def index if params[:completed] conds = ['completed_on NOT NULL'] else conds = nil end @list_items = @list.list_items.find(:all, :conditions => conds, :offset => params[:offset], :limit => params[:limit]) respond_to do |format| format.html # index.html.erb format.js format.xml { render :xml => @list_items } end end # GET /list_items/1 # GET /list_items/1.xml def show @list_item = @list.list_items.find(params[:id]) respond_to do |format| format.html # show.html.erb format.js format.xml { render :xml => @list_item } end end # GET /list_items/new # GET /list_items/new.xml def new return error_status(true, :cannot_create_listitem) unless (ListItem.can_be_created_by(@logged_user, @list)) @list_item = @list.list_items.build respond_to do |format| format.html # new.html.erb format.xml { render :xml => @list_item } end end # GET /list_items/1/edit def edit @list_item = @list.list_items.find(params[:id]) return error_status(true, :cannot_edit_listitem) unless (@list_item.can_be_edited_by(@logged_user)) end # POST /list_items # POST /list_items.xml def create return error_status(true, :cannot_create_listitem) unless (ListItem.can_be_created_by(@logged_user, @list)) @list_item = @list.list_items.build(params[:list_item]) @list_item.created_by = @logged_user respond_to do |format| if @list_item.save flash[:notice] = 'ListItem was successfully created.' format.html { redirect_to(@list_item) } format.js format.xml { render :xml => @list_item, :status => :created, :location => page_list_list_item_path(:page_id => @page.id, :list_id => @list.id, :id => @list_item.id) } else format.html { render :action => "new" } format.js format.xml { render :xml => @list_item.errors, :status => :unprocessable_entity } end end end # PUT /list_items/1 # PUT /list_items/1.xml def update @list_item = @list.list_items.find(params[:id]) return error_status(true, :cannot_edit_listitem) unless (@list_item.can_be_edited_by(@logged_user)) @list_item.updated_by = @logged_user respond_to do |format| if @list_item.update_attributes(params[:list_item]) flash[:notice] = 'ListItem was successfully updated.' format.html { redirect_to(@list_item) } format.js format.xml { head :ok } else format.html { render :action => "edit" } format.js format.xml { render :xml => @list_item.errors, :status => :unprocessable_entity } end end end # DELETE /list_items/1 # DELETE /list_items/1.xml def destroy @list_item = @list.list_items.find(params[:id]) return error_status(true, :cannot_edit_listitem) unless (@list_item.can_be_deleted_by(@logged_user)) @list_item.updated_by = @logged_user @list_item.destroy respond_to do |format| format.html { redirect_to(list_items_url) } format.js format.xml { head :ok } end end # PUT /list_items/1 def status @list_item = @list.list_items.find(params[:id]) return error_status(true, :cannot_edit_listitem) unless (@list_item.can_be_completed_by(@logged_user)) @list_item.set_completed(params[:list_item][:completed] == 'true', @logged_user) @list_item.position = @list.list_items.length @list_item.save respond_to do |format| format.html { redirect_to(list_items_url) } format.js format.xml { head :ok } end end protected def grab_list begin @list = @page.lists.find(params[:list_id]) rescue ActiveRecord::RecordNotFound error_status(true, :cannot_find_list) return false end true end end
30.682081
175
0.666918
e8c13d0d158033a7a32ef213811149d40e6d09bf
785
module Kuby::KubeDB::DSL::Catalog::V1alpha1 class RedisVersionSpec < ::KubeDSL::DSLObject value_fields :deprecated, :version object_field(:exporter) { Kuby::KubeDB::DSL::Catalog::V1alpha1::RedisVersionExporter.new } object_field(:db) { Kuby::KubeDB::DSL::Catalog::V1alpha1::RedisVersionDatabase.new } object_field(:pod_security_policies) { Kuby::KubeDB::DSL::Catalog::V1alpha1::RedisVersionPodSecurityPolicy.new } def serialize {}.tap do |result| result[:deprecated] = deprecated result[:version] = version result[:exporter] = exporter.serialize result[:db] = db.serialize result[:podSecurityPolicies] = pod_security_policies.serialize end end def kind_sym :redis_version_spec end end end
34.130435
116
0.696815
380a18818ab068d903319df2012dcd7f3bbff204
646
# frozen_string_literal: true class Projects::GrafanaApiController < Projects::ApplicationController include RenderServiceResults include MetricsDashboard def proxy result = ::Grafana::ProxyService.new( project, params[:datasource_id], params[:proxy_path], query_params.to_h ).execute return continue_polling_response if result.nil? return error_response(result) if result[:status] == :error success_response(result) end private def metrics_dashboard_params params.permit(:embedded, :grafana_url) end def query_params params.permit(:query, :start, :end, :step) end end
20.83871
70
0.724458
08ced4a9b946b25d6ed88238c52aa08e7fa41cd7
687
# frozen_string_literal: true # == Schema Information # # Table name: player_histories # # id :bigint not null, primary key # kit_no :integer # ovr :integer # recorded_on :date # value :integer # created_at :datetime not null # updated_at :datetime not null # player_id :bigint # # Indexes # # index_player_histories_on_player_id (player_id) # FactoryBot.define do factory :player_history do recorded_on { Date.new } ovr { Faker::Number.between(from: 50, to: 90) } value { Faker::Number.between(from: 50_000, to: 200_000_000) } kit_no { Faker::Number.between(from: 1, to: 99) } player end end
22.9
66
0.63901
bbf3fe32a3235e651adb80d6b7d3f6bb9240a77c
416
# frozen_string_literal: true module InvisibleCollector module Model class Debit < AbstractModel attr_accessor :number attr_accessor :date attr_accessor :gross_total def initialize(options = {}) options = options.with_indifferent_access @number = options[:number] @date = options[:date] @gross_total = options[:gross_total] end end end end
21.894737
49
0.661058
bf42fdbda0b8ae860419e94fc90595636837feb5
280
module Pageflow class SubmitFileToZencoderJob @queue = :default extend StateMachineJob def self.perform_with_result(file, options, api = ZencoderApi.instance) file.job_id = api.create_job(file.output_definition) file.save! :ok end end end
18.666667
75
0.703571
216fb33d2afb7fa24387ee0435673033aa28cd90
12,194
require 'puppet/parameter/value_collection' require 'pathname' class Puppet::Type::Acl # Ace is an Access Control Entry for use with the Access # Control List (ACL) type. ACEs contain information about # the trustee, the rights, and on some systems how they are # inherited and propagated to subtypes. class Ace < Hash # < Hash is due to a bug with how Puppet::Resource.to_manifest # does not work through quite the same code and needs to # believe this custom object is a Hash. If issues are later # found, this should be reviewed. require Pathname.new(__FILE__).dirname + '../../../' + 'puppet/type/acl/rights' attr_reader :identity attr_reader :rights attr_reader :perm_type attr_reader :child_types attr_reader :affects attr_reader :is_inherited attr_reader :mask def initialize(permission_hash, provider = nil) @provider = provider id = permission_hash['identity'] id = permission_hash['id'] if id.nil? || id.empty? self.identity = id self.id = permission_hash['id'] @mask = permission_hash['mask'] self.rights = permission_hash['rights'] self.perm_type = permission_hash['perm_type'] if permission_hash['type'] Puppet.deprecation_warning('Permission `type` is deprecated and has been replaced with perm_type for allow or deny') if permission_hash['perm_type'] && permission_hash['type'] != permission_hash['perm_type'] raise ArgumentError, "Can not accept both `type` => #{permission_hash['type']} and `perm_type` => #{permission_hash['perm_type']}" end self.perm_type = permission_hash['type'] end self.child_types = permission_hash['child_types'] self.affects = permission_hash['affects'] @is_inherited = permission_hash['is_inherited'] || false @hash = nil end def validate(value, *allowed_values) validator = Puppet::Parameter::ValueCollection.new validator.newvalues(*allowed_values) validator.validate(value) value end def inherited? is_inherited end def convert_to_symbol(value) return nil if value.nil? || value.empty? return value if value.is_a?(Symbol) value.downcase.to_sym end def validate_non_empty(name, value) if value.nil? || value == '' raise ArgumentError, "A non-empty #{name} must be specified." end if value.is_a?(Array) && value.count.zero? raise ArgumentError, "Value for #{name} should have least one element in the array." end value end def validate_array(name, values) raise ArgumentError, "Value for #{name} should be an array. Perhaps try ['#{values}']?" unless values.is_a?(Array) values end def validate_individual_values(values, *allowed_values) values.each do |value| validate(value, *allowed_values) end values end def convert_to_symbols(values) value_syms = [] values.each do |value| value_syms << convert_to_symbol(value) end value_syms end def convert_from_symbols(symbols) values = [] symbols.each do |value| values << value.to_s end values end def ensure_rights_order @rights.sort_by! { |r| Puppet::Type::Acl::Rights.new(r).order } end def ensure_rights_values_compatible if @rights.include?(:mask_specific) && rights.count != 1 raise ArgumentError, "In each ace, when specifying rights, if you include 'mask_specific', it should be without anything else e.g. rights => ['mask_specific']. Please decide whether 'mask_specific' or predetermined rights and correct the manifest. Reference: #{inspect}" # rubocop:disable Metrics/LineLength end if @rights.include?(:full) && rights.count != 1 Puppet.warning("In each ace, when specifying rights, if you include 'full', it should be without anything else e.g. rights => ['full']. Please remove the extraneous rights from the manifest to remove this warning. Reference: #{inspect}") # rubocop:disable Metrics/LineLength @rights = [:full] end if @rights.include?(:modify) && rights.count != 1 # rubocop:disable Style/GuardClause Changing this to a guard clause makes the line long and unreadable Puppet.warning("In each ace, when specifying rights, if you include 'modify', it should be without anything else e.g. rights => ['modify']. Please remove the extraneous rights from the manifest to remove this warning. Reference: #{inspect}") # rubocop:disable Metrics/LineLength @rights = [:modify] end end def ensure_mask_when_mask_specific if @rights.include?(:mask_specific) && (@mask.nil? || @mask.empty?) # rubocop:disable Style/GuardClause Changing this to a guard clause makes the line long and unreadable raise ArgumentError, "If you specify rights => ['mask_specific'], you must also include mask => 'value'. Reference: #{inspect}" end end def ensure_unique_values(values) if values.is_a?(Array) return values.uniq end values end def ensure_none_or_self_only_sync return if @child_types.nil? || @affects.nil? return if @child_types == :none && @affects == :self_only return unless @child_types == :none || @affects == :self_only if @child_types == :none && (@affects != :all && @affects != :self_only) Puppet.warning("If child_types => 'none', affects => value will be ignored. Please remove affects or set affects => 'self_only' to remove this warning. Reference: #{inspect}") end @affects = :self_only if @child_types == :none if @affects == :self_only && (@child_types != :all && @child_types != :none) Puppet.warning("If affects => 'self_only', child_types => value will be ignored. Please remove child_types or set child_types => 'none' to remove this warning. Reference: #{inspect}") end @child_types = :none if @affects == :self_only end def identity=(value) @identity = validate_non_empty('identity', value) @hash = nil end def id if @id.nil? || @id.empty? if @identity && @provider && @provider.respond_to?(:get_account_id) @id = @provider.get_account_id(@identity) end end @id end def id=(value) @id = value @hash = nil end def rights=(value) @rights = ensure_unique_values( convert_to_symbols( validate_individual_values( validate_array( 'rights', validate_non_empty('rights', value), ), :full, :modify, :write, :read, :execute, :mask_specific ), ), ) ensure_rights_order ensure_rights_values_compatible ensure_mask_when_mask_specific if @rights.include?(:mask_specific) @hash = nil end def mask=(value) @mask = value @hash = nil end def perm_type=(value) @perm_type = convert_to_symbol(validate(value || :allow, :allow, :deny)) @hash = nil end def child_types=(value) @child_types = convert_to_symbol(validate(value || :all, :all, :objects, :containers, :none)) ensure_none_or_self_only_sync @hash = nil end def affects=(value) @affects = convert_to_symbol(validate(value || :all, :all, :self_only, :children_only, :self_and_direct_children_only, :direct_children_only)) ensure_none_or_self_only_sync @hash = nil end def get_comparison_ids(other = nil) ignore_other = true id_has_value = false other_id_has_value = false other_id = nil unless other.nil? ignore_other = false other_id_has_value = true unless other.id.nil? || other.id.empty? end id_has_value = true unless id.nil? || id.empty? if id_has_value && (ignore_other || other_id_has_value) id = self.id other_id = other.id unless ignore_other elsif @provider && @provider.respond_to?(:get_account_name) id = @provider.get_account_name(@identity) other_id = @provider.get_account_name(other.identity) unless ignore_other else id = @identity other_id = other.identity unless ignore_other end [id, other_id] end # This ensures we are looking at the same ace even if the # rights are different. Contextually we have two ace objects # and we are trying to determine if they are the same ace or # different given all of the different compare points. # # @param other [Ace] The ace that we are comparing to. # @return [Boolean] true if all points are equal def same?(other) return false unless other.is_a?(Ace) account_ids = get_comparison_ids(other) account_ids[0] == account_ids[1] && @child_types == other.child_types && @affects == other.affects && @is_inherited == other.is_inherited && @perm_type == other.perm_type end # This ensures we are looking at the same ace with the same # rights. We want to know if the two aces are equal on all # important data points. # # @param other [Ace] The ace that we are comparing to. # @return [Boolean] true if all points are equal def ==(other) return false unless other.is_a?(Ace) same?(other) && @rights == other.rights end alias eql? == def hash get_comparison_ids[0].hash ^ @rights.hash ^ @perm_type.hash ^ @child_types.hash ^ @affects.hash ^ @is_inherited.hash end def to_hash return @hash if @hash ace_hash = {} ace_hash['identity'] = identity ace_hash['rights'] = convert_from_symbols(rights) ace_hash['mask'] = mask if rights == [:mask_specific] && !mask.nil? ace_hash['perm_type'] = perm_type unless perm_type == :allow || perm_type.nil? ace_hash['child_types'] = child_types unless child_types == :all || child_types == :none || child_types.nil? ace_hash['affects'] = affects unless affects == :all || affects.nil? ace_hash['is_inherited'] = is_inherited if is_inherited @hash = ace_hash @hash end # The following methods: keys, values, [](key) make # `puppet resource acl somelocation` believe that # this is actually a Hash and can pull the values # from this object. def keys to_hash.keys end def values to_hash.values end def [](key) to_hash[key] end def inspect hash = to_hash return_value = hash.keys.map { |key| key_value = hash[key] if key_value.is_a? Array "#{key} => #{key_value}" else "#{key} => '#{key_value}'" end }.join(', ') "\n { #{return_value} }" end alias to_s inspect # added to support Ruby 2.3 which serializes Hashes differently when # writing YAML than previous Ruby versions, which can break the last # run report or corrective changes reports due to attempts to # serialize the attached provider def encode_with(coder) # produce a set of plain key / value pairs by removing the "tag" # by setting it to nil, producing YAML serialization like # "---\nidentity: Administrators\nrights:\n- full\n" # with the tag set to its default value, serialization appears like # "--- !ruby/object:Puppet::Type::Acl::Ace\nidentity: Administrators\nrights:\n- full\n" coder.represent_map nil, to_hash # rubocop:disable Metrics/LineLength # without this method implemented, serialization varies based on Ruby version like: # Ruby 2.3 # "--- !ruby/hash-with-ivars:Puppet::Type::Acl::Ace\nelements: {}\nivars:\n :@provider: \n :@identity: Administrators\n :@hash: \n :@id: S-32-12-0\n :@mask: '2023422'\n :@rights:\n - :full\n :@perm_type: :allow\n :@child_types: :all\n :@affects: :all\n :@is_inherited: false\n" # Ruby 2.1.9 # "--- !ruby/hash:Puppet::Type::Acl::Ace {}\n" # rubocop:enable Metrics/LineLength end end end
34.156863
315
0.644169
4aa53081f7b4b00796f13ee6cd09d1599a3e51fa
1,116
#-------------------------- # # @class Memberships::BecomeFormerIndividualMemberActions # # @desc Responsibility: Do all the things that need to be done when an individual membership # enters the renewal grace period # # # @author Ashley Engelund (ashley.engelund@gmail.com weedySeaDragon @ github) # @date 4/1/21 # #-------------------------------------------------------------------------------------------------- module Memberships class BecomeFormerIndividualMemberActions < MembershipActions LOGMSG_MEMBERSHIP_FORMER = 'Membership now a former membership' def self.other_keyword_args_valid?(_other_keyword_args) true end # Set membership to false # If we should send email: # send email to the user saying they are now a former member and have to re-apply # def self.accomplish_actions(user, _send_email: SEND_EMAIL_DEFAULT, **other_keyword_args) user.update!(member: false) # MemberMailer.membership_now_is_former(user).deliver if send_email true end def self.log_message_success LOGMSG_MEMBERSHIP_FORMER end end end
27.219512
99
0.655018
edfc52599e73e76439887ca33b0d7c65c1305129
38
class Bucket < ActiveRecord::Base end
12.666667
33
0.789474
1859cc89de9c5f3a4f526f6938b7610cb9b6ca71
781
class FightClubApp configure :development do set :database, 'sqlite:///dev.db' set :show_exceptions, true end configure :production do db = URI.parse(ENV['DATABASE_URL'] || 'postgres:///localhost/mydb') ActiveRecord::Base.establish_connection( :adapter => db.scheme == 'postgres' ? 'postgresql' : db.scheme, :host => db.host, :username => db.user, :password => db.password, :database => db.path[1..-1], :encoding => 'utf8' ) end configure do if ENV["REDISCLOUD_URL"] uri = URI.parse(ENV["REDISCLOUD_URL"]) $redis = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password) # else # raise "Please set the REDISCLOUD_URL env variable. See the README for more information." end end end
27.892857
96
0.640205
18d63306159f9304fa4488ed8e97d9dcbc7913df
113
module AthenaHealth class AnalyteCollection < BaseCollection attribute :analytes, Array[Analyte] end end
18.833333
42
0.787611
613dfd9d7f4076a8d20855a1a5f73785d77cadae
1,330
# Clean this up. Have it assume there's an install? $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require "panini" grammar = Panini::Grammar.new # ================ # = Nonterminals = # ================ expression = grammar.add_nonterminal("EXPR") term = grammar.add_nonterminal("TERM") factor = grammar.add_nonterminal("FACT") identifier = grammar.add_nonterminal("ID") number = grammar.add_nonterminal("NUM") # ============= # = Terminals = # ============= expression.add_production([term, '+', term]) expression.add_production([term, '-', term]) expression.add_production([term]) term.add_production([factor, '*', term]) term.add_production([factor, '/', term]) term.add_production([factor]) factor.add_production([identifier]) factor.add_production([number]) factor.add_production(['(', expression, ')']) ('a'..'z').each do |v| identifier.add_production([v]) end # It would be cool to have a way to create a random number. (0..100).each do |n| number.add_production([n]) end # =============================================== # = Choose a strategy and create some sentences = # =============================================== deriver = Panini::DerivationStrategy::RandomDampened.new(grammar) 10.times do puts "#{deriver.sentence.join(' ')}" end
25.576923
66
0.631579
267c7b65edf69ad1611619cfa58596f3865b7eda
1,962
# # Be sure to run `pod lib lint FlexLib.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 = 'FlexLib' s.version = '1.8.5' s.summary = 'An obj-c flex layout framework for IOS' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC It's a layout framework based on yoga engine. The main purpose is to provide easy and fast usage. DESC s.homepage = 'https://github.com/zhenglibao/FlexLib' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { '798393829@qq.com' => '798393829@qq.com' } s.source = { :git => 'https://github.com/zhenglibao/FlexLib.git', :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '8.0' s.source_files = 'FlexLib/Classes/**/*' s.resource_bundles = { 'FlexLib' => ['FlexLib/Assets/*'] } # s.frameworks = 'UIKit', 'MapKit' s.dependency 'Yoga', '1.6.0' s.library = 'xml2' s.xcconfig = { 'HEADER_SEARCH_PATHS' => '/usr/include/libxml2' } #s.private_header_files = 'FlexLib/Classes/private/*.h' #s.public_header_files = 'FlexLib/Classes/*.h' non_arc_files = 'FlexLib/Classes/GDataXMLNode.{h,m}' s.exclude_files = non_arc_files s.subspec 'no-arc' do |sna| sna.requires_arc = false sna.source_files = non_arc_files end end
35.035714
102
0.650866
11064409a858388e897b13a788f4a3cd8c0b6021
401
class Api::UsersController < ApplicationController def index @users = User.all end def create @user = User.new(user_params) if @user.save sign_in!(@user) render 'api/users/show' else render( json: @user.errors.full_messages, status: 422 ) end end def user_params params.require(:user).permit(:username, :password) end end
16.708333
54
0.618454
f85eeadd90a59a39d63ededd3b90284f852175b7
496
# Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. Dummy::Application.config.secret_token = 'b60a14ba9bc5e860fb35696b5cd5fb3485b4b57b9739e65c6ee479b2ba290b8a3f89019349b6d3361a22025fcafbd88f7b4bad7b8f5e08f6170c404c1231648b'
62
171
0.832661
bf855c37e36853e2b0172e7ff69555ecd5ab00a7
5,273
# # Be sure to run `pod spec lint WalrusKit.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see https://guides.cocoapods.org/syntax/podspec.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |spec| # ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # These will help people to find your library, and whilst it # can feel like a chore to fill in it's definitely to your advantage. The # summary should be tweet-length, and the description more in depth. # spec.name = "WalrusKit" spec.version = "0.0.3" spec.summary = "Design system by Delivery Club" # 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! spec.description = <<-DESC In Delivery Club we desided to create Design system named Walrus. We want to share with you what we've got so far. DESC spec.homepage = "https://github.com/delivery-club/WalrusKit" # spec.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif" # ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Licensing your code is important. See https://choosealicense.com for more info. # CocoaPods will detect a license file if there is a named LICENSE* # Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'. # spec.license = { :type => "MIT", :file => "FILE_LICENSE" } # ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Specify the authors of the library, with email addresses. Email addresses # of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also # accepts just a name if you'd rather not provide an email address. # # Specify a social_media_url where others can refer to, for example a twitter # profile URL. # spec.author = { "Aleksandr Anosov" => "al.anosov@corp.mail.ru" } # Or just: spec.author = "Aleksandr Anosov" # spec.authors = { "Aleksandr Anosov" => "al.anosov@corp.mail.ru" } # spec.social_media_url = "https://twitter.com/Aleksandr Anosov" # ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # If this Pod runs only on iOS or OS X, then specify the platform and # the deployment target. You can optionally include the target after the platform. # spec.platform = :ios spec.platform = :ios, "12.2" # When using multiple platforms # spec.ios.deployment_target = "5.0" # spec.osx.deployment_target = "10.7" # spec.watchos.deployment_target = "2.0" # spec.tvos.deployment_target = "9.0" # ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Specify the location from where the source should be retrieved. # Supports git, hg, bzr, svn and HTTP. # spec.source = { :git => "https://github.com/delivery-club/WalrusKit.git", :tag => "#{spec.version}" } # ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # CocoaPods is smart about how it includes source code. For source files # giving a folder will include any swift, h, m, mm, c & cpp files. # For header files it will include any header in the folder. # Not including the public_header_files will make all headers public. # spec.source_files = "WalrusKit/**/*.{h,m,swift}" # spec.public_header_files = "Classes/**/*.h" # ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # A list of resources included with the Pod. These are copied into the # target bundle with a build phase script. Anything else will be cleaned. # You can preserve files from being cleaned, please don't preserve # non-essential files like tests, examples and documentation. # # spec.resource = "icon.png" # spec.resources = "Resources/*.png" # spec.preserve_paths = "FilesToSave", "MoreFilesToSave" # ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Link your library with frameworks, or libraries. Libraries do not include # the lib prefix of their name. # # spec.framework = "SomeFramework" # spec.frameworks = "SomeFramework", "AnotherFramework" # spec.library = "iconv" # spec.libraries = "iconv", "xml2" # ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # If your library depends on compiler flags you can set them in the xcconfig hash # where they will only apply to your library. If you depend on other Podspecs # you can include multiple dependencies to ensure it works. # spec.requires_arc = true # spec.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" } # spec.dependency "JSONKit", "~> 1.4" spec.swift_versions = "5" end
37.935252
109
0.604969
6a68365b9c9253a5aefbf85af067acca43bba126
1,298
# frozen_string_literal: true ORIG_ARGV = ARGV.dup require "active_support/core_ext/kernel/reporting" silence_warnings do Encoding.default_internal = Encoding::UTF_8 Encoding.default_external = Encoding::UTF_8 end require "active_support/testing/autorun" require "active_support/testing/method_call_assertions" ENV["NO_RELOAD"] = "1" require "active_support" Thread.abort_on_exception = true # Show backtraces for deprecated behavior for quicker cleanup. ActiveSupport::Deprecation.debug = true # Default to old to_time behavior but allow running tests with new behavior ActiveSupport.to_time_preserves_timezone = ENV["PRESERVE_TIMEZONES"] == "1" # Disable available locale checks to avoid warnings running the test suite. I18n.enforce_available_locales = false class ActiveSupport::TestCase include ActiveSupport::Testing::MethodCallAssertions private # Skips the current run on Rubinius using Minitest::Assertions#skip def rubinius_skip(message = "") skip message if RUBY_ENGINE == "rbx" end # Skips the current run on JRuby using Minitest::Assertions#skip def jruby_skip(message = "") skip message if defined?(JRUBY_VERSION) end end # Contains logic for running in "BUILDKITE" CI environment. # require_relative "../../tools/test_common"
28.217391
75
0.77735
18dc0c05b3feb90b698a090c4a0fc68138aee3c5
681
require 'spec_helper' describe GatherContent::Api::Account, vcr: true do let(:account_id) { 123456 } let(:account) { GatherContent::Api::Account.new(account_id) } describe '.new' do subject { account } it { is_expected.to be_a GatherContent::Api::Account } end describe '#fetch' do subject { account.fetch } it { is_expected.to be_a Hash } end describe "[]" do subject { account } it "returns the data related to the supplied key" do expect(subject["id"]).to eq("123456") expect(subject["name"]).to eq("Example") expect(subject["slug"]).to eq("example") expect(subject["timezone"]).to eq("UTC") end end end
23.482759
63
0.643172
39d94c9a73e4412465daa8ae6b00ab80c7ab4ddb
2,359
lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "blue_cross_pets/version" Gem::Specification.new do |spec| spec.name = "blue_cross_pets" spec.version = BlueCrossPets::VERSION spec.summary = %q{CLI that display Blue Cross UK adoptable dogs/cats} spec.description = %q{Displays all the available dogs/cats listed on the Blue Cross UK website. This is my first gem, so please feel free to add suggestions.} spec.authors = ["'Jessica Gomes-Ng'"] spec.email = ["'jgnpeluso@gmail.com'"] spec.files = ["bin/blue_cross_pets", "lib/blue_cross_pets.rb", "lib/blue_cross_pets/version.rb", "lib/blue_cross_pets/cli.rb", "lib/blue_cross_pets/scraper.rb", "lib/blue_cross_pets/dog.rb", "lib/blue_cross_pets/cat.rb", "lib/blue_cross_pets/pet.rb"] # spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do # `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } # end spec.homepage = "https://github.com/jessicagomesng/blue_cross_pets" spec.license = "MIT" # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host' # to allow pushing to a single host or delete this section to allow pushing to any host. #if spec.respond_to?(:metadata) # spec.metadata["allowed_push_host"] = "https://rubygems.org" # spec.metadata["homepage_uri"] = spec.homepage # spec.metadata["source_code_uri"] = "https://github.com/jessicagomesng/blue_cross_pets" # spec.metadata["changelog_uri"] = "https://github.com/jessicagomesng/blue_cross_pets" #else # raise "RubyGems 2.0 or newer is required to protect against " \ # "public gem pushes." #end # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. spec.bindir = "bin" spec.executables = ["blue_cross_pets"] spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 2.0" spec.add_development_dependency 'rake', '~> 12.3', '>= 12.3.3' spec.add_development_dependency "pry", '~> 0.13.1' spec.add_development_dependency "rspec", '~> 3.9.0' spec.add_dependency "nokogiri", '~> 1.10.9' spec.add_dependency "colorize", '~> 0.8.1' end
51.282609
260
0.686732
919096f739369a15e65301ffd3a6cef45eecdae6
503
# Copyright (c) 2016 Oracle and/or its affiliates. All rights reserved. This # code is released under a tri EPL/GPL/LGPL license. You can use it, # redistribute it and/or modify it under the terms of the: # # Eclipse Public License version 1.0 # GNU General Public License version 2 # GNU Lesser General Public License version 2.1 # The Truffle API's this uses are different from GraalVM 0.12 and Truffle 0.13 tagged main_thread example "Truffle::Interop.eval('application/javascript', '14 + 2')", 16
45.727273
90
0.759443
ac14d7e35b46a70164e534b0d43e3007a61757ac
110
FactoryGirl.define do factory :subject do sequence(:name) { |n| "#{Faker::Lorem.word} #{n}" } end end
18.333333
55
0.627273
e92c783ea37176d1d7de7825e9f97f1e40be40f9
362
class Ruian class Model class Row < Struct.new(:adm_code, :city_code, :city_name, :momc_code, :momc_name, :mop_code, :mop_name, :city_part_code, :city_part_name, :street_name_code, :street_name, :so_type, :e, :o, :o_code, :zip, :gis_y, :gis_x, :valid_from) end end end
36.2
86
0.549724
b9e5cacb697e31b883755f0cd3e71aa7a471e64a
135
# frozen_string_literal: true class VACOLS::Actcode < VACOLS::Record self.table_name = "actcode" self.primary_key = "actckey" end
19.285714
38
0.748148
611226e48adc170aad7f03035b6102dfb9f0e646
653
# frozen_string_literal: true module Mutations module Issues class SetLocked < Base graphql_name 'IssueSetLocked' argument :locked, GraphQL::BOOLEAN_TYPE, required: true, description: 'Whether or not to lock discussion on the issue.' def resolve(project_path:, iid:, locked:) issue = authorized_find!(project_path: project_path, iid: iid) ::Issues::UpdateService.new(issue.project, current_user, discussion_locked: locked) .execute(issue) { issue: issue, errors: errors_on_object(issue) } end end end end
24.185185
91
0.614089
abfebcd74c32a59cdd56317d5039822c572f77eb
867
# デフォルト # max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } # min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } # threads min_threads_count, max_threads_count # worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" # port ENV.fetch("PORT") { 3000 } # environment ENV.fetch("RAILS_ENV") { "development" } # pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } # plugin :tmp_restart # Pumaの設定ファイル max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } threads min_threads_count, max_threads_count port ENV.fetch("PORT") { 3000 } environment ENV.fetch("RAILS_ENV") { ENV['RACK_ENV'] || "production" } pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } workers ENV.fetch("WEB_CONCURRENCY") { 2 } preload_app! plugin :tmp_restart
43.35
79
0.739331
1d55b2db52a3743bb02c4bdc5df117dfdb845a33
281
require "vagrant" module VagrantPlugins module GuestFedora autoload :Guest, File.expand_path("../guest", __FILE__) class Plugin < Vagrant.plugin("1") name "Fedora guest" description "Fedora guest support." guest("fedora") { Guest } end end end
18.733333
59
0.661922
01862ee6b0b3b0c6e98638cebe6e7c9eafe5adb3
411
# encoding: UTF-8 require "#{File.dirname(__FILE__)}/../lib/hammer" module HammerMocks def self.included(base) base.let(:container_mock) { mock(:container, :drop_context => true) } base.let(:context_mock) { mock(:context, :conteiner => container_mock) } base.let(:component_mock) { mock(:component, :context => context_mock) } end end RSpec.configure do |config| config.mock_with :rspec end
27.4
76
0.705596
5ddca3b1b260821adc1d3f2b5459bf2460c43cf5
5,538
require 'test_helper' class RequestChangeTest < ActiveSupport::TestCase # заявка на изменение - выслана на согласование def setup @admin = users(:admin) @budget_owner = users(:budget_owner) @budget_top_owner = users(:budget_top_owner) @fo_user = users(:fo_user) current_user = @admin @request_change = request_changes(:one) # b_service # budget_owner -> budget_top_owner -> fo_user # b_nakladn_management: # parent: b_nakladn # owner: budget_top_owner # b_service: # name: Бюджет Сервисного Центра # parent: b_nakladn_management # owner: budget_owner @request_change.set_state "На согласовании", current_user end test "exists and class" do assert_instance_of RequestChange, @request_change end test "budgets owners" do assert_equal @request_change.budget.owner, users(:budget_owner) assert_equal @request_change.budget.parent.owner, users(:budget_top_owner) end # budget_owner, budget_top_owner, user_fo # при посылке на согласование - трем сотрудникам уходит на согласование # владельцам бюджетов (текущего и вышестоящего) и сотруднику ФО test "init state" do assert_equal "На согласовании", @request_change.state assert_equal 3, @request_change.request_change_signs.size end # начальный согласователь test "current confirm" do assert_equal @budget_owner, @request_change.current_sign.user assert_equal false, @request_change.is_all_confirmed? end # согласовывает первый - переходит на согласование к следующему test "do confirm first" do @request_change.sign(RequestChangeSign::CONFIRMED, @budget_owner) assert_equal false, @request_change.is_all_confirmed? assert_equal "На согласовании", @request_change.state assert_equal @budget_top_owner, @request_change.current_sign.user assert_equal RequestChangeSign::CONFIRMED, @request_change.request_change_signs[0].result end # согласовывает второй - переходит на согласование к ФО test "do confirm second" do @request_change.sign(RequestChangeSign::CONFIRMED, @budget_owner) @request_change.sign(RequestChangeSign::CONFIRMED, @budget_top_owner) assert_equal false, @request_change.is_all_confirmed? assert_equal "На согласовании", @request_change.state assert_equal @fo_user, @request_change.current_sign.user assert_equal RequestChangeSign::CONFIRMED, @request_change.request_change_signs[1].result end # согласовывает третий - заявка согласована test "do confirm third - all confirmed" do @request_change.sign(RequestChangeSign::CONFIRMED, @budget_owner) @request_change.sign(RequestChangeSign::CONFIRMED, @budget_top_owner) @request_change.sign(RequestChangeSign::CONFIRMED, @fo_user) assert_equal true, @request_change.is_all_confirmed? assert_equal true, @request_change.request_change_histories.map{|h| h.state}.include?("Согласована") assert_equal "Обработано", @request_change.state end # отклоняет первый - переходит на Отклонена test "do rejected first" do @request_change.sign(RequestChangeSign::REJECTED, @budget_owner) assert_equal "Отклонена", @request_change.state assert_equal RequestChangeSign::REJECTED, @request_change.request_change_signs[0].result end # отклонение и на редактирование test "do rejected first and edit" do @request_change.sign(RequestChangeSign::REJECTED, @budget_owner) assert_equal "Отклонена", @request_change.state @request_change.set_state "Редактируется", @budget_owner assert_equal "Редактируется", @request_change.state end # отклонение и на редактирование, и на согласование (вторая попытка) # владелец бюджета (меньше согласователей) - 2 test "do rejected first then edit and to confirm" do @request_change.sign(RequestChangeSign::REJECTED, @budget_owner) @request_change.set_state "Редактируется", @budget_owner @request_change.set_state "На согласовании", @budget_owner assert_equal "На согласовании", @request_change.state assert_equal 2, @request_change.current_signs.size end test "fot change" do fot_change = request_changes(:fot_change) assert fot_change assert_equal 1, fot_change.request_change_actions.size # '{ "state_unit_id": 109958, # "salaries": [[1,"25300.0"],[2,"25300.0"],[3,"25300.0"],[4,"25300.0"],[5,"233444"],[6,"233444"],[7,"233444"],[8,"233444"],[9,"233444"],[10,"233444"],[11,"233444"],[12,"233444"]], # "selectedStatZatrFot": 12345, # "deltaStatZatrFot": 1665152}' assert_equal 109958, fot_change.request_change_actions.first.content['state_unit_id'] fot_delta = 1_665_152 assert_equal fot_delta, fot_change.request_change_actions.first.content['deltaStatZatrFot'] assert_equal 12345, fot_change.request_change_actions.first.content['selectedStatZatrFot'] fot_stat_zatr = stat_zatrs(:fot_stat_zatr) # zp before, for - 25300 * 12 = 303600.00 st_unit = state_units(:cfo_1_fzp_next_user1) assert_equal 109958, st_unit.id assert_equal 12, st_unit.salaries.size assert_equal 303_600.00, st_unit.fzp # fot stat zatr assert fot_stat_zatr.budget.get_fot_stat_zatr assert_equal 2_000_000.00, fot_stat_zatr.budget.fot_value # fot_change fot_change.proceed(users(:admin)) # new fot 1,968,752.00 st_unit = StateUnit.find(109958) assert_equal 1_968_752.00, st_unit.fzp # fot changed assert_equal 2_000_000.00 - fot_delta.to_f, fot_change.budget.fot_value end end
36.196078
191
0.747382